Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?
IMHO
the pervasive, implicit localization in Java is its single largest design flaw. It may be intended for user interfaces, but frankly, who really uses Java for user interfaces today except for some IDEs where you can basically ignore localization because programmers aren't exactly the target audience for it. You can fix it (especially on Linux servers) by:
- export
LC_ALL=C TZ=UTC
- set your system clock to UTC
- never use localized implementations unless absolutely necessary (ie for display only)
To the Java Community Process members I recommend:
- make localized methods, not the default, but require the user to explicitly request localization.
- use
UTF-8/UTC
as the FIXED default instead because that's simply the default today. There is no reason to do something else, except if you want to produce threads like this.
I mean, come on, aren't global static variables an anti-OO pattern? Nothing else is those pervasive defaults given by some rudimentary environment variables.......
How to utilize date add function in Google spreadsheet?
You can use the DATE(Year;Month;Day) to make operations on date:
Examples:
=DATE(2013;3;8 + 30) give the result... 7 april 2013 !
=DATE(2013;3 + 15; 8) give the result... 8 june 2014 !
It's very surprising but it works...
How to insert an item into an array at a specific index (JavaScript)?
Another possible solution, with usage of Array#reduce
.
_x000D_
_x000D_
const arr = ["apple", "orange", "raspberry"];
const arr2 = [1, 2, 4];
const insert = (arr, item, index) =>
arr.reduce(function(s, a, i) {
i === index ? s.push(item, a) : s.push(a);
return s;
}, []);
console.log(insert(arr, "banana", 1));
console.log(insert(arr2, 3, 2))
_x000D_
_x000D_
_x000D_
How to select between brackets (or quotes or ...) in Vim?
Use whatever navigation key you want to get inside the parentheses, then you can use either yi(
or yi)
to copy everything within the matching parens. This also works with square brackets (e.g. yi]
) and curly braces. In addition to y
, you can also delete or change text (e.g. ci)
, di]
).
I tried this with double and single-quotes and it appears to work there as well. For your data, I do:
write (*, '(a)') 'Computed solution coefficients:'
Move cursor to the C
, then type yi'
. Move the cursor to a blank line, hit p
, and get
Computed solution coefficients:
As CMS noted, this works for visual mode selection as well - just use vi)
, vi}
, vi'
, etc.
Spark - repartition() vs coalesce()
There is a use-case for repartition >> coalesce even where the partition number decreases mentioned in @Rob's answer, that is writing data to a single file.
@Rob's answer hints in the good direction, but I think that some further explanation is needed to understand what's going on under the hood.
If you need to filter your data before writing, then repartition is much more suitable than coalesce, since coalesce will be pushed-down right before the loading operation.
For instance:
load().map(…).filter(…).coalesce(1).save()
translates to:
load().coalesce(1).map(…).filter(…).save()
This means that all your data will collapse into a single partition, where it will be filtered, losing all parallelism.
This happens even for very simple filters like column='value'
.
This does not happen with repartition: load().map(…).filter(…).repartition(1).save()
In such case, filtering happens in parallel on the original partitions.
Just to give an order of magnitude, in my case when filtering 109M rows (~105G) with ~1000 partitions after loading from a Hive table, the runtime dropped from the ~6h for coalesce(1) to ~2m for repartition(1).
The specific example is taken from this article from AirBnB, which is pretty good and covers even more aspects of repartitioning techniques in Spark.
Invalid self signed SSL cert - "Subject Alternative Name Missing"
To fix this, you need to supply an extra parameter to openssl
when you're creating the cert, basically
-sha256 -extfile v3.ext
where v3.ext
is a file like so, with %%DOMAIN%%
replaced with the same name you use as your Common Name
. More info here and over here. Note that typically you'd set the Common Name
and %%DOMAIN%%
to the domain you're trying to generate a cert for. So if it was www.mysupersite.com
, then you'd use that for both.
v3.ext
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = %%DOMAIN%%
Another note: If all you're trying to do is stop chrome from throwing errors when viewing a self signed certificate, you can can tell Chrome to ignore all SSL errors for ALL sites by starting it with a special command line option, as detailed here on SuperUser
MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes
It is a security risk to have max_allowed_packet
at higher value, as an attacker can push bigger sized packets and crash the system.
So, Optimum Value of max_allowed_packet
to be tuned and tested.
It is to better to change when required (using set global max_allowed_packet = xxx
)
than to have it as part of my.ini or my.conf.
How to change the playing speed of videos in HTML5?
You can use this code:
var vid = document.getElementById("video1");
function slowPlaySpeed() {
vid.playbackRate = 0.5;
}
function normalPlaySpeed() {
vid.playbackRate = 1;
}
function fastPlaySpeed() {
vid.playbackRate = 2;
}
CSS3 :unchecked pseudo-class
There is no :unchecked pseudo class however if you use the :checked pseudo class and the sibling selector you can differentiate between both states. I believe all of the latest browsers support the :checked pseudo class, you can find more info from this resource: http://www.whatstyle.net/articles/18/pretty_form_controls_with_css
Your going to get better browser support with jquery... you can use a click function to detect when the click happens and if its checked or not, then you can add a class or remove a class as necessary...
LINQ select in C# dictionary
This will return all the values matching your key valueTitle
subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();
How to use mouseover and mouseout in Angular 6
The Angular6 equivalent code should be:
app.component.html
<div (mouseover)="changeText=true" (mouseout)="changeText=false">
<span *ngIf="!changeText">Hide</span>
<span *ngIf="changeText">Show</span>
</div>
app.component.ts
@Component({
selector: 'app-main',
templateUrl: './app.component.html'
})
export class AppComponent {
changeText: boolean;
constructor() {
this.changeText = false;
}
}
Notice that there is no such thing as $scope
anymore as it existed in AngularJS. Its been replaced with member variables from the component class. Also, there is no scope resolution algorithm based on prototypical inheritance either - it either resolves to a component class member, or it doesn't.
How to apply Hovering on html area tag?
for complete this script , the function for draw circle ,
function drawCircle(coordon)
{
var coord = coordon.split(',');
var c = document.getElementById("myCanvas");
var hdc = c.getContext("2d");
hdc.beginPath();
hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
hdc.stroke();
}
Including a groovy script in another groovy
After some investigation I have come to the conclusion that the following approach seems the best.
some/subpackage/Util.groovy
@GrabResolver(name = 'nexus', root = 'https://local-nexus-server:8443/repository/maven-public', m2Compatible = true)
@Grab('com.google.errorprone:error_prone_annotations:2.1.3')
@Grab('com.google.guava:guava:23.0')
@GrabExclude('com.google.errorprone:error_prone_annotations')
import com.google.common.base.Strings
class Util {
void msg(int a, String b, Map c) {
println 'Message printed by msg method inside Util.groovy'
println "Print 5 asterisks using the Guava dependency ${Strings.repeat("*", 5)}"
println "Arguments are a=$a, b=$b, c=$c"
}
}
example.groovy
#!/usr/bin/env groovy
Class clazz = new GroovyClassLoader().parseClass("${new File(getClass().protectionDomain.codeSource.location.path).parent}/some/subpackage/Util.groovy" as File)
GroovyObject u = clazz.newInstance()
u.msg(1, 'b', [a: 'b', c: 'd'])
In order to run the example.groovy
script, add it to your system path and type from any directory:
example.groovy
The script prints:
Message printed by msg method inside Util.groovy
Print 5 asterisks using the Guava dependency *****
Arguments are a=1, b=b, c=[a:b, c:d]
The above example was tested in the following environment: Groovy Version: 2.4.13 JVM: 1.8.0_151 Vendor: Oracle Corporation OS: Linux
The example demonstrates the following:
- How to use a
Util
class inside a groovy script.
- A
Util
class calling the Guava
third party library by including it as a Grape
dependency (@Grab('com.google.guava:guava:23.0')
).
- The
Util
class can reside in a subdirectory.
- Passing arguments to a method within the
Util
class.
Additional comments/suggestions:
- Always use a groovy class instead of groovy script for reusable functionality within your groovy scripts. The above example uses the Util class defined in the Util.groovy file. Using groovy scripts for reusable functionality is problematic. For example, if using a groovy script then the Util class would have to be instantiated at the bottom of the script with
new Util()
, but most importantly it would have to be placed in a file named anything but Util.groovy. Refer to Scripts versus classes for more details about the differences between groovy scripts and groovy classes.
- In the above example I use the path
"${new File(getClass().protectionDomain.codeSource.location.path).parent}/some/subpackage/Util.groovy"
instead of "some/subpackage/Util.groovy"
. This will guarantee that the Util.groovy
file will always be found in relation to the groovy script's location (example.groovy
) and not the current working directory. For example, using "some/subpackage/Util.groovy"
would result in searching at WORK_DIR/some/subpackage/Util.groovy
.
- Follow the Java class naming convention to name your groovy scripts. I personally prefer a small deviation where the scripts start with a lower letter instead of a capital one. For example,
myScript.groovy
is a script name, and MyClass.groovy
is a class name. Naming my-script.groovy
will result in runtime errors in certain scenarios because the resulting class will not have a valid Java class name.
- In the JVM world in general the relevant functionality is named JSR 223: Scripting for the Java. In groovy in particular the functionality is named Groovy integration mechanisms. In fact, the same approach can be used in order to call any JVM language from within Groovy or Java. Some notable examples of such JVM languages are Groovy, Java, Scala, JRuby, and JavaScript (Rhino).
C# Telnet Library
Here is my code that is finally working
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;
class TelnetTest
{
static void Main(string[] args)
{
TelnetTest tt = new TelnetTest();
tt.tcpClient = new TcpClient("myserver", 23);
tt.ns = tt.tcpClient.GetStream();
tt.connectHost("admin", "admin");
tt.sendCommand();
tt.tcpClient.Close();
}
public void connectHost(string user, string passwd) {
bool i = true;
while (i)
{
Console.WriteLine("Connecting.....");
Byte[] output = new Byte[1024];
String responseoutput = String.Empty;
Byte[] cmd = System.Text.Encoding.ASCII.GetBytes("\n");
ns.Write(cmd, 0, cmd.Length);
Thread.Sleep(1000);
Int32 bytes = ns.Read(output, 0, output.Length);
responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
Console.WriteLine("Responseoutput: " + responseoutput);
Regex objToMatch = new Regex("login:");
if (objToMatch.IsMatch(responseoutput)) {
cmd = System.Text.Encoding.ASCII.GetBytes(user + "\r");
ns.Write(cmd, 0, cmd.Length);
}
Thread.Sleep(1000);
bytes = ns.Read(output, 0, output.Length);
responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
Console.Write(responseoutput);
objToMatch = new Regex("Password");
if (objToMatch.IsMatch(responseoutput))
{
cmd = System.Text.Encoding.ASCII.GetBytes(passwd + "\r");
ns.Write(cmd, 0, cmd.Length);
}
Thread.Sleep(1000);
bytes = ns.Read(output, 0, output.Length);
responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
Console.Write("Responseoutput: " + responseoutput);
objToMatch = new Regex("#");
if (objToMatch.IsMatch(responseoutput))
{
i = false;
}
}
Console.WriteLine("Just works");
}
}
$(document).ready not Working
function pageLoad() {
console.log('pageLoad');
$(document).ready(function () {
alert("hi");
});
};
its the ScriptManager ajax making the problem
use pageLoad() instead
php - How do I fix this illegal offset type error
check $xml->entry[$i] exists and is an object
before trying to get a property of it
if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
$source = $xml->entry[$i]->source;
$s[$source] += 1;
}
or $source might not be a legal array offset but an array, object, resource or possibly null
How to implement authenticated routes in React Router 4?
I was also looking for some answer. Here all answers are quite good, but none of them give answers how we can use it if user starts application after opening it back. (I meant to say using cookie together).
No need to create even different privateRoute Component. Below is my code
import React, { Component } from 'react';
import { Route, Switch, BrowserRouter, Redirect } from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './stores';
import requireAuth from './components/authentication/authComponent'
import SearchComponent from './components/search/searchComponent'
import LoginComponent from './components/login/loginComponent'
import ExampleContainer from './containers/ExampleContainer'
class App extends Component {
state = {
auth: true
}
componentDidMount() {
if ( ! Cookies.get('auth')) {
this.setState({auth:false });
}
}
render() {
return (
<Provider store={store}>
<BrowserRouter>
<Switch>
<Route exact path="/searchComponent" component={requireAuth(SearchComponent)} />
<Route exact path="/login" component={LoginComponent} />
<Route exact path="/" component={requireAuth(ExampleContainer)} />
{!this.state.auth && <Redirect push to="/login"/> }
</Switch>
</BrowserRouter>
</Provider>);
}
}
}
export default App;
And here is authComponent
import React from 'react';
import { withRouter } from 'react-router';
import * as Cookie from "js-cookie";
export default function requireAuth(Component) {
class AuthenticatedComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
auth: Cookie.get('auth')
}
}
componentDidMount() {
this.checkAuth();
}
checkAuth() {
const location = this.props.location;
const redirect = location.pathname + location.search;
if ( ! Cookie.get('auth')) {
this.props.history.push(`/login?redirect=${redirect}`);
}
}
render() {
return Cookie.get('auth')
? <Component { ...this.props } />
: null;
}
}
return withRouter(AuthenticatedComponent)
}
Below I have written blog, you can get more depth explanation there as well.
Create Protected routes in ReactJS
How can I add shadow to the widget in flutter?
Add box shadow to container in flutter
Container(
margin: EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)
),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 3), // changes position of shadow
),
],
),
)
Here is my output
Adding iOS UITableView HeaderView (not section header)
You can do it pretty easy in Interface Builder. Just create a view with a table and drop another view onto the table. This will become the table header view. Add your labels and image to that view. See the pic below for the view hierarchy.
Read/write to file using jQuery
You will need to handle your file access through web programming language, such as PHP or ASP.net.
To set this up, you would:
Create a script that handles the file reading and writing. This should be visible to the browser.
Send jQuery ajax requests to that script that either write data or read data. You would need to pass all of your read/write information through the request parameters. You can learn more about this in the jQuery ajax documentation.
Make sure that you sanitize any data that you are storing, since this could potentially be a security risk. However, this is really just standard flat-file data storage, and is not necessarily that unusual.
As Paolo pointed out, there is no way to directly read/write to a file through jQuery or any other type of javascript.
BackgroundWorker vs background Thread
The basic difference is, like you stated, generating GUI events from the BackgroundWorker
. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.
How to have Android Service communicate with Activity
Another way could be using observers with a fake model class through the activity and the service itself, implementing an MVC pattern variation. I don't know if it's the best way to accomplish this, but it's the way that worked for me. If you need some example ask for it and i'll post something.
Is there any way to install Composer globally on Windows?
An alternative variant (see Lusitanian answer) is to register .phar
files as executable on your system, exemplary phar.reg
file:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.phar]
@="phar_auto_file"
[HKEY_CLASSES_ROOT\phar_auto_file\shell\open\command]
@="\"c:\\PROGRA~1\\php\\php.exe\" \"%1\" %*"
Just replace the path to php.exe
to your PHP executable. You can then also extend the %PATHEXT%
commandline variable with .PHAR
which will allow you to type composer
instead of composer.phar
as long as composer.phar
is inside the %Path%
.
Get current batchfile directory
System read-only variable %CD%
keeps the path of the caller of the batch, not the batch file location.
You can get the name of the batch script itself as typed by the user with %0
(e.g. scripts\mybatch.bat
). Parameter extensions can be applied to this so %~dp0
will return the Drive and Path to the batch script (e.g. W:\scripts\
) and %~f0
will return the full pathname (e.g. W:\scripts\mybatch.cmd
).
You can refer to other files in the same folder as the batch script by using this syntax:
CALL %0\..\SecondBatch.cmd
This can even be used in a subroutine, Echo %0
will give the call label but, echo "%~nx0"
will give you the filename of the batch script.
When the %0
variable is expanded, the result is enclosed in quotation marks.
More on batch parameters.
How does the @property decorator work in Python?
I read all the posts here and realized that we may need a real life example. Why, actually, we have @property?
So, consider a Flask app where you use authentication system.
You declare a model User in models.py
:
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
...
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
In this code we've "hidden" attribute password
by using @property
which triggers AttributeError
assertion when you try to access it directly, while we used @property.setter to set the actual instance variable password_hash
.
Now in auth/views.py
we can instantiate a User with:
...
@auth.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User(email=form.email.data,
username=form.username.data,
password=form.password.data)
db.session.add(user)
db.session.commit()
...
Notice attribute password
that comes from a registration form when a user fills the form. Password confirmation happens on the front end with EqualTo('password', message='Passwords must match')
(in case if you are wondering, but it's a different topic related Flask forms).
I hope this example will be useful
Reload chart data via JSON with Highcharts
You can always load a json data
here i defined Chart as namespace
$.getJSON('data.json', function(data){
Chart.options.series[0].data = data[0].data;
Chart.options.series[1].data = data[1].data;
Chart.options.series[2].data = data[2].data;
var chart = new Highcharts.Chart(Chart.options);
});
Android Lint contentDescription warning
Disabling Lint warnings will easily get you into trouble later on. You're better off just specifying contentDescription for all of your ImageViews. If you don't need a description, then just use:
android:contentDescription="@null"
Inserting data to table (mysqli insert)
Warning: Never ever refer to w3schools for learning purposes. They have so many mistakes in their tutorials.
According to the mysqli_query documentation, the first parameter must be a connection string:
$link = mysqli_connect("localhost","root","","web_table");
mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)")
or die(mysqli_error($link));
Note: Add backticks ` for column names in your insert query as some of your column names are reserved words.
How to generate a range of numbers between two numbers?
This only works for sequences as long as some application table has rows. Assume I want sequence from 1..100, and have application table dbo.foo with column (of numeric or string type) foo.bar:
select
top 100
row_number() over (order by dbo.foo.bar) as seq
from dbo.foo
Despite its presence in an order by clause, dbo.foo.bar does not have to have distinct or even non-null values.
Of course, SQL Server 2012 has sequence objects, so there's a natural solution in that product.
How to create a fix size list in python?
Python has nothing built-in to support this. Do you really need to optimize it so much as I don't think that appending will add that much overhead.
However, you can do something like l = [None] * 1000
.
Alternatively, you could use a generator.
RecyclerView - Get view at particular position
You can simply use "findViewHolderForAdapterPosition" method of recycler view and you will get a viewHolder object from that then typecast that viewholder into your adapter viewholder so you can directly access your viewholder's views
following is the sample code for kotlin
val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
val textview=(viewHolder as YourViewHolder).yourTextView
Html helper for <input type="file" />
To use BeginForm
, here's the way to use it:
using(Html.BeginForm("uploadfiles",
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})
How do I do word Stemming or Lemmatization?
If you know Python, The Natural Language Toolkit (NLTK) has a very powerful lemmatizer that makes use of WordNet.
Note that if you are using this lemmatizer for the first time, you must download the corpus prior to using it. This can be done by:
>>> import nltk
>>> nltk.download('wordnet')
You only have to do this once. Assuming that you have now downloaded the corpus, it works like this:
>>> from nltk.stem.wordnet import WordNetLemmatizer
>>> lmtzr = WordNetLemmatizer()
>>> lmtzr.lemmatize('cars')
'car'
>>> lmtzr.lemmatize('feet')
'foot'
>>> lmtzr.lemmatize('people')
'people'
>>> lmtzr.lemmatize('fantasized','v')
'fantasize'
There are other lemmatizers in the nltk.stem module, but I haven't tried them myself.
Android ImageButton with a selected state?
Try this:
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/map_toolbar_details_selected" />
Also for colors i had success with
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:color="@color/primary_color" />
<item
android:color="@color/secondary_color" />
</selector>
Pandas How to filter a Series
As DACW pointed out, there are method-chaining improvements in pandas 0.18.1 that do what you are looking for very nicely.
Rather than using .where
, you can pass your function to either the .loc
indexer or the Series indexer []
and avoid the call to .dropna
:
test = pd.Series({
383: 3.000000,
663: 1.000000,
726: 1.000000,
737: 9.000000,
833: 8.166667
})
test.loc[lambda x : x!=1]
test[lambda x: x!=1]
Similar behavior is supported on the DataFrame and NDFrame classes.
How to set DateTime to null
This should work:
if (!string.IsNullOrWhiteSpace(dateTimeEnd))
eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
eventCustom.DateTimeEnd = null;
Note that this will throw an exception if the string is not in the correct format.
How to convert buffered image to image and vice-versa?
Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:
Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);
BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);
Import an existing git project into GitLab?
This is a basic move one repo to new location. I use this sequence all te time. With --bare no source files will be seen.
Open Git Bash.
Create a bare clone of the repository.
git clone --bare https://github.com/exampleuser/old-repository.git
Mirror-push to the new repository.
cd old-repository.git
git push --mirror https://github.com/exampleuser/new-repository.git
Remove the temporary local repository you created in step 1.
cd ../
rm -rf old-repository.git
Why mirror?
See documentation of git: https://git-scm.com/docs/git-push
--all Push all branches (i.e. refs under refs/heads/); cannot be used with other .
--mirror Instead of naming each ref to push, specifies that all refs under refs/ (which includes but is not limited to refs/heads/,
refs/remotes/, and refs/tags/) be mirrored to the remote repository.
Newly created local refs will be pushed to the remote end, locally
updated refs will be force updated on the remote end, and deleted refs
will be removed from the remote end. This is the default if the
configuration option remote..mirror is set.
How to Query an NTP Server using C#?
http://www.codeproject.com/Articles/237501/Windows-Phone-NTP-Client is going to work well for Windows Phone .
Adding the relevant code
/// <summary>
/// Class for acquiring time via Ntp. Useful for applications in which correct world time must be used and the
/// clock on the device isn't "trusted."
/// </summary>
public class NtpClient
{
/// <summary>
/// Contains the time returned from the Ntp request
/// </summary>
public class TimeReceivedEventArgs : EventArgs
{
public DateTime CurrentTime { get; internal set; }
}
/// <summary>
/// Subscribe to this event to receive the time acquired by the NTP requests
/// </summary>
public event EventHandler<TimeReceivedEventArgs> TimeReceived;
protected void OnTimeReceived(DateTime time)
{
if (TimeReceived != null)
{
TimeReceived(this, new TimeReceivedEventArgs() { CurrentTime = time });
}
}
/// <summary>
/// Not reallu used. I put this here so that I had a list of other NTP servers that could be used. I'll integrate this
/// information later and will provide method to allow some one to choose an NTP server.
/// </summary>
public string[] NtpServerList = new string[]
{
"pool.ntp.org ",
"asia.pool.ntp.org",
"europe.pool.ntp.org",
"north-america.pool.ntp.org",
"oceania.pool.ntp.org",
"south-america.pool.ntp.org",
"time-a.nist.gov"
};
string _serverName;
private Socket _socket;
/// <summary>
/// Constructor allowing an NTP server to be specified
/// </summary>
/// <param name="serverName">the name of the NTP server to be used</param>
public NtpClient(string serverName)
{
_serverName = serverName;
}
/// <summary>
///
/// </summary>
public NtpClient()
: this("time-a.nist.gov")
{ }
/// <summary>
/// Begins the network communication required to retrieve the time from the NTP server
/// </summary>
public void RequestTime()
{
byte[] buffer = new byte[48];
buffer[0] = 0x1B;
for (var i = 1; i < buffer.Length; ++i)
buffer[i] = 0;
DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
sArgsConnect.Completed += (o, e) =>
{
if (e.SocketError == SocketError.Success)
{
SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
sArgs.Completed +=
new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
sArgs.SetBuffer(buffer, 0, buffer.Length);
sArgs.UserToken = buffer;
_socket.SendAsync(sArgs);
}
};
_socket.ConnectAsync(sArgsConnect);
}
void sArgs_Completed(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
byte[] buffer = (byte[])e.Buffer;
SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs();
sArgs.RemoteEndPoint = e.RemoteEndPoint;
sArgs.SetBuffer(buffer, 0, buffer.Length);
sArgs.Completed += (o, a) =>
{
if (a.SocketError == SocketError.Success)
{
byte[] timeData = a.Buffer;
ulong hTime = 0;
ulong lTime = 0;
for (var i = 40; i <= 43; ++i)
hTime = hTime << 8 | buffer[i];
for (var i = 44; i <= 47; ++i)
lTime = lTime << 8 | buffer[i];
ulong milliseconds = (hTime * 1000 + (lTime * 1000) / 0x100000000L);
TimeSpan timeSpan =
TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
var currentTime = new DateTime(1900, 1, 1) + timeSpan;
OnTimeReceived(currentTime);
}
};
_socket.ReceiveAsync(sArgs);
}
}
}
Usage :
public partial class MainPage : PhoneApplicationPage
{
private NtpClient _ntpClient;
public MainPage()
{
InitializeComponent();
_ntpClient = new NtpClient();
_ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>(_ntpClient_TimeReceived);
}
void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
txtCurrentTime.Text = e.CurrentTime.ToLongTimeString();
txtSystemTime.Text = DateTime.Now.ToUniversalTime().ToLongTimeString();
});
}
private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)
{
_ntpClient.RequestTime();
}
}
java.lang.ClassCastException
To avoid x !instance of Long
prob
Add
<property name="openjpa.Compatibility" value="StrictIdentityValues=false"/>
in your persistence.xml
how to convert a string to a bool
I use this:
public static bool ToBoolean(this string input)
{
//Account for a string that does not need to be processed
if (string.IsNullOrEmpty(input))
return false;
return (input.Trim().ToLower() == "true") || (input.Trim() == "1");
}
$on and $broadcast in angular
First, a short description of $on()
, $broadcast()
and $emit()
:
.$on(name, listener)
- Listens for a specific event by a given name
.$broadcast(name, args)
- Broadcast an event down through the $scope
of all children
.$emit(name, args)
- Emit an event up the $scope
hierarchy to all parents, including the $rootScope
Based on the following HTML (see full example here):
<div ng-controller="Controller1">
<button ng-click="broadcast()">Broadcast 1</button>
<button ng-click="emit()">Emit 1</button>
</div>
<div ng-controller="Controller2">
<button ng-click="broadcast()">Broadcast 2</button>
<button ng-click="emit()">Emit 2</button>
<div ng-controller="Controller3">
<button ng-click="broadcast()">Broadcast 3</button>
<button ng-click="emit()">Emit 3</button>
<br>
<button ng-click="broadcastRoot()">Broadcast Root</button>
<button ng-click="emitRoot()">Emit Root</button>
</div>
</div>
The fired events will traverse the $scopes
as follows:
- Broadcast 1 - Will only be seen by Controller 1
$scope
- Emit 1 - Will be seen by Controller 1
$scope
then $rootScope
- Broadcast 2 - Will be seen by Controller 2
$scope
then Controller 3 $scope
- Emit 2 - Will be seen by Controller 2
$scope
then $rootScope
- Broadcast 3 - Will only be seen by Controller 3
$scope
- Emit 3 - Will be seen by Controller 3
$scope
, Controller 2 $scope
then $rootScope
- Broadcast Root - Will be seen by
$rootScope
and $scope
of all the Controllers (1, 2 then 3)
- Emit Root - Will only be seen by
$rootScope
JavaScript to trigger events (again, you can see a working example here):
app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.broadcastAndEmit = function(){
// This will be seen by Controller 1 $scope and all children $scopes
$scope.$broadcast('eventX', {data: '$scope.broadcast'});
// Because this event is fired as an emit (goes up) on the $rootScope,
// only the $rootScope will see it
$rootScope.$emit('eventX', {data: '$rootScope.emit'});
};
$scope.emit = function(){
// Controller 1 $scope, and all parent $scopes (including $rootScope)
// will see this event
$scope.$emit('eventX', {data: '$scope.emit'});
};
$scope.$on('eventX', function(ev, args){
console.log('eventX found on Controller1 $scope');
});
$rootScope.$on('eventX', function(ev, args){
console.log('eventX found on $rootScope');
});
}]);
Bootstrap get div to align in the center
In bootstrap you can use .text-center
to align center. also add .row
and .col-md-*
to your code.
align=
is deprecated,
Added .col-xs-*
for demo
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
<div class="container">
<div class="row">
<div class="col-xs-4">
<p>Hello there</p>
</div>
<div class="col-xs-4 text-center">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="col-xs-4 text-right">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
</div>
_x000D_
_x000D_
_x000D_
UPDATE(OCT 2017)
For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
<div class="d-flex justify-content-between">
<div class="p-1">
<p>Hello there</p>
</div>
<div class="p-1">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="p-1">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
_x000D_
_x000D_
_x000D_
WCF Service , how to increase the timeout?
The timeout configuration needs to be set at the client level, so the configuration I was setting in the web.config had no effect, the WCF test tool has its own configuration and there is where you need to set the timeout.
Vagrant ssh authentication failure
also could not get beyond:
default: SSH auth method: private key
When I used the VirtualBox GUI, it told me there was an OS processor mismatch.
To get vagrant up progressing further, in the BIOS settings I had to counter-intuitively:
Disable: Virtualisation
Enable: VT-X
Try toggling these setting in your BIOS.
How can I implement a tree in Python?
I implemented a rooted tree as a dictionary {child:parent}
. So for instance with the root node 0
, a tree might look like that:
tree={1:0, 2:0, 3:1, 4:2, 5:3}
This structure made it quite easy to go upward along a path from any node to the root, which was relevant for the problem I was working on.
jQuery events .load(), .ready(), .unload()
Also, I noticed one more difference between .load and .ready. I am opening a child window and I am performing some work when child window opens. .load is called only first time when I open the window and if I don't close the window then .load will not be called again. however, .ready is called every time irrespective of close the child window or not.
How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker
I used this approach to perform the same operation in my app.
var varDate = $("#dateStart").val();
var DateinISO = $.datepicker.parseDate('mm/dd/yy', varDate);
var DateNewFormat = $.datepicker.formatDate( "yy-mm-dd", new Date( DateinISO ) );
$("#dateStartNewFormat").val(DateNewFormat);
to remove first and last element in array
To remove the first and last element of an array is by using the built-in method of an array i.e shift()
and pop()
the fruits.shift()
get the first element of the array as "Banana" while fruits.pop()
get the last element of the array as "Mango". so the remaining element of the array will be ["Orange", "Apple"]
Mocking a function to raise an Exception to test an except block
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)
As I know, PDO_MYSQLND
replaced PDO_MYSQL
in PHP 5.3. Confusing part is that name is still PDO_MYSQL
. So now ND is default driver for MySQL+PDO.
Overall, to execute multiple queries at once you need:
- PHP 5.3+
- mysqlnd
- Emulated prepared statements. Make sure
PDO::ATTR_EMULATE_PREPARES
is set to 1
(default). Alternatively you can avoid using prepared statements and use $pdo->exec
directly.
Using exec
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
// works regardless of statements emulation
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);
$sql = "
DELETE FROM car;
INSERT INTO car(name, type) VALUES ('car1', 'coupe');
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";
$db->exec($sql);
Using statements
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
// works not with the following set to 0. You can comment this line as 1 is default
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$sql = "
DELETE FROM car;
INSERT INTO car(name, type) VALUES ('car1', 'coupe');
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";
$stmt = $db->prepare($sql);
$stmt->execute();
A note:
When using emulated prepared statements, make sure you have set proper encoding (that reflects actual data encoding) in DSN (available since 5.3.6). Otherwise there can be a slight possibility for SQL injection if some odd encoding is used.
How do I clear this setInterval inside a function?
The setInterval
method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:
function intervalTrigger() {
return window.setInterval( function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000 );
};
var id = intervalTrigger();
Then to clear the interval:
window.clearInterval(id);
Why does Java have an "unreachable statement" compiler error?
If the reason for allowing if (aBooleanVariable) return; someMoreCode;
is to allow flags, then the fact that if (true) return; someMoreCode;
does not generate a compile time error seems like inconsistency in the policy of generating CodeNotReachable exception, since the compiler 'knows' that true
is not a flag (not a variable).
Two other ways which might be interesting, but don't apply to switching off part of a method's code as well as if (true) return
:
Now, instead of saying if (true) return;
you might want to say assert false
and add -ea OR -ea package OR -ea className
to the jvm arguments. The good point is that this allows for some granularity and requires adding an extra parameter to the jvm invocation so there is no need of setting a DEBUG flag in the code, but by added argument at runtime, which is useful when the target is not the developer machine and recompiling & transferring bytecode takes time.
There is also the System.exit(0)
way, but this might be an overkill, if you put it in Java in a JSP then it will terminate the server.
Apart from that Java is by-design a 'nanny' language, I would rather use something native like C/C++ for more control.
Countdown timer in React
Countdown of user input
Interface Screenshot
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
hours: 0,
minutes: 0,
seconds:0
}
this.hoursInput = React.createRef();
this.minutesInput= React.createRef();
this.secondsInput = React.createRef();
}
inputHandler = (e) => {
this.setState({[e.target.name]: e.target.value});
}
convertToSeconds = ( hours, minutes,seconds) => {
return seconds + minutes * 60 + hours * 60 * 60;
}
startTimer = () => {
this.timer = setInterval(this.countDown, 1000);
}
countDown = () => {
const { hours, minutes, seconds } = this.state;
let c_seconds = this.convertToSeconds(hours, minutes, seconds);
if(c_seconds) {
// seconds change
seconds ? this.setState({seconds: seconds-1}) : this.setState({seconds: 59});
// minutes change
if(c_seconds % 60 === 0 && minutes) {
this.setState({minutes: minutes -1});
}
// when only hours entered
if(!minutes && hours) {
this.setState({minutes: 59});
}
// hours change
if(c_seconds % 3600 === 0 && hours) {
this.setState({hours: hours-1});
}
} else {
clearInterval(this.timer);
}
}
stopTimer = () => {
clearInterval(this.timer);
}
resetTimer = () => {
this.setState({
hours: 0,
minutes: 0,
seconds: 0
});
this.hoursInput.current.value = 0;
this.minutesInput.current.value = 0;
this.secondsInput.current.value = 0;
}
render() {
const { hours, minutes, seconds } = this.state;
return (
<div className="App">
<h1 className="title"> (( React Countdown )) </h1>
<div className="inputGroup">
<h3>Hrs</h3>
<input ref={this.hoursInput} type="number" placeholder={0} name="hours" onChange={this.inputHandler} />
<h3>Min</h3>
<input ref={this.minutesInput} type="number" placeholder={0} name="minutes" onChange={this.inputHandler} />
<h3>Sec</h3>
<input ref={this.secondsInput} type="number" placeholder={0} name="seconds" onChange={this.inputHandler} />
</div>
<div>
<button onClick={this.startTimer} className="start">start</button>
<button onClick={this.stopTimer} className="stop">stop</button>
<button onClick={this.resetTimer} className="reset">reset</button>
</div>
<h1> Timer {hours}: {minutes} : {seconds} </h1>
</div>
);
}
}
export default App;
Kendo grid date column not formatting
This is how you do it using ASP.NET:
add .Format("{0:dd/MM/yyyy HH:mm:ss}");
@(Html.Kendo().Grid<AlphaStatic.Domain.ViewModels.AttributeHistoryViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.AttributeName);
columns.Bound(c => c.UpdatedDate).Format("{0:dd/MM/yyyy HH:mm:ss}");
})
.HtmlAttributes(new { @class = ".big-grid" })
.Resizable(x => x.Columns(true))
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(c => c.Id);
})
.Read(read => read.Action("Read_AttributeHistory", "Attribute", new { attributeId = attributeId })))
)
How to use Monitor (DDMS) tool to debug application
I think that I got a solution for this. You don't have to start monitor but you can use DDMS instead almost like in Eclipse.
Start Android Studio-> pick breakpoint-> Run-> Debug-> Go to %sdk\tools in Terminal window and run ddms.bat to run DDMS without Monitor running (since it won't let you run ADB). You can now start profiling or debug step-by-step.
Hope this helps you.
See image here
How to query for Xml values and attributes from table in SQL Server?
I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.
You have it like this:
<Metrics>
<Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>
If it were like this instead:
<Metrics>
<Metric>
<id>TransactionCleanupThread.RefundOldTrans</id>
<type>timer</type>
.
.
.
Then you could simply use this SQL statement.
SELECT
Sqm.SqmId,
Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm
To me this is much less confusing than using the outer apply or cross apply.
I hope this helps someone else looking for a simpler solution!
Could not load file or assembly Exception from HRESULT: 0x80131040
I have issue with itextsharp and itextsharp.xmlworker dlls for exception-from-hresult-0x80131040 so I have removed those both dlls from references and downloaded new dlls directly from nuget packages, which resolved my issue.
May be this method can be useful to resolved the issue to other people.
How do I remove time part from JavaScript date?
This is probably the easiest way:
new Date(<your-date-object>.toDateString());
Example: To get the Current Date without time component:
new Date(new Date().toDateString());
gives:
Thu Jul 11 2019 00:00:00 GMT-0400 (Eastern Daylight Time)
Note this works universally, because toDateString()
produces date string with your browser's localization (without the time component), and the new Date()
uses the same localization to parse that date string.
What is the difference between atomic / volatile / synchronized?
Synchronized Vs Atomic Vs Volatile:
- Volatile and Atomic is apply only on variable , While Synchronized apply on method.
- Volatile ensure about visibility not atomicity/consistency of object , While other both ensure about visibility and atomicity.
- Volatile variable store in RAM and it’s faster in access but we can’t achive Thread safety or synchronization whitout synchronized keyword.
- Synchronized implemented as synchronized block or synchronized method while both not. We can thread safe multiple line of code with help of synchronized keyword while with both we can’t achieve the same.
- Synchronized can lock the same class object or different class object while both can’t.
Please correct me if anything i missed.
Bootstrap table striped: How do I change the stripe background colour?
I found this checkerboard pattern (as a subset of the zebra stripe) to be a pleasant way to display a two-column table. This is written using LESS CSS, and keys all colors off the base color.
@base-color: #0000ff;
@row-color: lighten(@base-color, 40%);
@other-row: darken(@row-color, 10%);
tbody {
td:nth-child(odd) { width: 45%; }
tr:nth-child(odd) > td:nth-child(odd) {
background: darken(@row-color, 0%); }
tr:nth-child(odd) > td:nth-child(even) {
background: darken(@row-color, 7%); }
tr:nth-child(even) > td:nth-child(odd) {
background: darken(@other-row, 0%); }
tr:nth-child(even) > td:nth-child(even) {
background: darken(@other-row, 7%); }
}
Note I've dropped the .table-striped
, but doesn't seem to matter.
Looks like:
Laravel Eloquent update just if changes have been made
You're already doing it!
save()
will check if something in the model has changed. If it hasn't it won't run a db query.
Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate
:
protected function performUpdate(Builder $query, array $options = [])
{
$dirty = $this->getDirty();
if (count($dirty) > 0)
{
// runs update query
}
return true;
}
The getDirty()
method simply compares the current attributes with a copy saved in original
when the model is created. This is done in the syncOriginal()
method:
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
public function syncOriginal()
{
$this->original = $this->attributes;
return $this;
}
If you want to check if the model is dirty just call isDirty()
:
if($product->isDirty()){
// changes have been made
}
Or if you want to check a certain attribute:
if($product->isDirty('price')){
// price has changed
}
VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323
I recently put all my source on a windows 8 32 box. Had the issues loading mscomctl.ocx
with existing projects.
I created a new project and add the common control (all). save the project and reloaded it no problem.
when you compare the project headers new vs old the old one uses reference=*\blah blah. I found removing this a replacing it with the Object={blah} sorted out the problem.
Python: Find in list
Instead of using list.index(x)
which returns the index of x if it is found in list or returns a #ValueError
message if x is not found, you could use list.count(x)
which returns the number of occurrences of x in list (validation that x is indeed in the list) or it returns 0 otherwise (in the absence of x). The cool thing about count()
is that it doesn't break your code or require you to throw an exception for when x is not found
Docker container not starting (docker start)
You are trying to run bash
, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d
, but you can do this by adding -it
to the command line, which ensures that the container has a valid tty associated with it and that stdin
remains connected:
docker run -it -d -p 52022:22 basickarl/docker-git-test
You would more commonly run some sort of long-lived non-interactive process (like sshd
, or a web server, or a database server, or a process manager like systemd
or supervisor
) when starting detached containers.
If you are trying to run a service like sshd
, you cannot simply run service ssh start
. This will -- depending on the distribution you're running inside your container -- do one of two things:
It will try to contact a process manager like systemd
or upstart
to start the service. Because there is no service manager running, this will fail.
It will actually start sshd
, but it will be started in the background. This means that (a) the service sshd start
command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.
If you want to run just ssh in a container, consider an example like this.
If you want to run sshd
and other processes inside the container, you will need to investigate some sort of process supervisor.
How to wait for the 'end' of 'resize' event and only then perform an action?
Well, as far as the window manager is concerned, each resize event is its own message, with a distinct beginning and end, so technically, every time the window is resized, it is the end.
Having said that, maybe you want to set a delay to your continuation? Here's an example.
var t = -1;
function doResize()
{
document.write('resize');
}
$(document).ready(function(){
$(window).resize(function(){
clearTimeout(t);
t = setTimeout(doResize, 1000);
});
});
Tower of Hanoi: Recursive Algorithm
Think of it as a stack with the disks diameter being represented by integers (4,3,2,1)
The first recursion call will be called 3 times and thus filling the run-time stack as follows
- first call : 1. Second call : 2,1. and third call: 3,2,1.
After the first recursion ends, the contents of the run-time stack is popped to the middle pole from largest diameter to smallest (first in last out). Next, disk with diameter 4 is moved to the destination.
The second recursion call is the same as the first with the exception of moving the elements from the middle pole to destination.
How to find the size of an int[]?
Try this:
sizeof(list) / sizeof(list[0]);
Because this question is tagged C++, it is always recommended to use std::vector
in C++ rather than using conventional C-style arrays.
An array-type
is implicitly converted into a pointer-type
when you pass it to a function.
Have a look at this.
In order to correctly print the sizeof an array inside any function, pass the array by reference to that function (but you need to know the size of that array in advance).
You would do it like so for the general case
template<typename T,int N>
//template argument deduction
int size(T (&arr1)[N]) //Passing the array by reference
{
return sizeof(arr1)/sizeof(arr1[0]); //Correctly returns the size of 'list'
// or
return N; //Correctly returns the size too [cool trick ;-)]
}
XML Schema How to Restrict Attribute by Enumeration
The numerical value seems to be missing from your price definition.
Try the following:
<xs:simpleType name="curr">
<xs:restriction base="xs:string">
<xs:enumeration value="pounds" />
<xs:enumeration value="euros" />
<xs:enumeration value="dollars" />
</xs:restriction>
</xs:simpleType>
<xs:element name="price">
<xs:complexType>
<xs:extension base="xs:decimal">
<xs:attribute name="currency" type="curr"/>
</xs:extension>
</xs:complexType>
</xs:element>
Can a Windows batch file determine its own file name?
Yes.
Use the special %0
variable to get the path to the current file.
Write %~n0
to get just the filename without the extension.
Write %~n0%~x0
to get the filename and extension.
Also possible to write %~nx0
to get the filename and extension.
How do I adb pull ALL files of a folder present in SD Card
Please try with just giving the path from where you want to pull the files
I just got the files from sdcard like
adb pull sdcard/
do NOT give * like to broaden the search or to filter out.
ex: adb pull sdcard/*.txt --> this is invalid.
just give adb pull sdcard/
How to pass command line arguments to a rake task
The ways to pass argument are correct in above answer. However to run rake task with arguments, there is a small technicality involved in newer version of rails
It will work with rake "namespace:taskname['argument1']"
Note the Inverted quotes in running the task from command line.
How to hide elements without having them take space on the page?
The answer to this question is saying to use display:none and display:block, but this does not help for someone who is trying to use css transitions to show and hide content using the visibility property.
This also drove me crazy, because using display kills any css transitions.
One solution is to add this to the class that's using visibility:
overflow:hidden
For this to work is does depend on the layout, but it should keep the empty content within the div it resides in.
Can't find file executable in your configured search path for gnc gcc compiler
For that you need to install binary of GNU GCC compiler, which comes with MinGW package. You can download MinGW( and put it under C:/ ) and later you have to download gnu -c, c++ related Binaries, so select required package and install them(in the MinGW ). Then in the Code::Blocks, go to Setting, Compiler, ToolChain Executable. In that you will find Path, there set C:/MinGW.
Then mentioned error will be vanished.
Comparing two vectors in an if statement
I'd probably use all.equal
and which
to get the information you want. It's not recommended to use all.equal
in an if...else
block for some reason, so we wrap it in isTRUE()
. See ?all.equal
for more:
foo <- function(A,B){
if (!isTRUE(all.equal(A,B))){
mismatches <- paste(which(A != B), collapse = ",")
stop("error the A and B does not match at the following columns: ", mismatches )
} else {
message("Yahtzee!")
}
}
And in use:
> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) :
error the A and B does not match at the following columns: 2,4
Setting PHP tmp dir - PHP upload not working
I struggled with this issue for a long time...
My solution was to modify the php.ini file, in the folder that contained the php script. This was important, as modifying the php.ini at the root did not resolve the problem (I have a php.ini in each folder for granular control).
The relevant entries in my php.ini looked like this.... (the output_buffering is not likely needed for this issue)
output_buffering = On
upload_max_filesize = 20M
post_max_size = 21M
How do I get the file name from a String containing the Absolute file path?
A method without any dependency and takes care of .. , . and duplicate separators.
public static String getFileName(String filePath) {
if( filePath==null || filePath.length()==0 )
return "";
filePath = filePath.replaceAll("[/\\\\]+", "/");
int len = filePath.length(),
upCount = 0;
while( len>0 ) {
//remove trailing separator
if( filePath.charAt(len-1)=='/' ) {
len--;
if( len==0 )
return "";
}
int lastInd = filePath.lastIndexOf('/', len-1);
String fileName = filePath.substring(lastInd+1, len);
if( fileName.equals(".") ) {
len--;
}
else if( fileName.equals("..") ) {
len -= 2;
upCount++;
}
else {
if( upCount==0 )
return fileName;
upCount--;
len -= fileName.length();
}
}
return "";
}
Test case:
@Test
public void testGetFileName() {
assertEquals("", getFileName("/"));
assertEquals("", getFileName("////"));
assertEquals("", getFileName("//C//.//../"));
assertEquals("", getFileName("C//.//../"));
assertEquals("C", getFileName("C"));
assertEquals("C", getFileName("/C"));
assertEquals("C", getFileName("/C/"));
assertEquals("C", getFileName("//C//"));
assertEquals("C", getFileName("/A/B/C/"));
assertEquals("C", getFileName("/A/B/C"));
assertEquals("C", getFileName("/C/./B/../"));
assertEquals("C", getFileName("//C//./B//..///"));
assertEquals("user", getFileName("/user/java/.."));
assertEquals("C:", getFileName("C:"));
assertEquals("C:", getFileName("/C:"));
assertEquals("java", getFileName("C:\\Program Files (x86)\\java\\bin\\.."));
assertEquals("C.ext", getFileName("/A/B/C.ext"));
assertEquals("C.ext", getFileName("C.ext"));
}
Maybe getFileName is a bit confusing, because it returns directory names also. It returns the name of file or last directory in a path.
Calling Web API from MVC controller
From my HomeController I want to call this Method and convert Json response to List
No you don't. You really don't want to add the overhead of an HTTP call and (de)serialization when the code is within reach. It's even in the same assembly!
Your ApiController goes against (my preferred) convention anyway. Let it return a concrete type:
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
If you don't want that and you're absolutely sure you need to return HttpResponseMessage
, then still there's absolutely no need to bother with calling JsonConvert.SerializeObject()
yourself:
return Request.CreateResponse<List<QDocumentRecord>>(HttpStatusCode.OK, listOfFiles);
Then again, you don't want business logic in a controller, so you extract that into a class that does the work for you:
public class FileListGetter
{
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
}
Either way, then you can call this class or the ApiController directly from your MVC controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var listOfFiles = new DocumentsController().GetAllRecords();
// OR
var listOfFiles = new FileListGetter().GetAllRecords();
return View(listOfFiles);
}
}
But if you really, really must do an HTTP request, you can use HttpWebRequest
, WebClient
, HttpClient
or RestSharp
, for all of which plenty of tutorials exist.
Forward declaration of a typedef in C++
I replaced the typedef
(using
to be specific) with inheritance and constructor inheritance (?).
Original
using CallStack = std::array<StackFrame, MAX_CALLSTACK_DEPTH>;
Replaced
struct CallStack // Not a typedef to allow forward declaration.
: public std::array<StackFrame, MAX_CALLSTACK_DEPTH>
{
typedef std::array<StackFrame, MAX_CALLSTACK_DEPTH> Base;
using Base::Base;
};
This way I was able to forward declare CallStack
with:
class CallStack;
Best way to deploy Visual Studio application that can run without installing
First you need to publish the file by:
BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter
NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go.
Save your file to a particular folder.
Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug
folder below the project file (.csproj).
In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files.
(You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)
NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Export pictures from excel file into jpg using VBA
Here is another cool way to do it- using en external viewer that accepts command line switches (IrfanView in this case) :
* I based the loop on what Michal Krzych has written above.
Sub ExportPicturesToFiles()
Const saveSceenshotTo As String = "C:\temp\"
Const pictureFormat As String = ".jpg"
Dim pic As Shape
Dim sFileName As String
Dim i As Long
i = 1
For Each pic In ActiveSheet.Shapes
pic.Copy
sFileName = saveSceenshotTo & Range("A" & i).Text & pictureFormat
Call ExportPicWithIfran(sFileName)
i = i + 1
Next
End Sub
Public Sub ExportPicWithIfran(sSaveAsPath As String)
Const sIfranPath As String = "C:\Program Files\IrfanView\i_view32.exe"
Dim sRunIfran As String
sRunIfran = sIfranPath & " /clippaste /convert=" & _
sSaveAsPath & " /killmesoftly"
' Shell is no good here. If you have more than 1 pic, it will
' mess things up (pics will over run other pics, becuase Shell does
' not make vba wait for the script to finish).
' Shell sRunIfran, vbHide
' Correct way (it will now wait for the batch to finish):
call MyShell(sRunIfran )
End Sub
Edit:
Private Sub MyShell(strShell As String)
' based on:
' http://stackoverflow.com/questions/15951837/excel-vba-wait-for-shell-command-to-complete
' by Nate Hekman
Dim wsh As Object
Dim waitOnReturn As Boolean:
Dim windowStyle As VbAppWinStyle
Set wsh = VBA.CreateObject("WScript.Shell")
waitOnReturn = True
windowStyle = vbHide
wsh.Run strShell, windowStyle, waitOnReturn
End Sub
Understanding ASP.NET Eval() and Bind()
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
- IntelliSense can find the correct property of the object your're working with
- If property is renamed/deleted, you will get an error before page is viewed in browser
- External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object
Source: from this excellent book
Regex to get NUMBER only from String
Either [0-9]
or \d
1 should suffice if you only need a single digit. Append +
if you need more.
1 The semantics are slightly different as \d
potentially matches any decimal digit in any script out there that uses decimal digits.
AttributeError: 'str' object has no attribute 'strftime'
You should use datetime
object, not str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'
Google Chrome "window.open" workaround?
The location=1
part should enable an editable location bar.
As a side note, you can drop the language="javascript"
attribute from your script as it is now deprecated.
update:
Setting the statusbar=1
to the correct parameter status=1
works for me
Setting the character encoding in form submit for Internet Explorer
For Russian symbols 'windows-1251'
<form action="yourProcessPage.php" method="POST" accept-charset="utf-8">
<input name="string" value="string" />
...
</form>
When simply convert string to cp1251
$string = $_POST['string'];
$string = mb_convert_encoding($string, "CP1251", "UTF-8");
NuGet Package Restore Not Working
vs2015 no enable nuget restore problem.
My solution:
add folder .nuget, add file NuGet.Config and NuGet.targets in Directory .nuget
each project file add:
build
<RestorePackages>true</RestorePackages>
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
What is the difference between ( for... in ) and ( for... of ) statements?
The for-in
loop
for-in
loop is used to traverse through enumerable properties of a collection, in an arbitrary order. A collection is a container type object whose items can be using an index or a key.
_x000D_
_x000D_
var myObject = {a: 1, b: 2, c: 3};_x000D_
var myArray = [1, 2, 3];_x000D_
var myString = "123";_x000D_
_x000D_
console.log( myObject[ 'a' ], myArray[ 1 ], myString[ 2 ] );
_x000D_
_x000D_
_x000D_
for-in
loop extracts the enumerable properties (keys) of a collection all at once and iterates over it one at a time. An enumerable property is the property of a collection that can appear in for-in
loop.
By default, all properties of an Array and Object appear in for-in
loop. However, we can use Object.defineProperty method to manually configure the properties of a collection.
_x000D_
_x000D_
var myObject = {a: 1, b: 2, c: 3};_x000D_
var myArray = [1, 2, 3];_x000D_
_x000D_
Object.defineProperty( myObject, 'd', { value: 4, enumerable: false } );_x000D_
Object.defineProperty( myArray, 3, { value: 4, enumerable: false } );_x000D_
_x000D_
for( var i in myObject ){ console.log( 'myObject:i =>', i ); }_x000D_
for( var i in myArray ){ console.log( 'myArray:i =>', i ); }
_x000D_
_x000D_
_x000D_
In the above example, the property d
of the myObject
and the index 3
of myArray
does not appear in for-in
loop because they are configured with enumerable: false
.
There are few issues with for-in
loops. In the case of Arrays, for-in
loop will also consider methods
added on the array using myArray.someMethod = f
syntax, however, myArray.length
remains 4
.
The for-of
loop
It is a misconception that for-of
loop iterate over the values of a collection. for-of
loop iterates over an Iterable
object. An iterable is an object that has the method with the name Symbol.iterator
directly on it one on one of its prototypes.
Symbol.iterator
method should return an Iterator. An iterator is an object which has a next
method. This method when called return value
and done
properties.
When we iterate an iterable object using for-of
loop, the Symbol.iterator
the method will be called once get an iterator object. For every iteration of for-of
loop, next
method of this iterator object will be called until done
returned by the next()
call returns false. The value received by the for-of
loop for every iteration if the value
property returned by the next()
call.
_x000D_
_x000D_
var myObject = { a: 1, b: 2, c: 3, d: 4 };_x000D_
_x000D_
// make `myObject` iterable by adding `Symbol.iterator` function directlty on it_x000D_
myObject[ Symbol.iterator ] = function(){_x000D_
console.log( `LOG: called 'Symbol.iterator' method` );_x000D_
var _myObject = this; // `this` points to `myObject`_x000D_
_x000D_
// return an iterator object_x000D_
return {_x000D_
keys: Object.keys( _myObject ), _x000D_
current: 0,_x000D_
next: function() {_x000D_
console.log( `LOG: called 'next' method: index ${ this.current }` );_x000D_
_x000D_
if( this.current === this.keys.length ){_x000D_
return { done: true, value: null }; // Here, `value` is ignored by `for-of` loop_x000D_
} else {_x000D_
return { done: false, value: _myObject[ this.keys[ this.current++ ] ] };_x000D_
}_x000D_
}_x000D_
};_x000D_
}_x000D_
_x000D_
// use `for-of` loop on `myObject` iterable_x000D_
for( let value of myObject ) {_x000D_
console.log( 'myObject: value => ', value );_x000D_
}
_x000D_
_x000D_
_x000D_
The for-of
loop is new in ES6 and so are the Iterable and Iterables. The Array
constructor type has Symbol.iterator
method on its prototype. The Object
constructor sadly doesn't have it but Object.keys()
, Object.values()
and Object.entries()
methods return an iterable (you can use console.dir(obj)
to check prototype methods). The benefit of the for-of
loop is that any object can be made iterable, even your custom Dog
and Animal
classes.
The easy way to make an object iterable is by implementing ES6 Generator instead of custom iterator implementation.
Unlike for-in
, for-of
loop can wait for an async task to complete in each iteration. This is achieved using await
keyword after for
statement documentation.
Another great thing about for-of
loop is that it has Unicode support. According to ES6 specifications, strings are stored with UTF-16 encoding. Hence, each character can take either 16-bit
or 32-bit
. Traditionally, strings were stored with UCS-2 encoding which has supports for characters that can be stored within 16 bits
only.
Hence, String.length
returns number of 16-bit
blocks in a string. Modern characters like an Emoji character takes 32 bits. Hence, this character would return length
of 2. for-in
loop iterates over 16-bit
blocks and returns the wrong index
. However, for-of
loop iterates over the individual character based on UTF-16 specifications.
_x000D_
_x000D_
var emoji = "";_x000D_
_x000D_
console.log( 'emoji.length', emoji.length );_x000D_
_x000D_
for( var index in emoji ){ console.log( 'for-in: emoji.character', emoji[index] ); }_x000D_
for( var character of emoji ){ console.log( 'for-of: emoji.character', character ); }
_x000D_
_x000D_
_x000D_
How to call javascript function from asp.net button click event
You're already prepending the hash sign in your showDialog()
function, and you're missing single quotes in your second code snippet. You should also return false
from the handler to prevent a postback from occurring. Try:
<asp:Button ID="ButtonAdd" runat="server" Text="Add"
OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />
Position DIV relative to another DIV?
You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo
#one
{
background-color: #EEE;
margin: 62px 258px;
padding: 5px;
width: 200px;
position: relative;
}
#two
{
background-color: #F00;
display: inline-block;
height: 30px;
position: absolute;
width: 100px;
top:10px;
}?
How to make/get a multi size .ico file?
ImageMagick, the free and open source image manipulation toolkit, can easily do this:
Note: Since ImageMagick 7, the CLI has changed slightly, you need to add magick
in front of any commands.
magick convert icon-16.png icon-32.png icon-64.png icon-128.png icon.ico
See also http://www.imagemagick.org/Usage/thumbnails/#favicon, that has the example:
magick convert image.png -bordercolor white -border 0 \
\( -clone 0 -resize 16x16 \) \
\( -clone 0 -resize 32x32 \) \
\( -clone 0 -resize 48x48 \) \
\( -clone 0 -resize 64x64 \) \
-delete 0 -alpha off -colors 256 favicon.ico
There is also now the shorter:
magick convert image.png -define icon:auto-resize="256,128,96,64,48,32,16" favicon.ico
How do I get the SharedPreferences from a PreferenceActivity in Android?
Declare these methods first..
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
Then call this when you want to put a pref:
putPref("myKey", "mystring", getApplicationContext());
call this when you want to get a pref:
getPref("myKey", getApplicationContext());
Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo
which simplifies everything even further
Example:
TinyDB tinydb = new TinyDB(context);
tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);
tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true);
tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
How to generate an openSSL key using a passphrase from the command line?
If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.
You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar
):
openssl genrsa -aes128 -passout pass:foobar 3072
However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.
A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:
openssl genrsa -aes128 -passout file:passphrase.txt 3072
Or supply the passphrase on standard input:
openssl genrsa -aes128 -passout stdin 3072
You can also used a named pipe with the file:
option, or a file descriptor.
To then obtain the matching public key, you need to use openssl rsa
, supplying the same passphrase with the -passin
parameter as was used to encrypt the private key:
openssl rsa -passin file:passphrase.txt -pubout
(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>
).
Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar
:
openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub
How to change dot size in gnuplot
The pointsize command scales the size of points, but does not affect the size of dots.
In other words, plot ... with points ps 2
will generate points of twice the normal size, but for plot ... with dots ps 2
the "ps 2
" part is ignored.
You could use circular points (pt 7
), which look just like dots.
curl_exec() always returns false
Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error()
and curl_errno()
will contain further information in case of failure:
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ($ch === false) {
throw new Exception('failed to initialize');
}
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(/* ... */);
$content = curl_exec($ch);
// Check the return value of curl_exec(), too
if ($content === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
/* Process $content here */
// Close curl handle
curl_close($ch);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
* The curl_init()
manual states:
Returns a cURL handle on success, FALSE on errors.
I've observed the function to return FALSE
when you're using its $url
parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE
. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.
Using Jquery Datatable with AngularJs
visit this link for reference:http://codepen.io/kalaiselvan/pen/RRBzda
<script>
var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope){
$scope.data=[
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011\/04\/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011\/07\/25",
"$170,750"
],
[
"Ashton Cox",
"Junior Technical Author",
"San Francisco",
"1562",
"2009\/01\/12",
"$86,000"
],
[
"Cedric Kelly",
"Senior Javascript Developer",
"Edinburgh",
"6224",
"2012\/03\/29",
"$433,060"
],
[
"Airi Satou",
"Accountant",
"Tokyo",
"5407",
"2008\/11\/28",
"$162,700"
],
[
"Brielle Williamson",
"Integration Specialist",
"New York",
"4804",
"2012\/12\/02",
"$372,000"
],
[
"Herrod Chandler",
"Sales Assistant",
"San Francisco",
"9608",
"2012\/08\/06",
"$137,500"
],
[
"Rhona Davidson",
"Integration Specialist",
"Tokyo",
"6200",
"2010\/10\/14",
"$327,900"
],
[
"Colleen Hurst",
"Javascript Developer",
"San Francisco",
"2360",
"2009\/09\/15",
"$205,500"
],
[
"Sonya Frost",
"Software Engineer",
"Edinburgh",
"1667",
"2008\/12\/13",
"$103,600"
],
[
"Jena Gaines",
"Office Manager",
"London",
"3814",
"2008\/12\/19",
"$90,560"
],
[
"Quinn Flynn",
"Support Lead",
"Edinburgh",
"9497",
"2013\/03\/03",
"$342,000"
],
[
"Charde Marshall",
"Regional Director",
"San Francisco",
"6741",
"2008\/10\/16",
"$470,600"
],
[
"Haley Kennedy",
"Senior Marketing Designer",
"London",
"3597",
"2012\/12\/18",
"$313,500"
],
[
"Tatyana Fitzpatrick",
"Regional Director",
"London",
"1965",
"2010\/03\/17",
"$385,750"
],
[
"Michael Silva",
"Marketing Designer",
"London",
"1581",
"2012\/11\/27",
"$198,500"
],
[
"Paul Byrd",
"Chief Financial Officer (CFO)",
"New York",
"3059",
"2010\/06\/09",
"$725,000"
],
[
"Gloria Little",
"Systems Administrator",
"New York",
"1721",
"2009\/04\/10",
"$237,500"
],
[
"Bradley Greer",
"Software Engineer",
"London",
"2558",
"2012\/10\/13",
"$132,000"
],
[
"Dai Rios",
"Personnel Lead",
"Edinburgh",
"2290",
"2012\/09\/26",
"$217,500"
],
[
"Jenette Caldwell",
"Development Lead",
"New York",
"1937",
"2011\/09\/03",
"$345,000"
],
[
"Yuri Berry",
"Chief Marketing Officer (CMO)",
"New York",
"6154",
"2009\/06\/25",
"$675,000"
],
[
"Caesar Vance",
"Pre-Sales Support",
"New York",
"8330",
"2011\/12\/12",
"$106,450"
],
[
"Doris Wilder",
"Sales Assistant",
"Sidney",
"3023",
"2010\/09\/20",
"$85,600"
],
[
"Angelica Ramos",
"Chief Executive Officer (CEO)",
"London",
"5797",
"2009\/10\/09",
"$1,200,000"
],
[
"Gavin Joyce",
"Developer",
"Edinburgh",
"8822",
"2010\/12\/22",
"$92,575"
],
[
"Jennifer Chang",
"Regional Director",
"Singapore",
"9239",
"2010\/11\/14",
"$357,650"
],
[
"Brenden Wagner",
"Software Engineer",
"San Francisco",
"1314",
"2011\/06\/07",
"$206,850"
],
[
"Fiona Green",
"Chief Operating Officer (COO)",
"San Francisco",
"2947",
"2010\/03\/11",
"$850,000"
],
[
"Shou Itou",
"Regional Marketing",
"Tokyo",
"8899",
"2011\/08\/14",
"$163,000"
],
[
"Michelle House",
"Integration Specialist",
"Sidney",
"2769",
"2011\/06\/02",
"$95,400"
],
[
"Suki Burks",
"Developer",
"London",
"6832",
"2009\/10\/22",
"$114,500"
],
[
"Prescott Bartlett",
"Technical Author",
"London",
"3606",
"2011\/05\/07",
"$145,000"
],
[
"Gavin Cortez",
"Team Leader",
"San Francisco",
"2860",
"2008\/10\/26",
"$235,500"
],
[
"Martena Mccray",
"Post-Sales support",
"Edinburgh",
"8240",
"2011\/03\/09",
"$324,050"
],
[
"Unity Butler",
"Marketing Designer",
"San Francisco",
"5384",
"2009\/12\/09",
"$85,675"
],
[
"Howard Hatfield",
"Office Manager",
"San Francisco",
"7031",
"2008\/12\/16",
"$164,500"
],
[
"Hope Fuentes",
"Secretary",
"San Francisco",
"6318",
"2010\/02\/12",
"$109,850"
],
[
"Vivian Harrell",
"Financial Controller",
"San Francisco",
"9422",
"2009\/02\/14",
"$452,500"
],
[
"Timothy Mooney",
"Office Manager",
"London",
"7580",
"2008\/12\/11",
"$136,200"
],
[
"Jackson Bradshaw",
"Director",
"New York",
"1042",
"2008\/09\/26",
"$645,750"
],
[
"Olivia Liang",
"Support Engineer",
"Singapore",
"2120",
"2011\/02\/03",
"$234,500"
],
[
"Bruno Nash",
"Software Engineer",
"London",
"6222",
"2011\/05\/03",
"$163,500"
],
[
"Sakura Yamamoto",
"Support Engineer",
"Tokyo",
"9383",
"2009\/08\/19",
"$139,575"
],
[
"Thor Walton",
"Developer",
"New York",
"8327",
"2013\/08\/11",
"$98,540"
],
[
"Finn Camacho",
"Support Engineer",
"San Francisco",
"2927",
"2009\/07\/07",
"$87,500"
],
[
"Serge Baldwin",
"Data Coordinator",
"Singapore",
"8352",
"2012\/04\/09",
"$138,575"
],
[
"Zenaida Frank",
"Software Engineer",
"New York",
"7439",
"2010\/01\/04",
"$125,250"
],
[
"Zorita Serrano",
"Software Engineer",
"San Francisco",
"4389",
"2012\/06\/01",
"$115,000"
],
[
"Jennifer Acosta",
"Junior Javascript Developer",
"Edinburgh",
"3431",
"2013\/02\/01",
"$75,650"
],
[
"Cara Stevens",
"Sales Assistant",
"New York",
"3990",
"2011\/12\/06",
"$145,600"
],
[
"Hermione Butler",
"Regional Director",
"London",
"1016",
"2011\/03\/21",
"$356,250"
],
[
"Lael Greer",
"Systems Administrator",
"London",
"6733",
"2009\/02\/27",
"$103,500"
],
[
"Jonas Alexander",
"Developer",
"San Francisco",
"8196",
"2010\/07\/14",
"$86,500"
],
[
"Shad Decker",
"Regional Director",
"Edinburgh",
"6373",
"2008\/11\/13",
"$183,000"
],
[
"Michael Bruce",
"Javascript Developer",
"Singapore",
"5384",
"2011\/06\/27",
"$183,000"
],
[
"Donna Snider",
"Customer Support",
"New York",
"4226",
"2011\/01\/25",
"$112,000"
]
]
$scope.dataTableOpt = {
//if any ajax call
};
});
</script>
<div class="container" ng-app="formvalid">
<div class="panel" data-ng-controller="validationCtrl">
<div class="panel-heading border">
<h2>Data table using jquery datatable in Angularjs </h2>
</div>
<div class="panel-body">
<table class="table table-bordered bordered table-striped table-condensed datatable" ui-jq="dataTable" ui-options="dataTableOpt">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="n in data">
<td>{{$index+1}}</td>
<td>{{n[0]}}</td>
<td>{{n[1]}}</td>
<td>{{n[2]}}</td>
<td>{{n[3]}}</td>
<td>{{n[4] | date:'dd/MM/yyyy'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Select query to get data from SQL Server
you have to add parameter also @zip
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();
SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
//
// Add new SqlParameter to the command.
//
command.Parameters.AddWithValue("@zip","india");
int result = (Int32) (command.ExecuteScalar());
using (SqlDataReader reader = command.ExecuteReader())
{
// iterate your results here
Console.WriteLine(String.Format("{0}",reader["id"]));
}
conn.Close();
How do I parse a URL query parameters, in Javascript?
Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
actually it's not that simple, see the peer-review in the comments, especially:
- hash based routing (@cmfolio)
- array parameters (@user2368055)
- proper use of decodeURIComponent and non-encoded
=
(@AndrewF)
- non-encoded
+
(added by me)
For further details, see MDN article and RFC 3986.
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
This function can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
Check string length in PHP
The xpath() function does not return a string. It returns an array with XML elements (of type SimpleXMLElement
), which may be casted to a string.
if (count($message)) {
if (strlen((string)$message[0]) < 141) {
echo "There Are No Contests.";
}
else if(strlen((string)$message[0]) > 142) {
echo "There is One Active Contest.";
}
}
Iterate through every file in one directory
I like this one, that hasn't been mentioned above.
require 'pathname'
Pathname.new('/my/dir').children.each do |path|
puts path
end
The benefit is that you get a Pathname object instead of a string, that you can do useful stuff with and traverse further.
UIScrollView scroll to bottom programmatically
Extend UIScrollView to add a scrollToBottom method:
extension UIScrollView {
func scrollToBottom(animated:Bool) {
let offset = self.contentSize.height - self.visibleSize.height
if offset > self.contentOffset.y {
self.setContentOffset(CGPoint(x: 0, y: offset), animated: animated)
}
}
}
Use python requests to download CSV
This should help:
import csv
import requests
CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'
with requests.Session() as s:
download = s.get(CSV_URL)
decoded_content = download.content.decode('utf-8')
cr = csv.reader(decoded_content.splitlines(), delimiter=',')
my_list = list(cr)
for row in my_list:
print(row)
Ouput sample:
['street', 'city', 'zip', 'state', 'beds', 'baths', 'sq__ft', 'type', 'sale_date', 'price', 'latitude', 'longitude']
['3526 HIGH ST', 'SACRAMENTO', '95838', 'CA', '2', '1', '836', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '59222', '38.631913', '-121.434879']
['51 OMAHA CT', 'SACRAMENTO', '95823', 'CA', '3', '1', '1167', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68212', '38.478902', '-121.431028']
['2796 BRANCH ST', 'SACRAMENTO', '95815', 'CA', '2', '1', '796', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68880', '38.618305', '-121.443839']
['2805 JANETTE WAY', 'SACRAMENTO', '95815', 'CA', '2', '1', '852', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '69307', '38.616835', '-121.439146']
[...]
Related question with answer: https://stackoverflow.com/a/33079644/295246
Edit: Other answers are useful if you need to download large files (i.e. stream=True
).
How to replace NaN value with zero in a huge data frame?
In fact, in R, this operation is very easy:
If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:
a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a
If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:
#for a data.frame:
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b
Note the difference is.nan
when it's a matrix vs. is.na
when it's a data frame.
Doing
#...
b[is.nan(b)] <- 0
#...
yields: Error in is.nan(b) : default method not implemented for type 'list'
because b is a data frame.
Note: Edited for small but confusing typos
Python 3.1.1 string to hex
In Python 3, all strings are unicode. Usually, if you encode an unicode object to a string, you use .encode('TEXT_ENCODING')
, since hex
is not a text encoding, you should use codecs.encode()
to handle arbitrary codecs. For example:
>>>> "hello".encode('hex')
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
>>>> import codecs
>>>> codecs.encode(b"hello", 'hex')
b'68656c6c6f'
Again, since "hello" is unicode, you need to indicate it as a byte string before encoding to hexadecimal. This may be more inline with what your original approach of using the encode
method.
The differences between binascii.hexlify
and codecs.encode
are as follow:
binascii.hexlify
Hexadecimal representation of binary data.
The return value is a bytes object.
Type: builtin_function_or_method
codecs.encode
encode(obj, [encoding[,errors]]) -> object
Encodes obj using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a ValueError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle ValueErrors.
Type: builtin_function_or_method
Meaning of - <?xml version="1.0" encoding="utf-8"?>
An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Virtual Library</title>
</head>
<body>
<p>Moved to <a href="http://example.org/">example.org</a>.</p>
</body>
</html>
Please refer to the W3 standards for XML.
How to move Jenkins from one PC to another
In case your JENKINS_HOME directory is too large to copy, and all you need is to set up same jobs, Jenkins Plugins and Jenkins configurations (and don't need old Job artifacts and reports), then you can use the ThinBackup Plugin:
Install ThinBackup on both the source and the target Jenkins servers
Configure the backup directory on both (in Manage Jenkins ? ThinBackup ? Settings)
On the source Jenkins, go to ThinBackup ? Backup Now
Copy from Jenkins source backup directory to the Jenkins target backup directory
On the target Jenkins, go to ThinBackup ? Restore, and then restart the Jenkins service.
If some plugins or jobs are missing, copy the backup content directly to the target JENKINS_HOME.
If you had user authentication on the source Jenkins, and now locked out on the target Jenkins, then edit Jenkins config.xml, set <useSecurity>
to false, and restart Jenkins.
How do I parse command line arguments in Bash?
Note that getopt(1)
was a short living mistake from AT&T.
getopt was created in 1984 but already buried in 1986 because it was not really usable.
A proof for the fact that getopt
is very outdated is that the getopt(1)
man page still mentions "$*"
instead of "$@"
, that was added to the Bourne Shell in 1986 together with the getopts(1)
shell builtin in order to deal with arguments with spaces inside.
BTW: if you are interested in parsing long options in shell scripts, it may be of interest to know that the getopt(3)
implementation from libc (Solaris) and ksh93
both added a uniform long option implementation that supports long options as aliases for short options. This causes ksh93
and the Bourne Shell
to implement a uniform interface for long options via getopts
.
An example for long options taken from the Bourne Shell man page:
getopts "f:(file)(input-file)o:(output-file)" OPTX "$@"
shows how long option aliases may be used in both Bourne Shell and ksh93.
See the man page of a recent Bourne Shell:
http://schillix.sourceforge.net/man/man1/bosh.1.html
and the man page for getopt(3) from OpenSolaris:
http://schillix.sourceforge.net/man/man3c/getopt.3c.html
and last, the getopt(1) man page to verify the outdated $*:
http://schillix.sourceforge.net/man/man1/getopt.1.html
Math operations from string
You could use this function which is doing the same as the eval()
function, but in a simple manner, using a function.
def numeric(equation):
if '+' in equation:
y = equation.split('+')
x = int(y[0])+int(y[1])
elif '-' in equation:
y = equation.split('-')
x = int(y[0])-int(y[1])
return x
Javascript/Jquery Convert string to array
check this out :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
?for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}?
How to call code behind server method from a client side JavaScript function?
In my projects, we usually call server side method like this:
in JavaScript:
document.getElementById("UploadButton").click();
Server side control:
<asp:Button runat="server" ID="UploadButton" Text="" style="display:none;" OnClick="UploadButton_Click" />
C#:
protected void Upload_Click(object sender, EventArgs e)
{
}
Transpose a data frame
You'd better not transpose the data.frame while the name column is in it - all numeric values will then be turned into strings!
Here's a solution that keeps numbers as numbers:
# first remember the names
n <- df.aree$name
# transpose all but the first column (name)
df.aree <- as.data.frame(t(df.aree[,-1]))
colnames(df.aree) <- n
df.aree$myfactor <- factor(row.names(df.aree))
str(df.aree) # Check the column types
Link to all Visual Studio $ variables
Ok, I finally wanted to have a pretty complete, searchable list of those variables for reference. Here is a complete (OCR-generated, as I did not easily find something akin to a printenv
command) list of defined variables for a Visual C++ project on my machine. Probably not all macros are defined for others (e.g. OCTAVE_EXECUTABLE
), but I wanted to err on the side of inclusiveness here.
For example, this is the first time that I see $(Language)
(expanding to C++
for this project) being mentioned outside of the IDE.
$(AllowLocalNetworkLoopback)
$(ALLUSERSPROFILE)
$(AndroidTargetsPath)
$(APPDATA)
$(AppxManifestMetadataClHostArchDir)
$(AppxManifestMetadataCITargetArchDir)
$(Attach)
$(BaseIntermediateOutputPath)
$(BuildingInsideVisualStudio)
$(CharacterSet)
$(CLRSupport)
$(CommonProgramFiles)
$(CommonProgramW6432)
$(COMPUTERNAME)
$(ComSpec)
$(Configuration)
$(ConfigurationType)
$(CppWinRT_IncludePath)
$(CrtSDKReferencelnclude)
$(CrtSDKReferenceVersion)
$(CustomAfterMicrosoftCommonProps)
$(CustomBeforeMicrosoftCommonProps)
$(DebugCppRuntimeFilesPath)
$(DebuggerFlavor)
$(DebuggerLaunchApplication)
$(DebuggerRequireAuthentication)
$(DebuggerType)
$(DefaultLanguageSourceExtension)
$(DefaultPlatformToolset)
$(DefaultWindowsSDKVersion)
$(DefineExplicitDefaults)
$(DelayImplib)
$(DesignTimeBuild)
$(DevEnvDir)
$(DocumentLibraryDependencies)
$(DotNetSdk_IncludePath)
$(DotNetSdk_LibraryPath)
$(DotNetSdk_LibraryPath_arm)
$(DotNetSdk_LibraryPath_arm64)
$(DotNetSdk_LibraryPath_x64)
$(DotNetSdk_LibraryPath_x86)
$(DotNetSdkRoot)
$(DriverData)
$(EmbedManifest)
$(EnableManagedIncrementalBuild)
$(EspXtensions)
$(ExcludePath)
$(ExecutablePath)
$(ExtensionsToDeleteOnClean)
$(FPS_BROWSER_APP_PROFILE_STRING)
$(FPS_BROWSER_USER_PROFILE_STRING)
$(FrameworkDir)
$(FrameworkDir_110)
$(FrameworkSdkDir)
$(FrameworkSDKRoot)
$(FrameworkVersion)
$(GenerateManifest)
$(GPURefDebuggerBreakOnAllThreads)
$(HOMEDRIVE)
$(HOMEPATH)
$(IgnorelmportLibrary)
$(ImportByWildcardAfterMicrosoftCommonProps)
$(ImportByWildcardBeforeMicrosoftCommonProps)
$(ImportDirectoryBuildProps)
$(ImportProjectExtensionProps)
$(ImportUserLocationsByWildcardAfterMicrosoftCommonProps)
$(ImportUserLocationsByWildcardBeforeMicrosoftCommonProps)
$(IncludePath)
$(IncludeVersionInInteropName)
$(IntDir)
$(InteropOutputPath)
$(iOSTargetsPath)
$(Keyword)
$(KIT_SHARED_IncludePath)
$(LangID)
$(LangName)
$(Language)
$(LIBJABRA_TRACE_LEVEL)
$(LibraryPath)
$(LibraryWPath)
$(LinkCompiled)
$(LinkIncremental)
$(LOCALAPPDATA)
$(LocalDebuggerAttach)
$(LocalDebuggerDebuggerlType)
$(LocalDebuggerMergeEnvironment)
$(LocalDebuggerSQLDebugging)
$(LocalDebuggerWorkingDirectory)
$(LocalGPUDebuggerTargetType)
$(LOGONSERVER)
$(MicrosoftCommonPropsHasBeenImported)
$(MpiDebuggerCleanupDeployment)
$(MpiDebuggerDebuggerType)
$(MpiDebuggerDeployCommonRuntime)
$(MpiDebuggerNetworkSecurityMode)
$(MpiDebuggerSchedulerNode)
$(MpiDebuggerSchedulerTimeout)
$(MSBuild_ExecutablePath)
$(MSBuildAllProjects)
$(MSBuildAssemblyVersion)
$(MSBuildBinPath)
$(MSBuildExtensionsPath)
$(MSBuildExtensionsPath32)
$(MSBuildExtensionsPath64)
$(MSBuildFrameworkToolsPath)
$(MSBuildFrameworkToolsPath32)
$(MSBuildFrameworkToolsPath64)
$(MSBuildFrameworkToolsRoot)
$(MSBuildLoadMicrosoftTargetsReadOnly)
$(MSBuildNodeCount)
$(MSBuildProgramFiles32)
$(MSBuildProjectDefaultTargets)
$(MSBuildProjectDirectory)
$(MSBuildProjectDirectoryNoRoot)
$(MSBuildProjectExtension)
$(MSBuildProjectExtensionsPath)
$(MSBuildProjectFile)
$(MSBuildProjectFullPath)
$(MSBuildProjectName)
$(MSBuildRuntimeType)
$(MSBuildRuntimeVersion)
$(MSBuildSDKsPath)
$(MSBuildStartupDirectory)
$(MSBuildToolsPath)
$(MSBuildToolsPath32)
$(MSBuildToolsPath64)
$(MSBuildToolsRoot)
$(MSBuildToolsVersion)
$(MSBuildUserExtensionsPath)
$(MSBuildVersion)
$(MultiToolTask)
$(NETFXKitsDir)
$(NETFXSDKDir)
$(NuGetProps)
$(NUMBER_OF_PROCESSORS)
$(OCTAVE_EXECUTABLE)
$(OneDrive)
$(OneDriveCommercial)
$(OS)
$(OutDir)
$(OutDirWasSpecified)
$(OutputType)
$(Path)
$(PATHEXT)
$(PkgDefApplicationConfigFile)
$(Platform)
$(Platform_Actual)
$(PlatformArchitecture)
$(PlatformName)
$(PlatformPropsFound)
$(PlatformShortName)
$(PlatformTarget)
$(PlatformTargetsFound)
$(PlatformToolset)
$(PlatformToolsetVersion)
$(PostBuildEventUseInBuild)
$(PreBuildEventUseInBuild)
$(PreferredToolArchitecture)
$(PreLinkEventUselnBuild)
$(PROCESSOR_ARCHITECTURE)
$(PROCESSOR_ARCHITEW6432)
$(PROCESSOR_IDENTIFIER)
$(PROCESSOR_LEVEL)
$(PROCESSOR_REVISION)
$(ProgramData)
$(ProgramFiles)
$(ProgramW6432)
$(ProjectDir)
$(ProjectExt)
$(ProjectFileName)
$(ProjectGuid)
$(ProjectName)
$(ProjectPath)
$(PSExecutionPolicyPreference)
$(PSModulePath)
$(PUBLIC)
$(ReferencePath)
$(RemoteDebuggerAttach)
$(RemoteDebuggerConnection)
$(RemoteDebuggerDebuggerlype)
$(RemoteDebuggerDeployDebugCppRuntime)
$(RemoteDebuggerServerName)
$(RemoteDebuggerSQLDebugging)
$(RemoteDebuggerWorkingDirectory)
$(RemoteGPUDebuggerTargetType)
$(RetargetAlwaysSupported)
$(RootNamespace)
$(RoslynTargetsPath)
$(SDK35ToolsPath)
$(SDK40ToolsPath)
$(SDKDisplayName)
$(SDKIdentifier)
$(SDKVersion)
$(SESSIONNAME)
$(SolutionDir)
$(SolutionExt)
$(SolutionFileName)
$(SolutionName)
$(SolutionPath)
$(SourcePath)
$(SpectreMitigation)
$(SQLDebugging)
$(SystemDrive)
$(SystemRoot)
$(TargetExt)
$(TargetFrameworkVersion)
$(TargetName)
$(TargetPlatformMinVersion)
$(TargetPlatformVersion)
$(TargetPlatformWinMDLocation)
$(TargetUniversalCRTVersion)
$(TEMP)
$(TMP)
$(ToolsetPropsFound)
$(ToolsetTargetsFound)
$(UCRTContentRoot)
$(UM_IncludePath)
$(UniversalCRT_IncludePath)
$(UniversalCRT_LibraryPath_arm)
$(UniversalCRT_LibraryPath_arm64)
$(UniversalCRT_LibraryPath_x64)
$(UniversalCRT_LibraryPath_x86)
$(UniversalCRT_PropsPath)
$(UniversalCRT_SourcePath)
$(UniversalCRTSdkDir)
$(UniversalCRTSdkDir_10)
$(UseDebugLibraries)
$(UseLegacyManagedDebugger)
$(UseOfATL)
$(UseOfMfc)
$(USERDOMAIN)
$(USERDOMAIN_ROAMINGPROFILE)
$(USERNAME)
$(USERPROFILE)
$(UserRootDir)
$(VBOX_MSI_INSTALL_PATH)
$(VC_ATLMFC_IncludePath)
$(VC_ATLMFC_SourcePath)
$(VC_CRT_SourcePath)
$(VC_ExecutablePath_ARM)
$(VC_ExecutablePath_ARM64)
$(VC_ExecutablePath_x64)
$(VC_ExecutablePath_x64_ARM)
$(VC_ExecutablePath_x64_ARM64)
$(VC_ExecutablePath_x64_x64)
$(VC_ExecutablePath_x64_x86)
$(VC_ExecutablePath_x86)
$(VC_ExecutablePath_x86_ARM)
$(VC_ExecutablePath_x86_ARM64)
$(VC_ExecutablePath_x86_x64)
$(VC_ExecutablePath_x86_x86)
$(VC_IFCPath)
$(VC_IncludePath)
$(VC_LibraryPath_ARM)
$(VC_LibraryPath_ARM64)
$(VC_LibraryPath_ATL_ARM)
$(VC_LibraryPath_ATL_ARM64)
$(VC_LibraryPath_ATL_x64)
$(VC_LibraryPath_ATL_x86)
$(VC_LibraryPath_VC_ARM)
$(VC_LibraryPath_VC_ARM_Desktop)
$(VC_LibraryPath_VC_ARM_OneCore)
$(VC_LibraryPath_VC_ARM_Store)
$(VC_LibraryPath_VC_ARM64)
$(VC_LibraryPath_VC_ARM64_Desktop)
$(VC_LibraryPath_VC_ARM64_OneCore)
$(VC_LibraryPath_VC_ARM64_Store)
$(VC_LibraryPath_VC_x64)
$(VC_LibraryPath_VC_x64_Desktop)
$(VC_LibraryPath_VC_x64_OneCore)
$(VC_LibraryPath_VC_x64_Store)
$(VC_LibraryPath_VC_x86)
$(VC_LibraryPath_VC_x86_Desktop)
$(VC_LibraryPath_VC_x86_OneCore)
$(VC_LibraryPath_VC_x86_Store)
$(VC_LibraryPath_x64)
$(VC_LibraryPath_x86)
$(VC_PGO_RunTime_Dir)
$(VC_ReferencesPath_ARM)
$(VC_ReferencesPath_ARM64)
$(VC_ReferencesPath_ATL_ARM)
$(VC_ReferencesPath_ATL_ARM64)
$(VC_ReferencesPath_ATL_x64)
$(VC_ReferencesPath_ATL_x86)
$(VC_ReferencesPath_VC_ARM)
$(VC_ReferencesPath_VC_ARM64)
$(VC_ReferencesPath_VC_x64)
$(VC_ReferencesPath_VC_x86)
$(VC_ReferencesPath_x64)
$(VC_ReferencesPath_x86)
$(VC_SourcePath)
$(VC_VC_IncludePath)
$(VC_VS_IncludePath)
$(VC_VS_LibraryPath_VC_VS_ARM)
$(VC_VS_LibraryPath_VC_VS_x64)
$(VC_VS_LibraryPath_VC_VS_x86)
$(VC_VS_SourcePath)
$(VCIDEInstallDir)
$(VCIDEInstallDir_150)
$(VCInstallDir)
$(VCInstallDir_150)
$(VCLibPackagePath)
$(VCProjectVersion)
$(VCTargetsPath)
$(VCTargetsPath10)
$(VCTargetsPath11)
$(VCTargetsPath12)
$(VCTargetsPath14)
$(VCTargetsPath15)
$(VCTargetsPathActual)
$(VCTargetsPathEffective)
$(VCToolArchitecture)
$(VCToolsInstallDir)
$(VCToolsInstallDir_150)
$(VCToolsVersion)
$(VisualStudioDir)
$(VisualStudioEdition)
$(VisualStudioVersion)
$(VS_ExecutablePath)
$(VS140COMNTOOLS)
$(VSAPPIDDIR)
$(VSAPPIDNAME)
$(VSInstallDir)
$(VSInstallDir_150)
$(VsInstallRoot)
$(VSLANG)
$(VSSKUEDITION)
$(VSVersion)
$(WDKBinRoot)
$(WebBrowserDebuggerDebuggerlype)
$(WebServiceDebuggerDebuggerlype)
$(WebServiceDebuggerSQLDebugging)
$(WholeProgramOptimization)
$(WholeProgramOptimizationAvailabilityInstrument)
$(WholeProgramOptimizationAvailabilityOptimize)
$(WholeProgramOptimizationAvailabilityTrue)
$(WholeProgramOptimizationAvailabilityUpdate)
$(windir)
$(Windows81SdkInstalled)
$(WindowsAppContainer)
$(WindowsSDK_ExecutablePath)
$(WindowsSDK_ExecutablePath_arm)
$(WindowsSDK_ExecutablePath_arm64)
$(WindowsSDK_ExecutablePath_x64)
$(WindowsSDK_LibraryPath_x86)
$(WindowsSDK_MetadataFoundationPath)
$(WindowsSDK_MetadataPath)
$(WindowsSDK_MetadataPathVersioned)
$(WindowsSDK_PlatformPath)
$(WindowsSDK_SupportedAPIs_arm)
$(WindowsSDK_SupportedAPIs_x64)
$(WindowsSDK_SupportedAPIs_x86)
$(WindowsSDK_UnionMetadataPath)
$(WindowsSDK80Path)
$(WindowsSdkDir)
$(WindowsSdkDir_10)
$(WindowsSdkDir_81)
$(WindowsSdkDir_81A)
$(WindowsSDKToolArchitecture)
$(WindowsTargetPlatformVersion)
$(WinRT_IncludePath)
$(WMSISProject)
$(WMSISProjectDirectory)
Where to find this list within Visual Studio:
- Open your C++ project's dialogue Property Pages
- Select any textual field that can use a configuration variable. (in the screenshot, I use Target Name)
- On the right side of the text box, click the small combobox button and select option
<Edit...>
.
- In the new window (here, title is Target Name), click on button
Macros>>
.
- Scroll through the giant list of environment/linker/macro variables.
Motivational screenshot:
Password must have at least one non-alpha character
A simple method will be like this:
Match match1 = Regex.Match(<input_string>, @"(?=.{7})");
match1.Success ensures that there are at least 8 characters.
Match match2 = Regex.Match(<input_string>, [^a-zA-Z]);
match2.Success ensures that there is at least one special character or number within the string.
So, match1.Success && match2.Success guarantees will get what you want.
Mongoimport of json file
In windows you can use your Command Prompcmd cmd
, in Ubuntu you can use your terminal
by typing the following command:
mongoimport -d your_database_name -c your_collection_name /path_to_json_file/json_file_name.json
then when you open your mongo shell, you will find to check your database_name when running this command:
show databases
Manually install Gradle and use it in Android Studio
Assume, you have installed the latest gradle once. But, If your particular project gradle version not match with the gradle version that already installed in the machine, the gradle sycn want to download that version. To prevent this download there is one trick. First You have to know the gradle version that already installed in your machine. Go to : C:\Users{username}.gradle\wrapper\dists, here you see the versions allready installed, remember the latest version, assume it is gradle-6.1.1-all.zip . Now, come back to Android Studio. In your Opened project, navigate Android Studio's project tree, open the file gradle/wrapper/gradle-wrapper.properties. Change this entry:
distributionUrl=http\://services.gradle.org/distributions/gradle-6.1.1-all.zip
This way we prevent downloading the gradle again and again. But avoid this thing, if the version really old. If that, you will find this warning :
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.1.1/userguide/command_line_interface.html#sec:command_line_warnings
Can I get Unix's pthread.h to compile in Windows?
pthread.h
is a header for the Unix/Linux (POSIX) API for threads. A POSIX layer such as Cygwin would probably compile an app with #include <pthreads.h>
.
The native Windows threading API is exposed via #include <windows.h>
and it works slightly differently to Linux's threading.
Still, there's a replacement "glue" library maintained at http://sourceware.org/pthreads-win32/ ; note that it has some slight incompatibilities with MinGW/VS (e.g. see here).
Good way to encapsulate Integer.parseInt()
To avoid an exception, you can use Java's Format.parseObject
method. The code below is basically a simplified version of Apache Common's IntegerValidator class.
public static boolean tryParse(String s, int[] result)
{
NumberFormat format = NumberFormat.getIntegerInstance();
ParsePosition position = new ParsePosition(0);
Object parsedValue = format.parseObject(s, position);
if (position.getErrorIndex() > -1)
{
return false;
}
if (position.getIndex() < s.length())
{
return false;
}
result[0] = ((Long) parsedValue).intValue();
return true;
}
You can either use AtomicInteger
or the int[]
array trick depending upon your preference.
Here is my test that uses it -
int[] i = new int[1];
Assert.assertTrue(IntUtils.tryParse("123", i));
Assert.assertEquals(123, i[0]);
How do I find the PublicKeyToken for a particular dll?
Answer is very simple use the .NET Framework tools sn.exe
. So open the Visual Studio 2008 Command Prompt and then point to the dll’s folder you want to get the public key,
Use the following command,
sn –T myDLL.dll
This will give you the public key token. Remember one thing this only works if the assembly has to be strongly signed.
Example
C:\WINNT\Microsoft.NET\Framework\v3.5>sn -T EdmGen.exe
Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Public key token is b77a5c561934e089
How to get the value from the GET parameters?
window.location.href.split("?")
then disregard the first index
Array.prototype.slice.call(window.location.href.split("?"), 1)
returns an array of your url parameters
var paramArray = Array.prototype.slice.call(window.location.href.split(/[?=]+/), 1);
var paramObject = paramArray.reduce(function(x, y, i, a){ (i%2==0) ? (x[y] = a[i+1]) : void 0; return x; }, {});
A bit more verbose/hacky but also functional, paramObject contains all parameters mapped as a js object
fork() child and parent processes
It is printing the statement twice because it is printing it for both the parent and the child. The parent has a parent id of 0
Try something like this:
pid_t pid;
pid = fork();
if (pid == 0)
printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid());
else
printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid() );
How to find topmost view controller on iOS
you could find the top most view controller by using
NSArray *arrViewControllers=[[self navigationController] viewControllers];
UIViewController *topMostViewController=(UIViewController *)[arrViewControllers objectAtIndex:[arrViewControllers count]-1];
Capturing image from webcam in java?
http://grack.com/downloads/school/enel619.10/report/java_media_framework.html
Using the Player with Swing
The Player can be easily used in a Swing application as well. The following code creates a Swing-based TV capture program with the video output displayed in the entire window:
import javax.media.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.event.*;
public class JMFTest extends JFrame {
Player _player;
JMFTest() {
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
_player.stop();
_player.deallocate();
_player.close();
System.exit( 0 );
}
});
setExtent( 0, 0, 320, 260 );
JPanel panel = (JPanel)getContentPane();
panel.setLayout( new BorderLayout() );
String mediaFile = "vfw://1";
try {
MediaLocator mlr = new MediaLocator( mediaFile );
_player = Manager.createRealizedPlayer( mlr );
if (_player.getVisualComponent() != null)
panel.add("Center", _player.getVisualComponent());
if (_player.getControlPanelComponent() != null)
panel.add("South", _player.getControlPanelComponent());
}
catch (Exception e) {
System.err.println( "Got exception " + e );
}
}
public static void main(String[] args) {
JMFTest jmfTest = new JMFTest();
jmfTest.show();
}
}
What is the SQL command to return the field names of a table?
Just for completeness, since MySQL and Postgres have already been mentioned: With SQLite, use "pragma table_info()
"
sqlite> pragma table_info('table_name');
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 id integer 99 1
1 name 0 0
What is an opaque response, and what purpose does it serve?
javascript is a bit tricky getting the answer, I fixed it by getting the api from the backend and then calling it to the frontend.
public function get_typechange () {
$ url = "https://........";
$ json = file_get_contents ($url);
$ data = json_decode ($ json, true);
$ resp = json_encode ($data);
$ error = json_last_error_msg ();
return $ resp;
}
Edit and Continue: "Changes are not allowed when..."
Couple of things to check
- Make sure your compile is set to Debug vs. Release
- Make sure you're not launching a mixed mode process
- If on a 64 bit machine Make sure to set the CPU target to x86 rather than AnyCPU
EDIT
I don't believe this should matter but make sure that the hosting process is enabled for the target platform. Probably won't help.
If it repros for new projects then it might be something even more subtle. I would try the following.
- Backup HKCU:\Software\Wow6432Node\VisualStudio\9.0 (maybe just rename it)
- Delete the same key
- Try the repro again
What are NR and FNR and what does "NR==FNR" imply?
In awk, FNR
refers to the record number (typically the line number) in the current file and NR
refers to the total record number. The operator ==
is a comparison operator, which returns true when the two surrounding operands are equal.
This means that the condition NR==FNR
is only true for the first file, as FNR
resets back to 1 for the first line of each file but NR
keeps on increasing.
This pattern is typically used to perform actions on only the first file. The next
inside the block means any further commands are skipped, so they are only run on files other than the first.
The condition FNR==NR
compares the same two operands as NR==FNR
, so it behaves in the same way.
Best way to store passwords in MYSQL database
Passwords in the database should be stored encrypted.
One way encryption (hashing) is recommended, such as SHA2, SHA2, WHIRLPOOL, bcrypt
DELETED: MD5 or SHA1. (those are older, vulnerable
In addition to that you can use additional per-user generated random string - 'salt':
$salt = MD5($this->createSalt());
$Password = SHA2($postData['Password'] . $salt);
createSalt()
in this case is a function that generates a string from random characters.
EDIT:
or if you want more security, you can even add 2 salts:
$salt1 . $pass . $salt2
Another security measure you can take is user inactivation: after 5 (or any other number) incorrect login attempts user is blocked for x minutes (15 mins lets say).
It should minimize success of brute force attacks.
What's the advantage of a Java enum versus a class with public static final fields?
Main reason: Enums help you to write well-structured code where the semantic meaning of parameters is clear and strongly-typed at compile time - for all the reasons other answers have given.
Quid pro quo: in Java out of the box, an Enum's array of members is final. That's normally good as it helps value safety and testing, but in some situations it could be a drawback, for example if you are extending existing base code perhaps from a library. In contrast, if the same data is in a class with static fields you can easily add new instances of that class at runtime (you might also need to write code to add these to any Iterable you have for that class). But this behaviour of Enums can be changed: using reflection you can add new members at runtime or replace existing members, though this should probably only be done in specialised situations where there is no alternative: i.e. it's a hacky solution and may produce unexpected issues, see my answer on Can I add and remove elements of enumeration at runtime in Java.
How to copy part of an array to another array in C#?
In case if you want to implement your own Array.Copy method.
Static method which is of generic type.
static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;
//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}
Boundary method implementation.
private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}
How to position a DIV in a specific coordinates?
I cribbed this and added the 'px';
Works very well.
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: (el.right + window.scrollX ) +'px',
top: (el.top + window.scrollY ) +'px'
}
}
to call: //Gets it to the right side
el.style.top = getOffset(othis).top ;
el.style.left = getOffset(othis).left ;
execute function after complete page load
I'm little bit confuse that what you means by page load completed, "DOM Load" or "Content Load" as well? In a html page load can fire event after two type event.
DOM load: Which ensure the entire DOM tree loaded start to end. But not ensure load the reference content. Suppose you added images by the img
tags, so this event ensure that all the img
loaded but no the images properly loaded or not. To get this event you should write following way:
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
Or using jQuery:
$(document).ready(function(){
// your code
});
After DOM and Content Load: Which indicate the the DOM and Content load as well. It will ensure not only img
tag it will ensure also all images or other relative content loaded. To get this event you should write following way:
window.addEventListener('load', function() {...})
Or using jQuery:
$(window).on('load', function() {
console.log('All assets are loaded')
})
CSS change button style after click
If you're looking for a pure css option, try using the :focus pseudo class.
#style {
background-color: red;
}
#style:focus {
background-color:yellow;
}
WPF: Setting the Width (and Height) as a Percentage Value
I use two methods for relative sizing. I have a class called Relative
with three attached properties To
, WidthPercent
and HeightPercent
which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.
The other approach is rather more cunning. Add a ViewBox
where you want relative sizes inside, then inside that, add a Grid
at width 100. Then if you add a TextBlock
with width 10 inside that, it is obviously 10% of 100.
The ViewBox
will scale the Grid
according to whatever space it has been given, so if its the only thing on the page, then the Grid
will be scaled out full width and effectively, your TextBlock
is scaled to 10% of the page.
If you don't set a height on the Grid
then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox
else it will start scaling the height as well. You can probably work around this with a Stretch
of UniformToFill
.
Javascript: getFullyear() is not a function
One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:
> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function
Had you used the 'new' keyword, it would have looked like this:
> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016
Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:
el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function
How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"
Visual Studio Community 2017
Go here :
C:\Program Files (x86)\Windows Kits\10
and do whatever you were supposed to go in the given directory for VS 13.
in the lib folder, you will find some versions, I copied the 32-bit glut.lib files in amd and x86 and 64-bit glut.lib in arm64 and x64 directories in um
folder for every version that I could find.
That worked for me.
EDIT : I tried this in windows 10, maybe you need to go to C:\Program Files (x86)\Windows Kits\8.1
folder for windows 8/8.1.
How to set menu to Toolbar in Android
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar;
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_drawer,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_drawer){
drawerLayout.openDrawer(GravityCompat.END);
if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.closeDrawer(GravityCompat.END);
} else {
drawerLayout.openDrawer(GravityCompat.END);
}
}
return super.onOptionsItemSelected(item);
}
res/layout/drawer_menu
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_drawer"
android:title="@string/app_name"
android:icon="@drawable/ic_menu_black_24dp"
app:showAsAction="always"/>
</menu>
toolbar.xml
<com.google.android.material.appbar.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:titleTextColor="@android:color/white"
app:titleTextAppearance="@style/TextAppearance.Widget.Event.Toolbar.Title">
<TextView
android:id="@+id/toolbar_title"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/app_name"
android:textColor="@android:color/white"
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title" />
</androidx.appcompat.widget.Toolbar>
How is a CRC32 checksum calculated?
For IEEE802.3, CRC-32. Think of the entire message as a serial bit stream, append 32 zeros to the end of the message. Next, you MUST reverse the bits of EVERY byte of the message and do a 1's complement the first 32 bits. Now divide by the CRC-32 polynomial, 0x104C11DB7. Finally, you must 1's complement the 32-bit remainder of this division bit-reverse each of the 4 bytes of the remainder. This becomes the 32-bit CRC that is appended to the end of the message.
The reason for this strange procedure is that the first Ethernet implementations would serialize the message one byte at a time and transmit the least significant bit of every byte first. The serial bit stream then went through a serial CRC-32 shift register computation, which was simply complemented and sent out on the wire after the message was completed. The reason for complementing the first 32 bits of the message is so that you don't get an all zero CRC even if the message was all zeros.
Getting the error "Missing $ inserted" in LaTeX
I had this problem too. I solved it by removing the unnecessary blank line between equation tags. This gives the error:
\begin{equation}
P(\underline{\hat{X}} | \underline{Y}) = ...
\end{equation}
while this code compiles succesfully:
\begin{equation}
P(\underline{\hat{X}} | \underline{Y}) = ...
\end{equation}