What's the difference between HEAD^ and HEAD~ in Git?
If you're wondering whether to type HEAD^
or HEAD~
in your command, just use either:
They're both names for the same commit - the first parent of the current commit.
Likewise with master~
and master^
- both names for the first parent of master.
In the same way as 2 + 2
and 2 x 2
are both 4
- they're different ways of getting there, but the answer is the same.
This answers the question: What's the difference between HEAD^ and HEAD~ in Git?
If you just did a merge (so your current commit has more than one parent), or you're still interested in how the caret and tilde work, see the other answers (which I won't duplicate here) for an in-depth explanation, as well as how to use them repeatedly (e.g.HEAD~~~
), or with numbers (e.g.HEAD^2
). Otherwise, I hope this answer saves you some time.
What's the syntax to import a class in a default package in Java?
As others have said, this is bad practice, but if you don't have a choice because you need to integrate with a third-party library that uses the default package, then you could create your own class in the default package and access the other class that way. Classes in the default package basically share a single namespace, so you can access the other class even if it resides in a separate JAR file. Just make sure the JAR file is in the classpath.
This trick doesn't work if your class is not in the default package.
How to navigate through a vector using iterators? (C++)
Typically, iterators are used to access elements of a container in linear fashion; however, with "random access iterators", it is possible to access any element in the same fashion as operator[]
.
To access arbitrary elements in a vector vec
, you can use the following:
vec.begin() // 1st
vec.begin()+1 // 2nd
// ...
vec.begin()+(i-1) // ith
// ...
vec.begin()+(vec.size()-1) // last
The following is an example of a typical access pattern (earlier versions of C++):
int sum = 0;
using Iter = std::vector<int>::const_iterator;
for (Iter it = vec.begin(); it!=vec.end(); ++it) {
sum += *it;
}
The advantage of using iterator is that you can apply the same pattern with other containers:
sum = 0;
for (Iter it = lst.begin(); it!=lst.end(); ++it) {
sum += *it;
}
For this reason, it is really easy to create template code that will work the same regardless of the container type.
Another advantage of iterators is that it doesn't assume the data is resident in memory; for example, one could create a forward iterator that can read data from an input stream, or that simply generates data on the fly (e.g. a range or random number generator).
Another option using std::for_each
and lambdas:
sum = 0;
std::for_each(vec.begin(), vec.end(), [&sum](int i) { sum += i; });
Since C++11 you can use auto
to avoid specifying a very long, complicated type name of the iterator as seen before (or even more complex):
sum = 0;
for (auto it = vec.begin(); it!=vec.end(); ++it) {
sum += *it;
}
And, in addition, there is a simpler for-each variant:
sum = 0;
for (auto value : vec) {
sum += value;
}
And finally there is also std::accumulate
where you have to be careful whether you are adding integer or floating point numbers.
How to install a specific version of Node on Ubuntu?
Try this way. This worked me.
wget nodejs.org/dist/v0.10.36/node-v0.10.36-linux-x64.tar.gz(download file)
Go to the directory where the Node.js binary was downloaded to, and then run command i.e, sudo tar -C /usr/local --strip-components 1 -xzf node-v0.10.36-linux-x64.tar.gz to install the Node.js binary package in “/usr/local/”.
You can check:-
$ node -v
v0.10.36
$ npm -v
1.4.28
Android Material Design Button Styles
Here is a sample that will help in applying button style consistently across your app.
Here is a sample Theme I used with the specific styles..
<style name="MyTheme" parent="@style/Theme.AppCompat.Light">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/accent</item>
<item name="android:buttonStyle">@style/ButtonAppTheme</item>
</style>
<style name="ButtonAppTheme" parent="android:Widget.Material.Button">
<item name="android:background">@drawable/material_button</item>
</style>
This is how I defined the button shape & effects inside res/drawable-v21 folder...
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?attr/colorControlHighlight">
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="2dp" />
<solid android:color="@color/primary" />
</shape>
</item>
</ripple>
2dp corners are to keep it consistent with Material theme.
Best way to define error codes/strings in Java?
Please follow the below example:
public enum ErrorCodes {
NO_File("No file found. "),
private ErrorCodes(String value) {
this.errordesc = value;
}
private String errordesc = "";
public String errordesc() {
return errordesc;
}
public void setValue(String errordesc) {
this.errordesc = errordesc;
}
};
In your code call it like:
fileResponse.setErrorCode(ErrorCodes.NO_FILE.errordesc());
Producer/Consumer threads using a Queue
OK, as others note, the best thing to do is to use java.util.concurrent
package. I highly recommend "Java Concurrency in Practice". It's a great book that covers almost everything you need to know.
As for your particular implementation, as I noted in the comments, don't start Threads from Constructors -- it can be unsafe.
Leaving that aside, the second implementation seem better. You don't want to put queues in static fields. You are probably just loosing flexibility for nothing.
If you want to go ahead with your own implementation (for learning purpose I guess?), supply a start()
method at least. You should construct the object (you can instantiate the Thread
object), and then call start()
to start the thread.
Edit: ExecutorService
have their own queue so this can be confusing.. Here's something to get you started.
public class Main {
public static void main(String[] args) {
//The numbers are just silly tune parameters. Refer to the API.
//The important thing is, we are passing a bounded queue.
ExecutorService consumer = new ThreadPoolExecutor(1,4,30,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(100));
//No need to bound the queue for this executor.
//Use utility method instead of the complicated Constructor.
ExecutorService producer = Executors.newSingleThreadExecutor();
Runnable produce = new Produce(consumer);
producer.submit(produce);
}
}
class Produce implements Runnable {
private final ExecutorService consumer;
public Produce(ExecutorService consumer) {
this.consumer = consumer;
}
@Override
public void run() {
Pancake cake = Pan.cook();
Runnable consume = new Consume(cake);
consumer.submit(consume);
}
}
class Consume implements Runnable {
private final Pancake cake;
public Consume(Pancake cake){
this.cake = cake;
}
@Override
public void run() {
cake.eat();
}
}
Further EDIT:
For producer, instead of while(true)
, you can do something like:
@Override
public void run(){
while(!Thread.currentThread().isInterrupted()){
//do stuff
}
}
This way you can shutdown the executor by calling .shutdownNow()
. If you'd use while(true)
, it won't shutdown.
Also note that the Producer
is still vulnerable to RuntimeExceptions
(i.e. one RuntimeException
will halt the processing)
Dynamic classname inside ngClass in angular 2
This one should work
<button [ngClass]="{[namespace + '-mybutton']: type === 'mybutton'}"></button>
but Angular throws on this syntax. I'd consider this a bug.
See also https://stackoverflow.com/a/36024066/217408
The others are invalid. You can't use []
together with {{}}
. Either one or the other. {{}}
binds the result stringified which doesn't lead to the desired result in this case because an object needs to be passed to ngClass
.
Plunker example
As workaround the syntax shown by @A_Sing or
<button [ngClass]="type === 'mybutton' ? namespace + '-mybutton' : ''"></button>
can be used.
Open another application from your own (intent)
Launch an application from another application on Android
Intent launchIntent = getActivity.getPackageManager().getLaunchIntentForPackage("com.ionicframework.uengage");
startActivity(launchIntent);
Java and SSL - java.security.NoSuchAlgorithmException
Try javax.net.ssl.keyStorePassword
instead of javax.net.ssl.keyPassword
: the latter isn't mentioned in the JSSE ref guide.
The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmException
s are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.
You could also use -Djavax.net.debug=ssl
, or at least -Djavax.net.debug=ssl,keymanager
, to get more debugging information, if the information in the stack trace isn't sufficient.
Angular2, what is the correct way to disable an anchor element?
Specifying pointer-events: none
in CSS disables mouse input but doesn't disable keyboard input. For example, the user can still tab to the link and "click" it by pressing the Enter key or (in Windows) the ? Menu key. You could disable specific keystrokes by intercepting the keydown
event, but this would likely confuse users relying on assistive technologies.
Probably the best way to disable a link is to remove its href
attribute, making it a non-link. You can do this dynamically with a conditional href
attribute binding:
<a *ngFor="let link of links"
[attr.href]="isDisabled(link) ? null : '#'"
[class.disabled]="isDisabled(link)"
(click)="!isDisabled(link) && onClick(link)">
{{ link.name }}
</a>
Or, as in Günter Zöchbauer's answer, you can create two links, one normal and one disabled, and use *ngIf
to show one or the other:
<ng-template ngFor #link [ngForOf]="links">
<a *ngIf="!isDisabled(link)" href="#" (click)="onClick(link)">{{ link.name }}</a>
<a *ngIf="isDisabled(link)" class="disabled">{{ link.name }}</a>
</ng-template>
Here's some CSS to make the link look disabled:
a.disabled {
color: gray;
cursor: not-allowed;
text-decoration: underline;
}
How to rename a file using svn?
This message will appear if you are using a case-insensitive file system (e.g. on a Mac) and you're trying to capitalize the name (or another change of case).
In which case you need to rename to a third, dummy, name:
svn mv file-name file-name_
svn mv file-name_ FILE_Name
svn commit
SQL Query Where Date = Today Minus 7 Days
DECLARE @Daysforward int
SELECT @Daysforward = 25 (no of days required)
Select * from table name
where CAST( columnDate AS date) < DATEADD(day,1+@Daysforward,CAST(GETDATE() AS date))
How to know installed Oracle Client is 32 bit or 64 bit?
None of the links above about lib and lib32 folder worked for me with Oracle Client 11.2.0 But I found this on the OTN community:
As far as inspecting a client install to try to tell if it's 32 bit or
64 bit, you can check the registry, a 32 bit home will be located in
HKLM>Software>WOW6432Node>Oracle, whereas a 64 bit home will be in
HKLM>Software>Oracle.
PHP, get file name without file extension
Your answer is below the perfect solution to hide to file extension in php.
<?php
$path = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo basename($path, ".php");
?>
How do I compare two DateTime objects in PHP 5.2.8?
$elapsed = '2592000';
// Time in the past
$time_past = '2014-07-16 11:35:33';
$time_past = strtotime($time_past);
// Add a month to that time
$time_past = $time_past + $elapsed;
// Time NOW
$time_now = time();
// Check if its been a month since time past
if($time_past > $time_now){
echo 'Hasnt been a month';
}else{
echo 'Been longer than a month';
}
Best way to move files between S3 buckets?
.NET Example as requested:
using (client)
{
var existingObject = client.ListObjects(requestForExisingFile).S3Objects;
if (existingObject.Count == 1)
{
var requestCopyObject = new CopyObjectRequest()
{
SourceBucket = BucketNameProd,
SourceKey = objectToMerge.Key,
DestinationBucket = BucketNameDev,
DestinationKey = newKey
};
client.CopyObject(requestCopyObject);
}
}
with client being something like
var config = new AmazonS3Config { CommunicationProtocol = Protocol.HTTP, ServiceURL = "s3-eu-west-1.amazonaws.com" };
var client = AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretAccessKey, config);
There might be a better way, but it's just some quick code I wrote to get some files transferred.
Concatenate text files with Windows command line, dropping leading lines
I know you said that you couldn't install any software, but I'm not sure how tight that restriction is. Anyway, I had the same issue (trying to concatenate two files with presumably the same headers) and I thought I'd provide an alternative answer for others who arrive at this page, since it worked just great for me.
After trying a whole bunch of commands in windows and being severely frustrated, and also trying all sorts of graphical editors that promised to be able to open large files, but then couldn't, I finally got back to my Linux roots and opened my Cygwin prompt. Two commands:
cp file1.csv out.csv
tail -n+2 file2.csv >> out.csv
For file1.csv
800MB and file2.csv
400MB, those two commands took under 5 seconds on my machine. In a Cygwin prompt, no less. I thought Linux commands were supposed to be slow in Cygwin but that approach took far less effort and was way easier than any windows approach I could find.
Difference between View and Request scope in managed beans
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
See also:
Android: How to rotate a bitmap on a center point
Edited: optimized code.
public static Bitmap RotateBitmap(Bitmap source, float angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
To get Bitmap from resources:
Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);
How to update column value in laravel
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
What is the easiest way to encrypt a password when I save it to the registry?
I have looked all over for a good example of encryption and decryption process but most were overly complex.
Anyhow there are many reasons someone may want to decrypt some text values including passwords. The reason I need to decrypt the password on the site I am working on currently is because they want to make sure when someone is forced to change their password when it expires that we do not let them change it with a close variant of the same password they used in the last x months.
So I wrote up a process that will do this in a simplified manner. I hope this code is beneficial to someone. For all I know I may end up using this at another time for a different company/site.
public string GenerateAPassKey(string passphrase)
{
// Pass Phrase can be any string
string passPhrase = passphrase;
// Salt Value can be any string(for simplicity use the same value as used for the pass phrase)
string saltValue = passphrase;
// Hash Algorithm can be "SHA1 or MD5"
string hashAlgorithm = "SHA1";
// Password Iterations can be any number
int passwordIterations = 2;
// Key Size can be 128,192 or 256
int keySize = 256;
// Convert Salt passphrase string to a Byte Array
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
// Using System.Security.Cryptography.PasswordDeriveBytes to create the Key
PasswordDeriveBytes pdb = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
//When creating a Key Byte array from the base64 string the Key must have 32 dimensions.
byte[] Key = pdb.GetBytes(keySize / 11);
String KeyString = Convert.ToBase64String(Key);
return KeyString;
}
//Save the keystring some place like your database and use it to decrypt and encrypt
//any text string or text file etc. Make sure you dont lose it though.
private static string Encrypt(string plainStr, string KeyString)
{
RijndaelManaged aesEncryption = new RijndaelManaged();
aesEncryption.KeySize = 256;
aesEncryption.BlockSize = 128;
aesEncryption.Mode = CipherMode.ECB;
aesEncryption.Padding = PaddingMode.ISO10126;
byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);
aesEncryption.Key = KeyInBytes;
byte[] plainText = ASCIIEncoding.UTF8.GetBytes(plainStr);
ICryptoTransform crypto = aesEncryption.CreateEncryptor();
byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherText);
}
private static string Decrypt(string encryptedText, string KeyString)
{
RijndaelManaged aesEncryption = new RijndaelManaged();
aesEncryption.KeySize = 256;
aesEncryption.BlockSize = 128;
aesEncryption.Mode = CipherMode.ECB;
aesEncryption.Padding = PaddingMode.ISO10126;
byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);
aesEncryption.Key = KeyInBytes;
ICryptoTransform decrypto = aesEncryption.CreateDecryptor();
byte[] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(), 0, encryptedText.Length);
return ASCIIEncoding.UTF8.GetString(decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length));
}
String KeyString = GenerateAPassKey("PassKey");
String EncryptedPassword = Encrypt("25Characterlengthpassword!", KeyString);
String DecryptedPassword = Decrypt(EncryptedPassword, KeyString);
Draw path between two points using Google Maps Android API v2
Try below solution to draw path with animation and also get time and distance between two points.
DirectionHelper.java
public class DirectionHelper {
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
List<List<HashMap<String, String>>> routes = new ArrayList<>();
JSONArray jRoutes;
JSONArray jLegs;
JSONArray jSteps;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap<>();
hm.put("lat", Double.toString((list.get(l)).latitude));
hm.put("lng", Double.toString((list.get(l)).longitude));
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
//Method to decode polyline points
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
GetPathFromLocation.java
public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {
private Context context;
private String TAG = "GetPathFromLocation";
private LatLng source, destination;
private ArrayList<LatLng> wayPoint;
private GoogleMap mMap;
private boolean animatePath, repeatDrawingPath;
private DirectionPointListener resultCallback;
private ProgressDialog progressDialog;
//https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
//https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/
public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
this.context = context;
this.source = source;
this.destination = destination;
this.wayPoint = wayPoint;
this.mMap = mMap;
this.animatePath = animatePath;
this.repeatDrawingPath = repeatDrawingPath;
this.resultCallback = resultCallback;
}
synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {
String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
+ source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
if (centerPoint == 0) {
url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
} else {
url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
}
}
url = url + "&key=" + context.getResources().getString(R.string.google_api_key);
return url;
}
public int getRandomColor() {
Random rnd = new Random();
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please wait...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... url) {
String data;
try {
InputStream inputStream = null;
HttpURLConnection connection = null;
try {
URL directionUrl = new URL(getUrl(source, destination, wayPoint));
connection = (HttpURLConnection) directionUrl.openConnection();
connection.connect();
inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
data = stringBuffer.toString();
bufferedReader.close();
} catch (Exception e) {
Log.e(TAG, "Exception : " + e.toString());
return null;
} finally {
inputStream.close();
connection.disconnect();
}
Log.e(TAG, "Background Task data : " + data);
//Second AsyncTask
JSONObject jsonObject;
List<List<HashMap<String, String>>> routes = null;
try {
jsonObject = new JSONObject(data);
// Starts parsing data
DirectionHelper helper = new DirectionHelper();
routes = helper.parse(jsonObject);
Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);
return routes;
} catch (Exception e) {
Log.e(TAG, "Exception in Executing Routes : " + e.toString());
return null;
}
} catch (Exception e) {
Log.e(TAG, "Background Task Exception : " + e.toString());
return null;
}
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
super.onPostExecute(result);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
ArrayList<LatLng> points;
PolylineOptions lineOptions = null;
String distance = "";
String duration = "";
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) { // Get distance from the list
distance = (String) point.get("distance");
continue;
} else if (j == 1) { // Get duration from the list
duration = (String) point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(8);
lineOptions.color(Color.RED);
//lineOptions.color(getRandomColor());
if (animatePath) {
final ArrayList<LatLng> finalPoints = points;
((AppCompatActivity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
PolylineOptions polylineOptions;
final Polyline greyPolyLine, blackPolyline;
final ValueAnimator polylineAnimator;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : finalPoints) {
builder.include(latLng);
}
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.RED);
polylineOptions.width(8);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(ROUND);
polylineOptions.addAll(finalPoints);
greyPolyLine = mMap.addPolyline(polylineOptions);
polylineOptions = new PolylineOptions();
polylineOptions.width(8);
polylineOptions.color(Color.WHITE);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.zIndex(5f);
polylineOptions.jointType(ROUND);
blackPolyline = mMap.addPolyline(polylineOptions);
polylineAnimator = ValueAnimator.ofInt(0, 100);
polylineAnimator.setDuration(5000);
polylineAnimator.setInterpolator(new LinearInterpolator());
polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyLine.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polylineAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
if (repeatDrawingPath) {
List<LatLng> greyLatLng = greyPolyLine.getPoints();
if (greyLatLng != null) {
greyLatLng.clear();
}
polylineAnimator.start();
}
}
@Override
public void onAnimationCancel(Animator animation) {
polylineAnimator.cancel();
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
polylineAnimator.start();
}
});
}
Log.e(TAG, "PolylineOptions Decoded");
}
// Drawing polyline in the Google Map for the i-th route
if (resultCallback != null && lineOptions != null)
resultCallback.onPath(lineOptions, distance, duration);
}
}
DirectionPointListener
public interface DirectionPointListener {
public void onPath(PolylineOptions polyLine,String distance,String duration);
}
Now draw path using below code in your Activity
private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
/*Add Source Marker*/
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(source);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mMap.addMarker(markerOptions);
builder.include(source);
/*Add Destination Marker*/
markerOptions = new MarkerOptions();
markerOptions.position(destination);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mMap.addMarker(markerOptions);
builder.include(destination);
LatLngBounds bounds = builder.build();
int width = mapFragment.getView().getMeasuredWidth();
int height = mapFragment.getView().getMeasuredHeight();
int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
mMap.animateCamera(cu);
new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
@Override
public void onPath(PolylineOptions polyLine, String distance, String duration) {
mMap.addPolyline(polyLine);
Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);
binding.txtDistance.setText(String.format(" %s", distance));
binding.txtDuration.setText(String.format(" %s", duration));
}
}).execute();
}
});
}
OutPut
I hope this can help you!
Thank You.
This certificate has an invalid issuer Apple Push Services
- Download https://developer.apple.com/certificationauthority/AppleWWDRCA.cer
and double-click to install to Keychain.
- Select "View" -> "Show Expired Certificates" in Keychain app.
Confirm "Certificates" category is selected.
Remove expired Apple Worldwide Developer Relations Certificate Authority certificates from "login" tab and "System" tab.
Here's Apple's answer.
Thanks for bringing this to the attention of the community and apologies for the issues you’ve been having. This issue stems from having a copy of the expired WWDR Intermediate certificate in both your System and Login keychains. To resolve the issue, you should first download and install the new WWDR intermediate certificate (by double-clicking on the file). Next, in the Keychain Access application, select the System keychain. Make sure to select “Show Expired Certificates” in the View menu and then delete the expired version of the Apple Worldwide Developer Relations Certificate Authority Intermediate certificate (expired on February 14, 2016). Your certificates should now appear as valid in Keychain Access and be available to Xcode for submissions to the App Store.
https://forums.developer.apple.com/thread/37208
How to get value by key from JObject?
Try this:
private string GetJArrayValue(JObject yourJArray, string key)
{
foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
{
if (key == keyValuePair.Key)
{
return keyValuePair.Value.ToString();
}
}
}
Extract a substring from a string in Ruby using a regular expression
Here's a slightly more flexible approach using the match
method. With this, you can extract more than one string:
s = "<ants> <pants>"
matchdata = s.match(/<([^>]*)> <([^>]*)>/)
# Use 'captures' to get an array of the captures
matchdata.captures # ["ants","pants"]
# Or use raw indices
matchdata[0] # whole regex match: "<ants> <pants>"
matchdata[1] # first capture: "ants"
matchdata[2] # second capture: "pants"
Bootstrap number validation
It's not Twitter bootstrap specific, it is a normal HTML5 component and you can specify the range with the min
and max
attributes (in your case only the first attribute). For example:
_x000D_
_x000D_
<div> _x000D_
<input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_
I'm not sure if only integers are allowed by default in the control or not, but else you can specify the step
attribute:
_x000D_
_x000D_
<div> _x000D_
<input type="number" id="replyNumber" min="0" step="1" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_
Now only numbers higher (and equal to) zero can be used and there is a step of 1, which means the values are 0, 1, 2, 3, 4, ... .
BE AWARE: Not all browsers support the HTML5 features, so it's recommended to have some kind of JavaScript fallback (and in your back-end too) if you really want to use the constraints.
For a list of browsers that support it, you can look at caniuse.com.
/bin/sh: pushd: not found
Your shell (/bin/sh) is trying to find 'pushd'. But it can't find it because 'pushd','popd' and other commands like that are build in bash.
Launch you script using Bash (/bin/bash) instead of Sh like you are doing now, and it will work
How to save S3 object to a file using boto3
boto3 now has a nicer interface than the client:
resource = boto3.resource('s3')
my_bucket = resource.Bucket('MyBucket')
my_bucket.download_file(key, local_filename)
This by itself isn't tremendously better than the client
in the accepted answer (although the docs say that it does a better job retrying uploads and downloads on failure) but considering that resources are generally more ergonomic (for example, the s3 bucket and object resources are nicer than the client methods) this does allow you to stay at the resource layer without having to drop down.
Resources
generally can be created in the same way as clients, and they take all or most of the same arguments and just forward them to their internal clients.
Example to use shared_ptr?
Using a vector
of shared_ptr
removes the possibility of leaking memory because you forgot to walk the vector and call delete
on each element. Let's walk through a slightly modified version of the example line-by-line.
typedef boost::shared_ptr<gate> gate_ptr;
Create an alias for the shared pointer type. This avoids the ugliness in the C++ language that results from typing std::vector<boost::shared_ptr<gate> >
and forgetting the space between the closing greater-than signs.
std::vector<gate_ptr> vec;
Creates an empty vector of boost::shared_ptr<gate>
objects.
gate_ptr ptr(new ANDgate);
Allocate a new ANDgate
instance and store it into a shared_ptr
. The reason for doing this separately is to prevent a problem that can occur if an operation throws. This isn't possible in this example. The Boost shared_ptr
"Best Practices" explain why it is a best practice to allocate into a free-standing object instead of a temporary.
vec.push_back(ptr);
This creates a new shared pointer in the vector and copies ptr
into it. The reference counting in the guts of shared_ptr
ensures that the allocated object inside of ptr
is safely transferred into the vector.
What is not explained is that the destructor for shared_ptr<gate>
ensures that the allocated memory is deleted. This is where the memory leak is avoided. The destructor for std::vector<T>
ensures that the destructor for T
is called for every element stored in the vector. However, the destructor for a pointer (e.g., gate*
) does not delete the memory that you had allocated. That is what you are trying to avoid by using shared_ptr
or ptr_vector
.
How to have comments in IntelliSense for function in Visual Studio?
What you need is xml comments - basically, they follow this syntax (as vaguely described by Solmead):
C#
///<summary>
///This is a description of my function.
///</summary>
string myFunction() {
return "blah";
}
VB
'''<summary>
'''This is a description of my function.
'''</summary>
Function myFunction() As String
Return "blah"
End Function
Do Java arrays have a maximum size?
I tried to create a byte array like this
byte[] bytes = new byte[Integer.MAX_VALUE-x];
System.out.println(bytes.length);
With this run configuration:
-Xms4G -Xmx4G
And java version:
Openjdk version "1.8.0_141"
OpenJDK Runtime Environment (build 1.8.0_141-b16)
OpenJDK 64-Bit Server VM (build 25.141-b16, mixed mode)
It only works for x >= 2 which means the maximum size of an array is Integer.MAX_VALUE-2
Values above that give
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at Main.main(Main.java:6)
DirectX SDK (June 2010) Installation Problems: Error Code S1023
Here is the official answer from Microsoft: http://blogs.msdn.com/b/chuckw/archive/2011/12/09/known-issue-directx-sdk-june-2010-setup-and-the-s1023-error.aspx
Summary if you'd rather not click through:
Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:
MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}
MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
Install the DirectX SDK (June 2010)
Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB2565063 with a security fix.
Windows SDK: The Windows SDK 7.1 has exactly the same issue as noted in KB 2717426.
Saving ssh key fails
It looks like you are executing that command from a DOS session (see this thread), and that means you need to create the .ssh
directory before said command.
Or you can execute it from the bash session (part of the msysgit distribution), and it should work.
How to add elements to an empty array in PHP?
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";
//OR
$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}
Mixing a PHP variable with a string literal
$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";
print $bucket;
yields:
$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']
How do you connect to multiple MySQL databases on a single webpage?
Warning : mysql_xx
functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx
functions or see the answer below from @Troelskn
You can make multiple calls to mysql_connect()
, but if the parameters are the same you need to pass true for the '$new_link
' (fourth) parameter, otherwise the same connection is reused. For example:
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $dbh1);
and for database 2 pass the second:
mysql_query('select * from tablename', $dbh2);
If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2
) e.g.:
mysql_query('select * from tablename');
Other options
If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:
- Keep one connection open and call
mysql_select_db()
to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.
- Specify the database name when you reference tables within your queries (e.g.
SELECT * FROM database2.tablename
). This is likely to be a pain to implement.
Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.
Overriding fields or properties in subclasses
You can go with option 3 if you modify your abstract base class to require the property value in the constructor, you won't miss any paths. I'd really consider this option.
abstract class Aunt
{
protected int MyInt;
protected Aunt(int myInt)
{
MyInt = myInt;
}
}
Of course, you then still have the option of making the field private and then, depending on the need, exposing a protected or public property getter.
Sending Arguments To Background Worker?
You should always try to use a composite object with concrete types (using composite design pattern) rather than a list of object types. Who would remember what the heck each of those objects is? Think about maintenance of your code later on... Instead, try something like this:
Public (Class or Structure) MyPerson
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int ZipCode { get; set; }
End Class
And then:
Dim person as new MyPerson With { .FirstName = “Joe”,
.LastName = "Smith”,
...
}
backgroundWorker1.RunWorkerAsync(person)
and then:
private void backgroundWorker1_DoWork (object sender, DoWorkEventArgs e)
{
MyPerson person = e.Argument as MyPerson
string firstname = person.FirstName;
string lastname = person.LastName;
int zipcode = person.ZipCode;
}
Remove excess whitespace from within a string
Not sure exactly what you want but here are two situations:
If you are just dealing with excess whitespace on the beginning or end of the string you can use trim()
, ltrim()
or rtrim()
to remove it.
If you are dealing with extra spaces within a string consider a preg_replace
of multiple whitespaces " "*
with a single whitespace " "
.
Example:
$foo = preg_replace('/\s+/', ' ', $foo);
How to initialize std::vector from C-style array?
You use the word initialize so it's unclear if this is one-time assignment or can happen multiple times.
If you just need a one time initialization, you can put it in the constructor and use the two iterator vector constructor:
Foo::Foo(double* w, int len) : w_(w, w + len) { }
Otherwise use assign as previously suggested:
void set_data(double* w, int len)
{
w_.assign(w, w + len);
}
Multiple axis line chart in excel
Best and Free ( maybe only) solution for this is google sheets.
i don't know whether it plots as u expected or not but certainly you can draw multiple axes.
Regards
keerthan
Concatenate two NumPy arrays vertically
If the actual problem at hand is to concatenate two 1-D arrays vertically, and we are not fixated on using concatenate
to perform this operation, I would suggest the use of np.column_stack:
In []: a = np.array([1,2,3])
In []: b = np.array([4,5,6])
In []: np.column_stack((a, b))
array([[1, 4],
[2, 5],
[3, 6]])
How to remove MySQL completely with config and library files?
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql.
Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
Why do some functions have underscores "__" before and after the function name?
From the Python PEP 8 -- Style Guide for Python Code:
The following special forms using leading or trailing underscores are
recognized (these can generally be combined with any case convention):
_single_leading_underscore
: weak "internal use" indicator. E.g. from M import *
does not import objects whose name starts with an underscore.
single_trailing_underscore_
: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore
: when naming a class attribute, invokes name mangling (inside class FooBar, __boo
becomes _FooBar__boo
; see below).
__double_leading_and_trailing_underscore__
: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__
,
__import__
or __file__
. Never invent such names; only use them as documented.
Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".
How can I display just a portion of an image in HTML/CSS?
Another alternative is the following, although not the cleanest as it assumes the image to be the only element in a container, such as in this case:
<header class="siteHeader">
<img src="img" class="siteLogo" />
</header>
You can then use the container as a mask with the desired size, and surround the image with a negative margin to move it into the right position:
.siteHeader{
width: 50px;
height: 50px;
overflow: hidden;
}
.siteHeader .siteLogo{
margin: -100px;
}
Demo can be seen in this JSFiddle.
Only seems to work in IE>9, and probably all significant versions of all other browsers.
-XX:MaxPermSize with or without -XX:PermSize
By playing with parameters as -XX:PermSize
and -Xms
you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms
was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.
A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).
WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms
equal to -Xmx
or -XX:PermSize
equal to -XX:MaxPermSize
as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.
As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)
Angular and debounce
This is the best solution I have found till now. Updates the ngModel
on blur
and debounce
import { Directive, Input, Output, EventEmitter,ElementRef } from '@angular/core';
import { NgControl, NgModel } from '@angular/forms';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/map';
@Directive({
selector: '[ngModel][debounce]',
})
export class DebounceDirective {
@Output()
public onDebounce = new EventEmitter<any>();
@Input('debounce')
public debounceTime: number = 500;
private isFirstChange: boolean = true;
constructor(private elementRef: ElementRef, private model: NgModel) {
}
ngOnInit() {
const eventStream = Observable.fromEvent(this.elementRef.nativeElement, 'keyup')
.map(() => {
return this.model.value;
})
.debounceTime(this.debounceTime);
this.model.viewToModelUpdate = () => {};
eventStream.subscribe(input => {
this.model.viewModel = input;
this.model.update.emit(input);
});
}
}
as borrowed from https://stackoverflow.com/a/47823960/3955513
Then in HTML:
<input [(ngModel)]="hero.name"
[debounce]="3000"
(blur)="hero.name = $event.target.value"
(ngModelChange)="onChange()"
placeholder="name">
On blur
the model is explicitly updated using plain javascript.
Example here: https://stackblitz.com/edit/ng2-debounce-working
How do you clear the SQL Server transaction log?
It happened with me where the database log file was of 28 GBs.
What can you do to reduce this?
Actually, log files are those file data which the SQL server keeps when an transaction has taken place. For a transaction to process SQL server allocates pages for the same. But after the completion of the transaction, these are not released suddenly hoping that there may be a transaction coming like the same one. This holds up the space.
Step 1:
First Run this command in the database query explored
checkpoint
Step 2:
Right click on the database
Task> Back up
Select back up type as Transaction Log
Add a destination address and file name to keep the backup data (.bak)
Repeat this step again and at this time give another file name
Step 3:
Now go to the database
Right-click on the database
Tasks> Shrinks> Files
Choose File type as Log
Shrink action as release unused space
Step 4:
Check your log file
normally in SQL 2014 this can be found at
C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQL2014EXPRESS\MSSQL\DATA
In my case, its reduced from 28 GB to 1 MB
Is it possible to modify a registry entry via a .bat/.cmd script?
You can use the REG command. From http://www.ss64.com/nt/reg.html:
Syntax:
REG QUERY [ROOT\]RegKey /v ValueName [/s]
REG QUERY [ROOT\]RegKey /ve --This returns the (default) value
REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]
REG ADD [ROOT\]RegKey /ve [/d Data] [/f] -- Set the (default) value
REG DELETE [ROOT\]RegKey /v ValueName [/f]
REG DELETE [ROOT\]RegKey /ve [/f] -- Remove the (default) value
REG DELETE [ROOT\]RegKey /va [/f] -- Delete all values under this key
REG COPY [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey
REG EXPORT [ROOT\]RegKey FileName.reg
REG IMPORT FileName.reg
REG SAVE [ROOT\]RegKey FileName.hiv
REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv
REG LOAD FileName KeyName
REG UNLOAD KeyName
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s]
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]
Key:
ROOT :
HKLM = HKey_Local_machine (default)
HKCU = HKey_current_user
HKU = HKey_users
HKCR = HKey_classes_root
ValueName : The value, under the selected RegKey, to edit.
(default is all keys and values)
/d Data : The actual data to store as a "String", integer etc
/f : Force an update without prompting "Value exists, overwrite Y/N"
\\Machine : Name of remote machine - omitting defaults to current machine.
Only HKLM and HKU are available on remote machines.
FileName : The filename to save or restore a registry hive.
KeyName : A key name to load a hive file into. (Creating a new key)
/S : Query all subkeys and values.
/S Separator : Character to use as the separator in REG_MULTI_SZ values
the default is "\0"
/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ
Output : /od (only differences) /os (only matches) /oa (all) /on (no output)
Remove a fixed prefix/suffix from a string in Bash
$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor
This is documented in the Shell Parameter Expansion section of the manual:
${parameter#word}
${parameter##word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the #
case) or the longest matching pattern (the ##
case) deleted. […]
${parameter%word}
${parameter%%word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the %
case) or the longest matching pattern (the %%
case) deleted. […]
How to Load RSA Private Key From File
You need to convert your private key to PKCS8 format using following command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file -nocrypt > pkcs8_key
After this your java program can read it.
Get Hard disk serial Number
There is a simple way for @Sprunth's answer.
private void GetAllDiskDrives()
{
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject wmi_HD in searcher.Get())
{
HardDrive hd = new HardDrive();
hd.Model = wmi_HD["Model"].ToString();
hd.InterfaceType = wmi_HD["InterfaceType"].ToString();
hd.Caption = wmi_HD["Caption"].ToString();
hd.SerialNo =wmi_HD.GetPropertyValue("SerialNumber").ToString();//get the serailNumber of diskdrive
hdCollection.Add(hd);
}
}
public class HardDrive
{
public string Model { get; set; }
public string InterfaceType { get; set; }
public string Caption { get; set; }
public string SerialNo { get; set; }
}
What is the difference between a deep copy and a shallow copy?
{Imagine two objects: A and B of same type _t(with respect to C++) and you are thinking about shallow/deep copying A to B}
Shallow Copy:
Simply makes a copy of the reference to A into B. Think about it as a copy of A's Address.
So, the addresses of A and B will be the same i.e. they will be pointing to the same memory location i.e. data contents.
Deep copy:
Simply makes a copy of all the members of A, allocates memory in a different location for B and then assigns the copied members to B to achieve deep copy. In this way, if A becomes non-existant B is still valid in the memory. The correct term to use would be cloning, where you know that they both are totally the same, but yet different (i.e. stored as two different entities in the memory space). You can also provide your clone wrapper where you can decide via inclusion/exclusion list which properties to select during deep copy. This is quite a common practice when you create APIs.
You can choose to do a Shallow Copy ONLY_IF you understand the stakes involved. When you have enormous number of pointers to deal with in C++ or C, doing a shallow copy of an object is REALLY a bad idea.
EXAMPLE_OF_DEEP COPY_ An example is, when you are trying to do image processing and object recognition you need to mask "Irrelevant and Repetitive Motion" out of your processing areas. If you are using image pointers, then you might have the specification to save those mask images. NOW... if you do a shallow copy of the image, when the pointer references are KILLED from the stack, you lost the reference and its copy i.e. there will be a runtime error of access violation at some point. In this case, what you need is a deep copy of your image by CLONING it. In this way you can retrieve the masks in case you need them in the future.
EXAMPLE_OF_SHALLOW_COPY I am not extremely knowledgeable compared to the users in StackOverflow so feel free to delete this part and put a good example if you can clarify. But I really think it is not a good idea to do shallow copy if you know that your program is gonna run for an infinite period of time i.e. continuous "push-pop" operation over the stack with function calls. If you are demonstrating something to an amateur or novice person (e.g. C/C++ tutorial stuff) then it is probably okay. But if you are running an application such as surveillance and detection system, or Sonar Tracking System, you are not supposed to keep shallow copying your objects around because it will kill your program sooner or later.
What is the use of adding a null key or value to a HashMap in Java?
One example of usage for null
values is when using a HashMap
as a cache for results of an expensive operation (such as a call to an external web service) which may return null
.
Putting a null
value in the map then allows you to distinguish between the case where the operation has not been performed for a given key (cache.containsKey(someKey)
returns false
), and where the operation has been performed but returned a null
value (cache.containsKey(someKey)
returns true
, cache.get(someKey)
returns null
).
Without null
values, you would have to either put some special value in the cache to indicate a null
response, or simply not cache that response at all and perform the operation every time.
How do I get rid of an element's offset using CSS?
In my case the offset was added to a custom element with grid layout within an li while the ul was a vertical flexbox.
The pretty simple solution was to set the define the li as block element with
li {
display: block;
}
And the offset was gone
How do I write a Windows batch script to copy the newest file from a directory?
Bash:
find -type f -printf "%T@ %p \n" \
| sort \
| tail -n 1 \
| sed -r "s/^\S+\s//;s/\s*$//" \
| xargs -iSTR cp STR newestfile
where "newestfile" will become the newestfile
alternatively, you could do newdir/STR or just newdir
Breakdown:
- list all files in {time} {file} format.
- sort them by time
- get the last one
- cut off the time, and whitespace from the start/end
- copy resulting value
Important
After running this once, the newest file will be whatever you just copied :p ( assuming they're both in the same search scope that is ).
So you may have to adjust which filenumber you copy if you want this to work more than once.
Javascript validation: Block special characters
I think checking keypress
events is not completely adequate, as I believe users can copy/paste into input boxes without triggering a keypress.
So onblur
is probably somewhat more reliable (but is less immediate).
To truly make sure characters you don't want are not entered into input boxes (or textareas, etc.), I think you will need to
- check
keypress
(if you want to give immediate feedback) and
- also check
onblur
,
- as well as validating inputs on the server (which is the only real way to make sure nothing unwanted gets into your data).
The code samples in the other answers will work fine for doing the client-side checks (just don't rely only on checking keypress
events), but as was pointed out in the accepted answer, a server-side check is really required.
Html5 Full screen video
if (vi_video[0].exitFullScreen) vi_video[0].exitFullScreen();
else if (vi_video[0].webkitExitFullScreen) vi_video[0].webkitExitFullScreen();
else if (vi_video[0].mozExitFullScreen) vi_video[0].mozExitFullScreen();
else if (vi_video[0].oExitFullScreen) vi_video[0].oExitFullScreen();
else if (vi_video[0].msExitFullScreen) vi_video[0].msExitFullScreen();
else { vi_video.parent().append(vi_video.remove()); }
How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?
Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.
If the purpose of the CSS class on the <form/>
element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/>
element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.
Easiest way to pass an AngularJS scope variable from directive to controller?
Edited on 2014/8/25:
Here was where I forked it.
Thanks @anvarik.
Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @
<div ng-controller="MyCtrl">
<h2>Parent Scope</h2>
<input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>
<br><br>
<!-- attribute-foo binds to a DOM attribute which is always
a string. That is why we are wrapping it in curly braces so
that it can be interpolated. -->
<my-component attribute-foo="{{foo}}" binding-foo="foo"
isolated-expression-foo="updateFoo(newFoo)" >
<h2>Attribute</h2>
<div>
<strong>get:</strong> {{isolatedAttributeFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedAttributeFoo">
<i>// This does not update the parent scope.</i>
</div>
<h2>Binding</h2>
<div>
<strong>get:</strong> {{isolatedBindingFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedBindingFoo">
<i>// This does update the parent scope.</i>
</div>
<h2>Expression</h2>
<div>
<input ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
<i>// And this calls a function on the parent scope.</i>
</div>
</my-component>
</div>
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'@attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.foo = 'Hello!';
$scope.updateFoo = function (newFoo) {
$scope.foo = newFoo;
}
}]);
Loop through JSON in EJS
JSON.stringify
returns a String
. So, for example:
var data = [
{ id: 1, name: "bob" },
{ id: 2, name: "john" },
{ id: 3, name: "jake" },
];
JSON.stringify(data)
will return the equivalent of:
"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"
as a String
value.
So when you have
<% for(var i=0; i<JSON.stringify(data).length; i++) {%>
what that ends up looking like is:
<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>
which is probably not what you want. What you probably do want is something like this:
<table>
<% for(var i=0; i < data.length; i++) { %>
<tr>
<td><%= data[i].id %></td>
<td><%= data[i].name %></td>
</tr>
<% } %>
</table>
This will output the following table (using the example data
from above):
<table>
<tr>
<td>1</td>
<td>bob</td>
</tr>
<tr>
<td>2</td>
<td>john</td>
</tr>
<tr>
<td>3</td>
<td>jake</td>
</tr>
</table>
Where to find the complete definition of off_t type?
Since this answer still gets voted up, I want to point out that you should almost never need to look in the header files. If you want to write reliable code, you're much better served by looking in the standard. A better question than "how is off_t
defined on my machine" is "how is off_t
defined by the standard?". Following the standard means that your code will work today and tomorrow, on any machine.
In this case, off_t
isn't defined by the C standard. It's part of the POSIX standard, which you can browse here.
Unfortunately, off_t
isn't very rigorously defined. All I could find to define it is on the page on sys/types.h
:
blkcnt_t
and off_t
shall be signed integer types.
This means that you can't be sure how big it is. If you're using GNU C, you can use the instructions in the answer below to ensure that it's 64 bits. Or better, you can convert to a standards defined size before putting it on the wire. This is how projects like Google's Protocol Buffers work (although that is a C++ project).
So, I think "where do I find the definition in my header files" isn't the best question.
But, for completeness here's the answer:
On my machine (and most machines using glibc) you'll find the definition in bits/types.h
(as a comment says at the top, never directly include this file), but it's obscured a bit in a bunch of macros. An alternative to trying to unravel them is to look at the preprocessor output:
#include <stdio.h>
#include <sys/types.h>
int main(void) {
off_t blah;
return 0;
}
And then:
$ gcc -E sizes.c | grep __off_t
typedef long int __off_t;
....
However, if you want to know the size of something, you can always use the sizeof()
operator.
Edit: Just saw the part of your question about the __
. This answer has a good discussion. The key point is that names starting with __
are reserved for the implementation (so you shouldn't start your own definitions with __
).
Post Build exited with code 1
So many solutions...
In my case, I had to save the bat file with non-unicode (Western, Windows) encoding. By default when I added the file to visual studio (and probably I should have done it outside of the VS), it added with UTF-8 encoding.
How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?
Future-Proof Solution That Works In All Time Zones
- Let
x
be the expected number of milliseconds into the year of interest without factoring in daylight savings.
- Let
y
be the number of milliseconds since the Epoch from the start of the year of the date of interest.
- Let
z
be the number of milliseconds since the Epoch of the full date and time of interest
- Let
t
be the subtraction of both x
and y
from z
: z - y - x
. This yields the offset due to DST.
- If
t
is zero, then DST is not in effect. If t
is not zero, then DST is in effect.
_x000D_
_x000D_
(function(){"use strict";_x000D_
function dstOffsetAtDate(dateInput) {_x000D_
var fullYear = dateInput.getFullYear()|0;_x000D_
// "Leap Years are any year that can be exactly divided by 4 (2012, 2016, etc)_x000D_
// except if it can be exactly divided by 100, then it isn't (2100,2200,etc)_x000D_
// except if it can be exactly divided by 400, then it is (2000, 2400)"_x000D_
// (https://www.mathsisfun.com/leap-years.html)._x000D_
var isLeapYear = ((fullYear & 3) | (fullYear/100 & 3)) === 0 ? 1 : 0;_x000D_
// (fullYear & 3) = (fullYear % 4), but faster_x000D_
//Alternative:var isLeapYear=(new Date(currentYear,1,29,12)).getDate()===29?1:0_x000D_
var fullMonth = dateInput.getMonth()|0;_x000D_
return (_x000D_
// 1. We know what the time since the Epoch really is_x000D_
(+dateInput) // same as the dateInput.getTime() method_x000D_
// 2. We know what the time since the Epoch at the start of the year is_x000D_
- (+new Date(fullYear, 0, 0)) // day defaults to 1 if not explicitly zeroed_x000D_
// 3. Now, subtract what we would expect the time to be if daylight savings_x000D_
// did not exist. This yields the time-offset due to daylight savings._x000D_
- ((_x000D_
((_x000D_
// Calculate the day of the year in the Gregorian calendar_x000D_
// The code below works based upon the facts of signed right shifts_x000D_
// • (x) >> n: shifts n and fills in the n highest bits with 0s _x000D_
// • (-x) >> n: shifts n and fills in the n highest bits with 1s_x000D_
// (This assumes that x is a positive integer)_x000D_
(31 & ((-fullMonth) >> 4)) + // January // (-11)>>4 = -1_x000D_
((28 + isLeapYear) & ((1-fullMonth) >> 4)) + // February_x000D_
(31 & ((2-fullMonth) >> 4)) + // March_x000D_
(30 & ((3-fullMonth) >> 4)) + // April_x000D_
(31 & ((4-fullMonth) >> 4)) + // May_x000D_
(30 & ((5-fullMonth) >> 4)) + // June_x000D_
(31 & ((6-fullMonth) >> 4)) + // July_x000D_
(31 & ((7-fullMonth) >> 4)) + // August_x000D_
(30 & ((8-fullMonth) >> 4)) + // September_x000D_
(31 & ((9-fullMonth) >> 4)) + // October_x000D_
(30 & ((10-fullMonth) >> 4)) + // November_x000D_
// There are no months past December: the year rolls into the next._x000D_
// Thus, fullMonth is 0-based, so it will never be 12 in Javascript_x000D_
_x000D_
(dateInput.getDate()|0) // get day of the month_x000D_
_x000D_
)&0xffff) * 24 * 60 // 24 hours in a day, 60 minutes in an hour_x000D_
+ (dateInput.getHours()&0xff) * 60 // 60 minutes in an hour_x000D_
+ (dateInput.getMinutes()&0xff)_x000D_
)|0) * 60 * 1000 // 60 seconds in a minute * 1000 milliseconds in a second_x000D_
- (dateInput.getSeconds()&0xff) * 1000 // 1000 milliseconds in a second_x000D_
- dateInput.getMilliseconds()_x000D_
);_x000D_
}_x000D_
_x000D_
// Demonstration:_x000D_
var date = new Date(2100, 0, 1)_x000D_
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))_x000D_
console.log(date.getMonth()+":\t"+dstOffsetAtDate(date)/60/60/1000+"h\t"+date);_x000D_
date = new Date(1900, 0, 1);_x000D_
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))_x000D_
console.log(date.getMonth()+":\t"+dstOffsetAtDate(date)/60/60/1000+"h\t"+date);_x000D_
_x000D_
// Performance Benchmark:_x000D_
console.time("Speed of processing 16384 dates");_x000D_
for (var i=0,month=date.getMonth()|0; i<16384; i=i+1|0)_x000D_
date.setMonth(month=month+1+(dstOffsetAtDate(date)|0)|0);_x000D_
console.timeEnd("Speed of processing 16384 dates");_x000D_
})();
_x000D_
_x000D_
_x000D_
I believe that the above code snippet is superior to all other answers posted here for many reasons.
- This answer works in all time zones, even Antarctica/Casey.
- Daylight savings is very much subject to change. It might be that 20 years from now, some country might have 3 DST periods instead of the normal 2. This code handles that case by returning the DST offset in milliseconds, not just whether DST is in effect or not in effect.
- The size of the months of the year and the way that Leap Years work fits perfectly into keeping our time on track with the sun. Heck, it works so perfectly that all we ever do is just adjust mere seconds here and there. Our current system of leap years has been in effect since February 24th, 1582, and will likely stay in effect for the foreseeable future.
- This code works in timezones that do not use DST.
- This code works in historic times before when DST was implemented (such as the 1900s).
- This code is maximally integer-optimized and should give you no problem if called in a tight loop. After running the code snippet above, scroll down to the bottom of the output to see the performance benchmark. My computer is able to process 16384 dates in ~97ms on Chrome.
However, if you are not preparing for over 2 DST periods, then the below code can be used to determine whether DST is in effect as a boolean.
function isDaylightSavingsInEffect(dateInput) {
// To satisfy the original question
return dstOffsetAtDate(dateInput) !== 0;
}
How to stop docker under Linux
if you have no systemctl and started the docker daemon by:
sudo service docker start
you can stop it by:
sudo service docker stop
pip install mysql-python fails with EnvironmentError: mysql_config not found
It seems mysql_config is missing on your system or the installer could not find it.
Be sure mysql_config is really installed.
For example on Debian/Ubuntu you must install the package:
sudo apt-get install libmysqlclient-dev
Maybe the mysql_config is not in your path, it will be the case when you compile by yourself
the mysql suite.
Update: For recent versions of debian/ubuntu (as of 2018) it is
sudo apt install default-libmysqlclient-dev
How is attr_accessible used in Rails 4?
Rails 4 now uses strong parameters.
Protecting attributes is now done in the controller. This is an example:
class PeopleController < ApplicationController
def create
Person.create(person_params)
end
private
def person_params
params.require(:person).permit(:name, :age)
end
end
No need to set attr_accessible
in the model anymore.
Dealing with accepts_nested_attributes_for
In order to use accepts_nested_attribute_for
with strong parameters, you will need to specify which nested attributes should be whitelisted.
class Person
has_many :pets
accepts_nested_attributes_for :pets
end
class PeopleController < ApplicationController
def create
Person.create(person_params)
end
# ...
private
def person_params
params.require(:person).permit(:name, :age, pets_attributes: [:name, :category])
end
end
Keywords are self-explanatory, but just in case, you can find more information about strong parameters in the Rails Action Controller guide.
Note: If you still want to use attr_accessible
, you need to add protected_attributes
to your Gemfile
. Otherwise, you will be faced with a RuntimeError
.
NUnit vs. MbUnit vs. MSTest vs. xUnit.net
I wouldn't go with MSTest. Although it's probably the most future proof of the frameworks with Microsoft behind it's not the most flexible solution. It won't run stand alone without some hacks. So running it on a build server other than TFS without installing Visual Studio is hard. The visual studio test-runner is actually slower than Testdriven.Net + any of the other frameworks. And because the releases of this framework are tied to releases of Visual Studio there are less updates and if you have to work with an older VS you're tied to an older MSTest.
I don't think it matters a lot which of the other frameworks you use. It's really easy to switch from one to another.
I personally use XUnit.Net or NUnit depending on the preference of my coworkers. NUnit is the most standard. XUnit.Net is the leanest framework.
Space between two rows in a table?
You can fill the <td/> elements with <div/> elements, and apply any margin to those divs that you like. For a visual space between the rows, you can use a repeating background image on the <tr/> element. (This was the solution I just used today, and it appears to work in both IE6 and FireFox 3, though I didn't test it any further.)
Also, if you're averse to modifying your server code to put <div/>s inside the <td/>s, you can use jQuery (or something similar) to dynamically wrap the <td/> contents in a <div/>, enabling you to apply the CSS as desired.
How do I find out what is hammering my SQL Server?
Run either of these a few second apart. You'll detect the high CPU connection.
Or: stored CPU in a local variable, WAITFOR DELAY, compare stored and current CPU values
select * from master..sysprocesses
where status = 'runnable' --comment this out
order by CPU
desc
select * from master..sysprocesses
order by CPU
desc
May not be the most elegant but it'd effective and quick.
How to resolve Value cannot be null. Parameter name: source in linq?
When you call a Linq statement like this:
// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));
You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:
var count = Enumerable.Count(x, s => s.StartsWith("x"));
So the error you are getting above is because the first parameter, source
(which would be x
in the sample above) is null.
Force index use in Oracle
There is an appropriate index on column_having_index, and its use actually increase performance, but Oracle didn't use it...
You should gather statistics on your table to let optimizer see that index access can help. Using direct hint is not a good practice.
What is the difference between the kernel space and the user space?
The maximum size of address space depends on the length of the address register on the CPU.
On systems with 32-bit address registers, the maximum size of address space is 232 bytes, or 4 GiB.
Similarly, on 64-bit systems, 264 bytes can be addressed.
Such address space is called virtual memory or virtual address space. It is not actually related to physical RAM size.
On Linux platforms, virtual address space is divided into kernel space and user space.
An architecture-specific constant called task size limit, or TASK_SIZE
, marks the position where the split occurs:
On a particular 32-bit system for example, 3 GiB could be occupied for user space and 1 GiB for kernel space.
Each application/program in a Unix-like operating system is a process; each of those has a unique identifier called Process Identifier (or simply Process ID, i.e. PID). Linux provides two mechanisms for creating a process: 1. the fork()
system call, or 2. the exec()
call.
A kernel thread is a lightweight process and also a program under execution.
A single process may consist of several threads sharing the same data and resources but taking different paths through the program code. Linux provides a clone()
system call to generate threads.
Example uses of kernel threads are: data synchronization of RAM, helping the scheduler to distribute processes among CPUs, etc.
no suitable HttpMessageConverter found for response type
If you are using Spring Boot, you might want to make sure you have the Jackson dependency in your classpath. You can do this manually via:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
Or you can use the web starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)
I was having the exact same error in my development environment. In the end all I needed to do in order to fix it was to add:
config.assets.manifest = Rails.root.join("public/assets")
to my config/environments/development.rb file and it fixed it. My final config in development related to assets looks like:
config.assets.compress = false
config.assets.precompile += %w[bootstrap-alerts.js] #Lots of other space separated files
config.assets.compile = false
config.assets.digest = true
config.assets.manifest = Rails.root.join("public/assets")
config.assets.debug = true
Write in body request with HttpClient
Extending your code (assuming that the XML you want to send is in xmlString
) :
String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);
How can I get the executing assembly version?
Two options... regardless of application type you can always invoke:
Assembly.GetExecutingAssembly().GetName().Version
If a Windows Forms application, you can always access via application if looking specifically for product version.
Application.ProductVersion
Using GetExecutingAssembly
for an assembly reference is not always an option. As such, I personally find it useful to create a static helper class in projects where I may need to reference the underlying assembly or assembly version:
// A sample assembly reference class that would exist in the `Core` project.
public static class CoreAssembly
{
public static readonly Assembly Reference = typeof(CoreAssembly).Assembly;
public static readonly Version Version = Reference.GetName().Version;
}
Then I can cleanly reference CoreAssembly.Version
in my code as required.
What's the difference between “mod” and “remainder”?
In C and C++ and many languages, %
is the remainder NOT the modulus operator.
For example in the operation -21 / 4
the integer part is -5
and the decimal part is -.25
. The remainder is the fractional part times the divisor, so our remainder is -1
. JavaScript uses the remainder operator and confirms this
_x000D_
_x000D_
console.log(-21 % 4 == -1);
_x000D_
_x000D_
_x000D_
The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.
Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.
Unable to verify leaf signature
Just putting this here in case it helps someone, my case was different and a bit of an odd mix. I was getting this on a request that was accessed via superagent - the problem had nothing to do with certificates (which were setup properly) and all to do with the fact that I was then passing the superagent result through the async module's waterfall callback. To fix: Instead of passing the entire result, just pass result.body
through the waterfall's callback.
Transition of background-color
Another way of accomplishing this is using animation
which provides more control.
#content #nav a {
background-color: #FF0;
/* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
animation-duration: 1s; /* same as transition duration */
animation-timing-function: linear; /* kind of same as transition timing */
animation-delay: 0ms; /* same as transition delay */
animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
animation-play-state: running; /* can be set dynamically to pause mid animation*/
/* declaring the states of the animation to transition through */
/* optionally add other properties that will change here, or new states (50% etc) */
@keyframes onHoverAnimation {
0% {
background-color: #FF0;
}
100% {
background-color: #AD310B;
}
}
}
#content #nav a:hover {
/* animation wont run unless the element is given the name of the animation. This is set on hover */
animation-name: onHoverAnimation;
}
How to add a title to a html select tag
With a default option having selected attribute
<select>
<option value="" selected>Choose your city</option>
<option value ="sydney">Sydney</option>
<option value ="melbourne">Melbourne</option>
<option value ="cromwell">Cromwell</option>
<option value ="queenstown">Queenstown</option>
</select>
Warning: mysqli_query() expects at least 2 parameters, 1 given. What?
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
Fragments within Fragments
Nested fragments are supported in android 4.2 and later
The Android Support Library also now supports nested fragments, so you can implement nested fragment designs on Android 1.6 and higher.
To nest a fragment, simply call getChildFragmentManager() on the Fragment in which you want to add a fragment. This returns a FragmentManager that you can use like you normally do from the top-level activity to create fragment transactions. For example, here’s some code that adds a fragment from within an existing Fragment class:
Fragment videoFragment = new VideoPlayerFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.video_fragment, videoFragment).commit();
To get more idea about nested fragments, please go through these tutorials
Part 1
Part 2
Part 3
and here is a SO post which discuss about best practices for nested fragments.
Selenium Finding elements by class name in python
As per the HTML:
<html>
<body>
<p class="content">Link1.</p>
</body>
<html>
<html>
<body>
<p class="content">Link2.</p>
</body>
<html>
Two(2) <p>
elements are having the same class content
.
So to filter the elements having the same class i.e. content
and create a list you can use either of the following Locator Strategies:
Using class_name
:
elements = driver.find_elements_by_class_name("content")
Using css_selector
:
elements = driver.find_elements_by_css_selector(".content")
Using xpath
:
elements = driver.find_elements_by_xpath("//*[@class='content']")
Ideally, to click on the element you need to induce WebDriverWait for the visibility_of_all_elements_located()
and you can use either of the following Locator Strategies:
Using CLASS_NAME
:
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "content")))
Using CSS_SELECTOR
:
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".content")))
Using XPATH
:
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='content']")))
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
References
You can find a couple of relevant discussions in:
Web.Config Debug/Release
It is possible using ConfigTransform
build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/
All "web.*.config" transform files will be transformed and output as a
series of "web.*.config.transformed" files in the build output
directory regardless of the chosen build configuration.
The same applies to "app.*.config" transform files in non-web
projects.
and then adding the following target to your *.csproj
.
<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
<TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>
Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.
Display the binary representation of a number in C?
There is no direct format specifier for this in the C language. Although I wrote this quick python snippet to help you understand the process step by step to roll your own.
#!/usr/bin/python
dec = input("Enter a decimal number to convert: ")
base = 2
solution = ""
while dec >= base:
solution = str(dec%base) + solution
dec = dec/base
if dec > 0:
solution = str(dec) + solution
print solution
Explained:
dec = input("Enter a decimal number to convert: ") - prompt the user for numerical input (there are multiple ways to do this in C via scanf for example)
base = 2 - specify our base is 2 (binary)
solution = "" - create an empty string in which we will concatenate our solution
while dec >= base: - while our number is bigger than the base entered
solution = str(dec%base) + solution - get the modulus of the number to the base, and add it to the beginning of our string (we must add numbers right to left using division and remainder method). the str() function converts the result of the operation to a string. You cannot concatenate integers with strings in python without a type conversion.
dec = dec/base - divide the decimal number by the base in preperation to take the next modulo
if dec > 0:
solution = str(dec) + solution - if anything is left over, add it to the beginning (this will be 1, if anything)
print solution - print the final number
When and where to use GetType() or typeof()?
typeof
is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType
is called on an object at runtime. In both cases the result is an object of the type System.Type
containing meta-information on a type.
Example where compile-time and run-time types are equal
string s = "hello";
Type t1 = typeof(string);
Type t2 = s.GetType();
t1 == t2 ==> true
Example where compile-time and run-time types are different
object obj = "hello";
Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType(); // ==> string!
t1 == t2 ==> false
i.e., the compile time type (static type) of the variable obj
is not the same as the runtime type of the object referenced by obj
.
Testing types
If, however, you only want to know whether mycontrol
is a TextBox
then you can simply test
if (mycontrol is TextBox)
Note that this is not completely equivalent to
if (mycontrol.GetType() == typeof(TextBox))
because mycontrol
could have a type that is derived from TextBox
. In that case the first comparison yields true
and the second false
! The first and easier variant is OK in most cases, since a control derived from TextBox
inherits everything that TextBox
has, probably adds more to it and is therefore assignment compatible to TextBox
.
public class MySpecializedTextBox : TextBox
{
}
MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox) ==> true
if (specialized.GetType() == typeof(TextBox)) ==> false
Casting
If you have the following test followed by a cast and T is nullable ...
if (obj is T) {
T x = (T)obj; // The casting tests, whether obj is T again!
...
}
... you can change it to ...
T x = obj as T;
if (x != null) {
...
}
Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as
operator followed by a test for null
is more performing.
Starting with C# 7.0 you can simplify the code by using pattern matching:
if (obj is T t) {
// t is a variable of type T having a non-null value.
...
}
Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:
if (o is int? ni) ===> does NOT compile!
This is because either the value is null
or it is an int
. This works for int? o
as well as for object o = new Nullable<int>(x);
:
if (o is int i) ===> OK!
I like it, because it eliminates the need to access the Nullable<T>.Value
property.
What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?
If you like ascii art:
"VALID"
= without padding:
inputs: 1 2 3 4 5 6 7 8 9 10 11 (12 13)
|________________| dropped
|_________________|
"SAME"
= with zero padding:
pad| |pad
inputs: 0 |1 2 3 4 5 6 7 8 9 10 11 12 13|0 0
|________________|
|_________________|
|________________|
In this example:
- Input width = 13
- Filter width = 6
- Stride = 5
Notes:
"VALID"
only ever drops the right-most columns (or bottom-most rows).
"SAME"
tries to pad evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right, as is the case in this example (the same logic applies vertically: there may be an extra row of zeros at the bottom).
Edit:
About the name:
- With
"SAME"
padding, if you use a stride of 1, the layer's outputs will have the same spatial dimensions as its inputs.
- With
"VALID"
padding, there's no "made-up" padding inputs. The layer only uses valid input data.
Infinity symbol with HTML
You can use the following:
- literal:
8
(if the encoding you use can encode it — UTF-8 can, for example)
- character reference:
∞
(decimal), ∞
(hexadecimal)
- entity reference:
∞
But whether it is displayed correctly does also depend on the font the text is displayed with.
SQL Server Script to create a new user
Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.
Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:
CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO
Here is how you create a User with db_owner privileges using the Login you just declared:
Use YourDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO
Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).
However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.
UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.
"Too many characters in character literal error"
Here's an example:
char myChar = '|';
string myString = "||";
Chars are delimited by single quotes, and strings by double quotes.
The good news is C# switch statements work with strings!
switch (mytoken)
{
case "==":
//Something here.
break;
default:
//Handle when no token is found.
break;
}
Page redirect with successful Ajax request
In your mail3.php file you should trap errors in a try {} catch {}
try {
/*code here for email*/
} catch (Exception $e) {
header('HTTP/1.1 500 Internal Server Error');
}
Then in your success
call you wont have to worry about your errors, because it will never return as a success.
and you can use: window.location.href = "thankyou.php";
inside your success function like Nick stated.
Telegram Bot - how to get a group chat id?
In order to get the group chat id, do as follows:
Add the Telegram BOT to the group.
Get the list of updates for your BOT:
https://api.telegram.org/bot<YourBOTToken>/getUpdates
Ex:
https://api.telegram.org/bot123456789:jbd78sadvbdy63d37gda37bd8/getUpdates
Look for the "chat" object:
{"update_id":8393,"message":{"message_id":3,"from":{"id":7474,"first_name":"AAA"},"chat":{"id":,"title":""},"date":25497,"new_chat_participant":{"id":71,"first_name":"NAME","username":"YOUR_BOT_NAME"}}}
This is a sample of the response when you add your BOT into a group.
- Use the "id" of the "chat" object to send your messages.
Static Initialization Blocks
If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:
public class Foo {
private static final int widgets;
static {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
widgets = first + second;
}
}
If first
and second
weren't in a block, they'd look like fields. If they were in a block without static
in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.
Now in this particular case, you could use a static method instead:
public class Foo {
private static final int widgets = getWidgets();
static int getWidgets() {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
return first + second;
}
}
... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).
How to export specific request to file using postman?
The workaround is to export the collection as explained in other answers or references. This will export all requests in that collection to JSON file.
Then edit the JSON file to remove the requests you do not want using any editor; this is very simple.
Look for "item"
collection in file. This contains all your requests; one in each item. Remove the items you do not want to keep.
If you import this edited file in Postman where original collection already exists, Postman will ask you if you want to replace it or create a copy. If you want to avoid this, you may consider changing "_postman_id"
and "name"
under "info"
. If original collection will not exist while importing edited collection, then this change is not needed.
RegEx for matching UK Postcodes
Most of the answers here didn't work for all the postcodes I have in my database. I finally found one that validates with all, using the new regex provided by the government:
https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf
It isn't in any of the previous answers so I post it here in case they take the link down:
^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
UPDATE: Updated regex as pointed by Jamie Bull. Not sure if it was my error copying or it was an error in the government's regex, the link is down now...
UPDATE: As ctwheels found, this regex works with the javascript regex flavor. See his comment for one that works with the pcre (php) flavor.
Building executable jar with maven?
The answer of Pascal Thivent helped me out, too.
But if you manage your plugins within the <pluginManagement>
element, you have to define the assembly again outside of the plugin management, or else the dependencies are not packed in the jar if you run mvn install
.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>main.App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins> <!-- did NOT work without this -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<!-- dependencies commented out to shorten example -->
</dependencies>
</project>
How to keep Docker container running after starting services?
Motivation:
There is nothing wrong in running multiple processes inside of a docker container. If one likes to use docker as a light weight VM - so be it. Others like to split their applications into micro services. Me thinks: A LAMP stack in one container? Just great.
The answer:
Stick with a good base image like the phusion base image. There may be others. Please comment.
And this is yet just another plead for supervisor. Because the phusion base image is providing supervisor besides of some other things like cron and locale setup. Stuff you like to have setup when running such a light weight VM. For what it's worth it also provides ssh connections into the container.
The phusion image itself will just start and keep running if you issue this basic docker run statement:
moin@stretchDEV:~$ docker run -d phusion/baseimage
521e8a12f6ff844fb142d0e2587ed33cdc82b70aa64cce07ed6c0226d857b367
moin@stretchDEV:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS
521e8a12f6ff phusion/baseimage "/sbin/my_init" 12 seconds ago Up 11 seconds
Or dead simple:
If a base image is not for you... For the quick CMD to keep it running I would suppose something like this for bash:
CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"
Or this for busybox:
CMD exec /bin/sh -c "trap : TERM INT; (while true; do sleep 1000; done) & wait"
This is nice, because it will exit immediately on a docker stop
. Just plain sleep
or cat
will take a few seconds before the container exits.
Alternative to file_get_contents?
Use cURL. This function is an alternative to file_get_contents
.
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
Dependency Injection vs Factory Pattern
Binoj,
I don't think you have to choose one over the other.
The act of moving a dependent class or interface to a class constructor or setter follows the DI pattern. The object you pass to the constructor or set can be implemented with Factory.
When to use? Use the pattern or patterns that are in your developer wheelhouse. What do they feel the most comfortable with and find easiest to understand.
How can I get enum possible values in a MySQL database?
You can parse the string as though it was a CSV (Comma Separated Value) string. PHP has a great build-in function called str_getcsv which converts a CSV string to an array.
// This is an example to test with
$enum_or_set = "'blond','brunette','redhead'";
// Here is the parser
$options = str_getcsv($enum_or_set, ',', "'");
// Output the value
print_r($options);
This should give you something similar to the following:
Array
(
[0] => blond
[1] => brunette
[2] => redhead
)
This method also allows you to have single quotes in your strings (notice the use of two single quotes):
$enum_or_set = "'blond','brunette','red''head'";
Array
(
[0] => blond
[1] => brunette
[2] => red'head
)
For more information on the str_getcsv function, check the PHP manual:
http://uk.php.net/manual/en/function.str-getcsv.php
Adding Python Path on Windows 7
For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.
How do you find out the caller function in JavaScript?
Another way around this problem is to simply pass the name of the calling function as a parameter.
For example:
function reformatString(string, callerName) {
if (callerName === "uid") {
string = string.toUpperCase();
}
return string;
}
Now, you could call the function like this:
function uid(){
var myString = "apples";
reformatString(myString, function.name);
}
My example uses a hard coded check of the function name, but you could easily use a switch statement or some other logic to do what you want there.
How do I pass a list as a parameter in a stored procedure?
The preferred method for passing an array of values to a stored procedure in SQL server is to use table valued parameters.
First you define the type like this:
CREATE TYPE UserList AS TABLE ( UserID INT );
Then you use that type in the stored procedure:
create procedure [dbo].[get_user_names]
@user_id_list UserList READONLY,
@username varchar (30) output
as
select last_name+', '+first_name
from user_mstr
where user_id in (SELECT UserID FROM @user_id_list)
So before you call that stored procedure, you fill a table variable:
DECLARE @UL UserList;
INSERT @UL VALUES (5),(44),(72),(81),(126)
And finally call the SP:
EXEC dbo.get_user_names @UL, @username OUTPUT;
Unable to load DLL 'SQLite.Interop.dll'
I ran across this problem, in a solution with a WebAPI/MVC5 web project and a Feature Test project, that both drew off of the same data access (or, 'Core') project. I, like so many others here, am using a copy downloaded via NuGet in Visual Studio 2013.
What I did, was in Visual Studio added a x86 and x64 solution folder to the Feature Test and Web Projects. I then did a Right Click | Add Existing Item...
, and added the appropriate SQLite.interop.dll library from ..\SolutionFolder\packages\System.Data.SQLite.Core.1.0.94.0\build\net451\[appropriate architecture]
for each of those folders. I then did a Right Click | Properties
, and set Copy to Output Directory
to Always Copy
. The next time I needed to run my feature tests, the tests ran successfully.
Determining if a number is prime
I Have Use This Idea For Finding If The No. Is Prime or Not:
#include <conio.h>
#include <iostream>
using namespace std;
int main() {
int x, a;
cout << "Enter The No. :";
cin >> x;
int prime(unsigned int);
a = prime(x);
if (a == 1)
cout << "It Is A Prime No." << endl;
else
if (a == 0)
cout << "It Is Composite No." << endl;
getch();
}
int prime(unsigned int x) {
if (x == 1) {
cout << "It Is Neither Prime Nor Composite";
return 2;
}
if (x == 2 || x == 3 || x == 5 || x == 7)
return 1;
if (x % 2 != 0 && x % 3 != 0 && x % 5 != 0 && x % 7 != 0)
return 1;
else
return 0;
}
#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel
I had the same issue as all of our servers run older versions of MySQL. This can be solved by running a PHP script. Save this code to a file and run it entering the database name, user and password and it'll change the collation from utf8mb4/utf8mb4_unicode_ci
to utf8/utf8_general_ci
<!DOCTYPE html>
<html>
<head>
<title>DB-Convert</title>
<style>
body { font-family:"Courier New", Courier, monospace; }
</style>
</head>
<body>
<h1>Convert your Database to utf8_general_ci!</h1>
<form action="db-convert.php" method="post">
dbname: <input type="text" name="dbname"><br>
dbuser: <input type="text" name="dbuser"><br>
dbpass: <input type="text" name="dbpassword"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_POST) {
$dbname = $_POST['dbname'];
$dbuser = $_POST['dbuser'];
$dbpassword = $_POST['dbpassword'];
$con = mysql_connect('localhost',$dbuser,$dbpassword);
if(!$con) { echo "Cannot connect to the database ";die();}
mysql_select_db($dbname);
$result=mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {
foreach ($tables as $key => $value) {
mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}}
echo "<script>alert('The collation of your database has been successfully changed!');</script>";
}
?>
Importing images from a directory (Python) to list or dictionary
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f)))
Fragment onCreateView and onActivityCreated called twice
It looks to me like it's because you are instantiating your TabListener every time... so the system is recreating your fragment from the savedInstanceState and then you are doing it again in your onCreate.
You should wrap that in a if(savedInstanceState == null)
so it only fires if there is no savedInstanceState.
Apache HttpClient Interim Error: NoHttpResponseException
Most likely persistent connections that are kept alive by the connection manager become stale. That is, the target server shuts down the connection on its end without HttpClient being able to react to that event, while the connection is being idle, thus rendering the connection half-closed or 'stale'. Usually this is not a problem. HttpClient employs several techniques to verify connection validity upon its lease from the pool. Even if the stale connection check is disabled and a stale connection is used to transmit a request message the request execution usually fails in the write operation with SocketException and gets automatically retried. However under some circumstances the write operation can terminate without an exception and the subsequent read operation returns -1 (end of stream). In this case HttpClient has no other choice but to assume the request succeeded but the server failed to respond most likely due to an unexpected error on the server side.
The simplest way to remedy the situation is to evict expired connections and connections that have been idle longer than, say, 1 minute from the pool after a period of inactivity. For details please see this section of the HttpClient tutorial.
How can we draw a vertical line in the webpage?
There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0;
and bottom:0;
style.
Try this:
CSS
.vr {
width:10px;
background-color:#000;
position:absolute;
top:0;
bottom:0;
left:150px;
}
HTML
<div class="vr"> </div>
Demo
Can I set a TTL for @Cacheable
When using Redis, TTL can be set in properties file like this:
spring.cache.redis.time-to-live=1d # 1 day
spring.cache.redis.time-to-live=5m # 5 minutes
spring.cache.redis.time-to-live=10s # 10 seconds
How to get height of entire document with JavaScript?
Full Document height calculation:
To be more generic and find the height of any document you could just find the highest DOM Node on current page with a simple recursion:
;(function() {
var pageHeight = 0;
function findHighestNode(nodesList) {
for (var i = nodesList.length - 1; i >= 0; i--) {
if (nodesList[i].scrollHeight && nodesList[i].clientHeight) {
var elHeight = Math.max(nodesList[i].scrollHeight, nodesList[i].clientHeight);
pageHeight = Math.max(elHeight, pageHeight);
}
if (nodesList[i].childNodes.length) findHighestNode(nodesList[i].childNodes);
}
}
findHighestNode(document.documentElement.childNodes);
// The entire page height is found
console.log('Page height is', pageHeight);
})();
You can Test it on your sample sites (http://fandango.com/ or http://paperbackswap.com/) with pasting this script to a DevTools Console.
NOTE: it is working with Iframes
.
Enjoy!
How to remove the URL from the printing page?
In Google Chrome, this can be done by setting the margins to 0, or if it prints funky, then adjusting it just enough to push the unwanted text to the non-printable areas of the page. I tried it and it works :D
CSS scrollbar style cross browser
As of IE6 I believe you cannot customize the scroll bar using those properties. The Chris Coyier article linked to above goes into nice detail about the options for webkit proprietary css for customizing the scroll bar.
If you really want a cross browser solution that you can fully customize you're going to have to use some JS. Here is a link to a nice plugin for it called FaceScroll: http://www.dynamicdrive.com/dynamicindex11/facescroll/index.htm
How to read and write excel file
Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.
Import data
try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
rowStream
// skip the header row that contains the column names
.skip(1)
.forEach(row -> {
System.out.println(
"row n°" + row.rowIndex()
+ " column 'User login' value : " + row.cell("User login").asString()
+ " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
);
});
}
Export data
Windmill
.export(Arrays.asList(bean1, bean2, bean3))
.withHeaderMapping(
new ExportHeaderMapping<Bean>()
.add("Name", Bean::getName)
.add("User login", bean -> bean.getUser().getLogin())
)
.asExcel()
.writeTo(new FileOutputStream("Export.xlsx"));
ORACLE and TRIGGERS (inserted, updated, deleted)
I've changed my code like this and it works:
CREATE or REPLACE TRIGGER test001
AFTER INSERT OR UPDATE OR DELETE ON tabletest001
REFERENCING OLD AS old_buffer NEW AS new_buffer
FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00')
DECLARE
Operation NUMBER;
CustomerCode CHAR(10 BYTE);
BEGIN
IF DELETING THEN
Operation := 3;
CustomerCode := :old_buffer.field1;
END IF;
IF INSERTING THEN
Operation := 1;
CustomerCode := :new_buffer.field1;
END IF;
IF UPDATING THEN
Operation := 2;
CustomerCode := :new_buffer.field1;
END IF;
// DO SOMETHING ...
EXCEPTION
WHEN OTHERS THEN ErrorCode := SQLCODE;
END;
Why do we use volatile keyword?
Consider this code,
int some_int = 100;
while(some_int == 100)
{
//your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int
, so it may be tempted to optimize the while
loop by changing it from while(some_int == 100)
to something which is equivalent to while(true)
so that the execution could be fast (since the condition in while
loop appears to be true
always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int
and compare it with 100, in each iteration which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while
loop. That is where the volatile
keyword plays its role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!
In other words, I would explain this as follows:
volatile
tells the compiler that,
"Hey compiler, I'm volatile and, you
know, I can be changed by some XYZ
that you're not even aware of. That
XYZ could be anything. Maybe some
alien outside this planet called
program. Maybe some lightning, some
form of interrupt, volcanoes, etc can
mutate me. Maybe. You never know who
is going to change me! So O you
ignorant, stop playing an all-knowing
god, and don't dare touch the code
where I'm present. Okay?"
Well, that is how volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.
Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the
implementation to avoid aggressive
optimization involving the object
because the value of the object might
be changed by means undetectable by an
implementation.[...]
Related topic:
Does making a struct volatile make all its members volatile?
Unresolved reference issue in PyCharm
- --> Right-click on the directory where your files are located in PyCharm
- Go to the --> Mark Directory as
- Select the --> Source Root
your problem will be solved
How to dynamically build a JSON object with Python?
There is already a solution provided which allows building a dictionary, (or nested dictionary for more complex data), but if you wish to build an object, then perhaps try 'ObjDict'. This gives much more control over the json to be created, for example retaining order, and allows building as an object which may be a preferred representation of your concept.
pip install objdict first.
from objdict import ObjDict
data = ObjDict()
data.key = 'value'
json_data = data.dumps()
How to cast an object in Objective-C
Typecasting in Objective-C is easy as:
NSArray *threeViews = @[[UIView new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
However, what happens if first object is not UIView
and you try to use it:
NSArray *threeViews = @[[NSNumber new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
CGRect firstViewFrame = firstView.frame; // CRASH!
It will crash. And it's easy to find such crash for this case, but what if those lines are in different classes and the third line is executed only once in 100 cases. I bet your customers find this crash, not you! A plausible solution is to crash early, like this:
UIView *firstView = (UIView *)threeViews[0];
NSAssert([firstView isKindOfClass:[UIView class]], @"firstView is not UIView");
Those assertions doesn't look very nice, so we could improve them with this handy category:
@interface NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object;
@end
@implementation NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object {
if (object != nil)
NSAssert([object isKindOfClass:[self class]], @"Object %@ is not kind of class %@", object, NSStringFromClass([self class]));
return object;
}
@end
This is much better:
UIView *firstView = [UIView typecastWithAssertion:[threeViews[0]];
P.S. For collections type safety Xcode 7 have a much better than typecasting - generics
How to download a file from a website in C#
Sure, you just use a HttpWebRequest
.
Once you have the HttpWebRequest
set up, you can save the response stream to a file StreamWriter
(Either BinaryWriter
, or a TextWriter
depending on the mimetype.) and you have a file on your hard drive.
EDIT: Forgot about WebClient
. That works good unless as long as you only need to use GET
to retrieve your file. If the site requires you to POST
information to it, you'll have to use a HttpWebRequest
, so I'm leaving my answer up.
Is there a concise way to iterate over a stream with indices in Java 8?
One possible way is to index each element on the flow:
AtomicInteger index = new AtomicInteger();
Stream.of(names)
.map(e->new Object() { String n=e; public i=index.getAndIncrement(); })
.filter(o->o.n.length()<=o.i) // or do whatever you want with pairs...
.forEach(o->System.out.println("idx:"+o.i+" nam:"+o.n));
Using an anonymous class along a stream is not well-used while being very useful.
jQuery selector to get form by name
You have no combinator (space, >
, +
...) so no children will get involved, ever.
However, you could avoid the need for jQuery by using an ID
and getElementById
, or you could use the old getElementsByName("frmSave")[0]
or the even older document.forms['frmSave']
. jQuery is unnecessary here.
Can dplyr join on multiple columns or composite key?
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
HTTP POST with URL query parameters -- good idea or not?
It would be fine to use query parameters on a POST endpoint, provided they refer to already existing resources.
For example:
POST /user_settings?user_id=4
{
"use_safe_mode": 1
}
The POST above has a query parameter referring to an existing resource.
The body parameter defines the new resource to be created.
(Granted, this may be more of a personal preference than a dogmatic principle.)
print memory address of Python variable
id
is the method you want to use: to convert it to hex:
hex(id(variable_here))
For instance:
x = 4
print hex(id(x))
Gave me:
0x9cf10c
Which is what you want, right?
(Fun fact, binding two variables to the same int
may result in the same memory address being used.)
Try:
x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))
This gave me identical pairs, even for the large integers.
Use Fieldset Legend with bootstrap
That's because Bootstrap by default sets the width of the legend
element to 100%. You can fix this by changing your legend.scheduler-border
to also use:
legend.scheduler-border {
width:inherit; /* Or auto */
padding:0 10px; /* To give a bit of padding on the left and right */
border-bottom:none;
}
JSFiddle example.
You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.
You may also want to add margin-bottom:0;
to it as well to reduce the gap between the legend and the divider.
Include an SVG (hosted on GitHub) in MarkDown
I have a working example with an img-tag, but your images won't display.
The difference I see is the content-type.
I checked the github image from your post (the google doc images don't load at all because of connection failures). The image from github is delivered as content-type: text/plain, which won't get rendered as an image by your browser.
The correct content-type value for svg is image/svg+xml. So you have to make sure that svg files set the correct mime type, but that's a server issue.
Try it with http://svg.tutorial.aptico.de/grafik_svg/dummy3.svg and don't forget to specify width and height in the tag.
bootstrap 3 navbar collapse button not working
Just my 2 cents, had:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
at the end of body, wasn't working, had to add crossorigin="anonymous"
and now it's working, Bootstrap version 3.3.6. ...
DropDownList in MVC 4 with Razor
You can use this:
@Html.DropDownListFor(x => x.Tipo, new List<SelectListItem>
{
new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}
})
How can I join multiple SQL tables using the IDs?
You want something more like this:
SELECT TableA.*, TableB.*, TableC.*, TableD.*
FROM TableA
JOIN TableB
ON TableB.aID = TableA.aID
JOIN TableC
ON TableC.cID = TableB.cID
JOIN TableD
ON TableD.dID = TableA.dID
WHERE DATE(TableC.date)=date(now())
In your example, you are not actually including TableD
. All you have to do is perform another join just like you have done before.
A note: you will notice that I removed many of your parentheses, as they really are not necessary in most of the cases you had them, and only add confusion when trying to read the code. Proper nesting is the best way to make your code readable and separated out.
How to send email by using javascript or jquery
You can do it server-side with nodejs.
Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!
The following example uses SES transport (Amazon SES):
let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
SES: new aws.SES({ apiVersion: "2010-12-01" })
});
How do I create sql query for searching partial matches?
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
Change image source in code behind - Wpf
None of the methods worked for me as i needed to pull the image from a folder instead of adding it to the application.
The below code worked:
TestImage.Source = GetImage("/Content/Images/test.png")
private static BitmapImage GetImage(string imageUri)
{
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageUri, UriKind.RelativeOrAbsolute);
bitmapImage.EndInit();
return bitmapImage;
}
sweet-alert display HTML code in text
There's sweet Alert version 1 and 2.
Actual version 2 works with HTML nodes.
I have a Sweet Alert 2 with a data form that looks this way:
<script>
var form = document.createElement("div");
form.innerHTML = `
<span id="tfHours">0</span> hours<br>
<input style="width:90%;" type="range" name="tfHours" value=0 step=1 min=0 max=25
onchange="window.changeHours(this.value)"
oninput="window.changeHours(this.value)"
><br>
<span id="tfMinutes">0</span> min<br>
<input style="width:60%;" type="range" name="tfMinutes" value=0 step=5 min=0 max=60
onchange="window.changeMinutes(this.value)"
oninput="window.changeMinutes(this.value)"
>`;
swal({
title: 'Request time to XXX',
text: 'Select time to send / request',
content: form,
buttons: {
cancel: "Cancel",
catch: {
text: "Create",
value: 5,
},
}
}).then((value) => {
console.log(value);
});
window.changeHours = function (value){
var tfHours = document.getElementById("tfHours");
tfHours.innerHTML = value;
}
window.changeMinutes = function (value){
var tfMinutes = document.getElementById("tfMinutes");
tfMinutes.innerHTML = value;
}
Have a go to the Codepen Example!
Artificially create a connection timeout error
You might install Microsoft Loopback driver that will create a separate interface for you. Then you can connect on it to some service of yours (your own host). Then in Network Connections you can disable/enable such interface...
Implementing a simple file download servlet
And to send a largFile
byte[] pdfData = getPDFData();
String fileType = "";
res.setContentType("application/pdf");
httpRes.setContentType("application/.pdf");
httpRes.addHeader("Content-Disposition", "attachment; filename=IDCards.pdf");
httpRes.setStatus(HttpServletResponse.SC_OK);
OutputStream out = res.getOutputStream();
System.out.println(pdfData.length);
out.write(pdfData);
System.out.println("sendDone");
out.flush();
Split a string into array in Perl
I found this one to be very simple!
my $line = "file1.gz file2.gz file3.gz";
my @abc = ($line =~ /(\w+[.]\w+)/g);
print $abc[0],"\n";
print $abc[1],"\n";
print $abc[2],"\n";
output:
file1.gz
file2.gz
file3.gz
Here take a look at this tutorial to find more on Perl regular expression and scroll down to More matching section.
Calendar date to yyyy-MM-dd format in java
java.util.Date
object can't represent date in custom format instead you've to use SimpleDateFormat.format
method that returns string
.
String myString=format1.format(date);
Camera access through browser
I think this one is working.
Recording a video or audio;
<input type="file" accept="video/*;capture=camcorder">
<input type="file" accept="audio/*;capture=microphone">
or (new method)
<device type="media" onchange="update(this.data)"></device>
<video autoplay></video>
<script>
function update(stream) {
document.querySelector('video').src = stream.url;
}
</script>
If it is not, probably will work on ios6, more detail can be found at get user media
Converting NumPy array into Python List structure?
tolist()
works fine even if encountered a nested array, say a pandas DataFrame
;
my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]
print(type(my_list),type(my_dt),type(new_list))
How to fast get Hardware-ID in C#?
The following approach was inspired by this answer to a related (more general) question.
The approach is to read the MachineGuid
value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
. This value is generated during OS installation.
There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid
value.
However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.
public string GetMachineGuid()
{
string location = @"SOFTWARE\Microsoft\Cryptography";
string name = "MachineGuid";
using (RegistryKey localMachineX64View =
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
{
if (rk == null)
throw new KeyNotFoundException(
string.Format("Key Not Found: {0}", location));
object machineGuid = rk.GetValue(name);
if (machineGuid == null)
throw new IndexOutOfRangeException(
string.Format("Index Not Found: {0}", name));
return machineGuid.ToString();
}
}
}
How to print variable addresses in C?
To print the address of a variable, you need to use the %p
format. %d
is for signed integers. For example:
#include<stdio.h>
void main(void)
{
int a;
printf("Address is %p:",&a);
}