Programs & Examples On #Cqrs

Command-Query Responsibility Segregation (CQRS) is an architectural pattern which separates commands (that change the data) from queries (that read the data). See 'about cqrs tag' for more details and references to learning materials. Not to be confused with Command-Query Segregation ([CQS]), a principle of object method design which CQRS incorporates.

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

And yet another option: https://github.com/apptik/jus

  • It is modular like Volley, but more extended and documentation is improving, supporting different HTTP stacks and converters out of the box
  • It has a module to generate server API interface mappings like Retrofit
  • It also has JavaRx support

And many other handy features like markers, transformers, etc.

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

We can do something like this

DateTime date_temp_from = DateTime.Parse(from.Value); //from.value" is input by user (dd/MM/yyyy)
DateTime date_temp_to = DateTime.Parse(to.Value); //to.value" is input by user (dd/MM/yyyy)

string date_from = date_temp_from.ToString("yyyy/MM/dd HH:mm");
string date_to = date_temp_to.ToString("yyyy/MM/dd HH:mm");

Thank you

Turn a number into star rating display using jQuery and CSS

I ended up going totally JS-free to avoid client-side render lag. To accomplish that, I generate HTML like this:

<span class="stars" title="{value as decimal}">
    <span style="width={value/5*100}%;"/>
</span>

To help with accessibility, I even add the raw rating value in the title attribute.

Check if a string is a valid Windows directory (folder) path

Here is a solution that leverages the use of Path.GetFullPath as recommended in the answer by @SLaks.

In the code that I am including here, note that IsValidPath(string path) is designed such that the caller does not have to worry about exception handling.

You may also find that the method that it calls, TryGetFullPath(...), also has merit on its own when you wish to safely attempt to get an absolute path.

/// <summary>
/// Gets a value that indicates whether <paramref name="path"/>
/// is a valid path.
/// </summary>
/// <returns>Returns <c>true</c> if <paramref name="path"/> is a
/// valid path; <c>false</c> otherwise. Also returns <c>false</c> if
/// the caller does not have the required permissions to access
/// <paramref name="path"/>.
/// </returns>
/// <seealso cref="Path.GetFullPath"/>
/// <seealso cref="TryGetFullPath"/>
public static bool IsValidPath(string path)
{
    string result;
    return TryGetFullPath(path, out result);
}

/// <summary>
/// Returns the absolute path for the specified path string. A return
/// value indicates whether the conversion succeeded.
/// </summary>
/// <param name="path">The file or directory for which to obtain absolute
/// path information.
/// </param>
/// <param name="result">When this method returns, contains the absolute
/// path representation of <paramref name="path"/>, if the conversion
/// succeeded, or <see cref="String.Empty"/> if the conversion failed.
/// The conversion fails if <paramref name="path"/> is null or
/// <see cref="String.Empty"/>, or is not of the correct format. This
/// parameter is passed uninitialized; any value originally supplied
/// in <paramref name="result"/> will be overwritten.
/// </param>
/// <returns><c>true</c> if <paramref name="path"/> was converted
/// to an absolute path successfully; otherwise, false.
/// </returns>
/// <seealso cref="Path.GetFullPath"/>
/// <seealso cref="IsValidPath"/>
public static bool TryGetFullPath(string path, out string result)
{
    result = String.Empty;
    if (String.IsNullOrWhiteSpace(path)) { return false; }
    bool status = false;

    try
    {
        result = Path.GetFullPath(path);
        status = true;
    }
    catch (ArgumentException) { }
    catch (SecurityException) { }
    catch (NotSupportedException) { }
    catch (PathTooLongException) { }

    return status;
}

How to set up gradle and android studio to do release build?

This is a procedure to configure run release version

1- Change build variants to release version.

enter image description here

2- Open project structure. enter image description here

3- Change default config to $signingConfigs.release enter image description here

Is it possible to get the index you're sorting over in Underscore.js?

I think it's worth mentioning how the Underscore's _.each() works internally. The _.each(list, iteratee) checks if the passed list is an array object, or an object.

In the case that the list is an array, iteratee arguments will be a list element and index as in the following example:

var a = ['I', 'like', 'pancakes', 'a', 'lot', '.'];
_.each( a, function(v, k) { console.log( k + " " + v); });

0 I
1 like
2 pancakes
3 a
4 lot
5 .

On the other hand, if the list argument is an object the iteratee will take a list element and a key:

var o = {name: 'mike', lastname: 'doe', age: 21};
_.each( o, function(v, k) { console.log( k + " " + v); });

name mike
lastname doe
age 21

For reference this is the _.each() code from Underscore.js 1.8.3

_.each = _.forEach = function(obj, iteratee, context) {
   iteratee = optimizeCb(iteratee, context);
   var i, length;
   if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
         iteratee(obj[i], i, obj);
      }
   } else {
      var keys = _.keys(obj);
      for (i = 0, length = keys.length; i < length; i++) {
         iteratee(obj[keys[i]], keys[i], obj);
      }
   }
   return obj;
};

jQuery’s .bind() vs. .on()

The direct methods and .delegate are superior APIs to .on and there is no intention of deprecating them.

The direct methods are preferable because your code will be less stringly typed. You will get immediate error when you mistype an event name rather than a silent bug. In my opinion, it's also easier to write and read click than on("click"

The .delegate is superior to .on because of the argument's order:

$(elem).delegate( ".selector", {
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
});

You know right away it's delegated because, well, it says delegate. You also instantly see the selector.

With .on it's not immediately clear if it's even delegated and you have to look at the end for the selector:

$(elem).on({
    click: function() {
    },
    mousemove: function() {
    },
    mouseup: function() {
    },
    mousedown: function() {
    }
}, "selector" );

Now, the naming of .bind is really terrible and is at face value worse than .on. But .delegate cannot do non-delegated events and there are events that don't have a direct method, so in a rare case like this it could be used but only because you want to make a clean separation between delegated and non-delegated events.

How can I set a website image that will show as preview on Facebook?

If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:

<meta property="og:image" content="/uploads/..." />

just replacing /uploads/... with the copied image address. Click Publish to apply the change.

You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.

UML class diagram enum

They are simply showed like this:

_______________________
|   <<enumeration>>   |
|    DaysOfTheWeek    |
|_____________________|
| Sunday              |
| Monday              |
| Tuesday             |
| ...                 |
|_____________________|

And then just have an association between that and your class.

MySQL Data Source not appearing in Visual Studio

I tried to install to VS 2015 using the Web installer. It seemed to work, but there was still no MySQL entry for Data Connections. I ended up going to http://dev.mysql.com/downloads/windows/visualstudio/, using it to uninstall then re-install the connector. Not it works as expected.

using setTimeout on promise chain

.then(() => new Promise((resolve) => setTimeout(resolve, 15000)))

UPDATE:

when I need sleep in async function I throw in

await new Promise(resolve => setTimeout(resolve, 1000))

How to grep for two words existing on the same line?

Use grep:

grep -wE "string1|String2|...." file_name

Or you can use:

echo string | grep -wE "string1|String2|...."

Does Python have a package/module management system?

The Python Package Index (PyPI) seems to be standard:

  • To install a package: pip install MyProject
  • To update a package pip install --upgrade MyProject
  • To fix a version of a package pip install MyProject==1.0

You can install the package manager as follows:

curl -O http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

References:

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

I faced this issue when moved from Android 7(Nougat) to Android 8(Oreo).

I have tried several ways listed above and to my bad luck nothing worked.

So i changed the .apk file to .zip file extracted it and found lib folder with which this file was there /x86_64/darwin/libscrypt.dylib so to remove this i added a code in my build.gradle module below android section (i.e.)

packagingOptions {
    exclude 'lib/x86_64/darwin/libscrypt.dylib'
    exclude 'lib/x86_64/freebsd/libscrypt.so'
    exclude 'lib/x86_64/linux/libscrypt.so'
}

Cheers issue solved

how to bind img src in angular 2 in ngFor?

Angular 2.x to 8 Compatible!

You can directly give the source property of the current object in the img src attribute. Please see my code below:

<div *ngFor="let brochure of brochureList">
    <img class="brochure-poster" [src]="brochure.imageUrl" />
</div>

NOTE: You can as well use string interpolation but that is not a legit way to do it. Property binding was created for this very purpose hence better use this.

NOT RECOMMENDED :

<img class="brochure-poster" src="{{brochure.imageUrl}}"/>

Its because that defeats the purpose of property binding. It is more meaningful to use that for setting the properties. {{}} is a normal string interpolation expression, that does not reveal to anyone reading the code that it makes special meaning. Using [] makes it easily to spot the properties that are set dynamically.

Here is my brochureList contains the following json received from service(you can assign it to any variable):

[ {
            "productId":1,
            "productName":"Beauty Products",
            "productCode": "XXXXXX",            
            "description":  "Skin Care",           
            "imageUrl":"app/Images/c1.jpg"
         },
        {
             "productId":2,
            "productName":"Samsung Galaxy J5",
            "productCode": "MOB-124",      
            "description":  "8GB, Gold",
            "imageUrl":"app/Images/c8.jpg"
         }]

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

I got this error, with angular 7, what helped me is, From the windows power shell I run the command:

npm install --global --production windows-build-tools

then again I reopen my VS Code, on it's terminal I run the same command npm uninstall node-sass and npm install node-sass

Why am I not getting a java.util.ConcurrentModificationException in this example?

Here's why: As it is says in the Javadoc:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

This check is done in the next() method of the iterator (as you can see by the stacktrace). But we will reach the next() method only if hasNext() delivered true, which is what is called by the for each to check if the boundary is met. In your remove method, when hasNext() checks if it needs to return another element, it will see that it returned two elements, and now after one element was removed the list only contains two elements. So all is peachy and we are done with iterating. The check for concurrent modifications does not occur, as this is done in the next() method which is never called.

Next we get to the second loop. After we remove the second number the hasNext method will check again if can return more values. It has returned two values already, but the list now only contains one. But the code here is:

public boolean hasNext() {
        return cursor != size();
}

1 != 2, so we continue to the next() method, which now realizes that someone has been messing with the list and fires the exception.

Hope that clears your question up.

Summary

List.remove() will not throw ConcurrentModificationException when it removes the second last element from the list.

textarea's rows, and cols attribute in CSS

I just wanted to post a demo using calc() for setting rows/height, since no one did.

_x000D_
_x000D_
body {_x000D_
  /* page default */_x000D_
  font-size: 15px;_x000D_
  line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
  /* demo related */_x000D_
  width: 300px;_x000D_
  margin-bottom: 1em;_x000D_
  display: block;_x000D_
  _x000D_
  /* rows related */_x000D_
  font-size: inherit;_x000D_
  line-height: inherit;_x000D_
  padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
  /* height: calc(font-size * line-height * rows); */_x000D_
  height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
  /* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
  height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
_x000D_
_x000D_

If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.

git push vs git push origin <branchname>

The first push should be a:

git push -u origin branchname

That would make sure:

Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.

shell-script headers (#!/bin/sh vs #!/bin/csh)

This is known as a Shebang:

http://en.wikipedia.org/wiki/Shebang_(Unix)

#!interpreter [optional-arg]

A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).

When a shell executes the script it will use the specified interpreter.

Example:

#!/bin/bash
# file: foo.sh
echo 1

$ chmod u+x foo.sh
$ ./foo.sh
  1

Get checkbox list values with jQuery

Not tested but should work:

$("#MyDiv td input:checked").each(function()
{
    alert($(this).attr("id"));
});

invalid new-expression of abstract class type

for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like

class Base 
{
  public:
      virtual void foo(int a, const int b) = 0;
}
class D: public Base 
{
 public:
     void foo(int a, int b){};
}

What is the memory consumption of an object in Java?

The question will be a very broad one.

It depends on the class variable or you may call as states memory usage in java.

It also has some additional memory requirement for headers and referencing.

The heap memory used by a Java object includes

  • memory for primitive fields, according to their size (see below for Sizes of primitive types);

  • memory for reference fields (4 bytes each);

  • an object header, consisting of a few bytes of "housekeeping" information;

Objects in java also requires some "housekeeping" information, such as recording an object's class, ID and status flags such as whether the object is currently reachable, currently synchronization-locked etc.

Java object header size varies on 32 and 64 bit jvm.

Although these are the main memory consumers jvm also requires additional fields sometimes like for alignment of the code e.t.c.

Sizes of primitive types

boolean & byte -- 1

char & short -- 2

int & float -- 4

long & double -- 8

How do you clear Apache Maven's cache?

I would do the following:

mvn dependency:purge-local-repository -DactTransitively=false -DreResolve=false --fail-at-end

The flags tell maven not to try to resolve dependencies or hit the network. Delete what you see locally.

And for good measure, ignore errors (--fail-at-end) till the very end. This is sometimes useful for projects that have a somewhat messed up set of dependencies or rely on a somewhat messed up internal repository (it happens.)

Loop through an array php

You can use also this without creating additional variables nor copying the data in the memory like foreach() does.

while (false !== (list($item, $values) = each($array)))
{
    ...
}

how to make a cell of table hyperlink

I have seen this before when people are trying to build a calendar. You want the cell linked but do not want to mess with anything else inside of it, try this and it might solve your problem.

<tr>
<td onClick="location.href='http://www.stackoverflow.com';">
Cell content goes here
</td>
</tr>

How to subtract X day from a Date object in Java?

I have created a function to make the task easier.

  • For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);

  • To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);


public static String dateCalculate(String dateString, String dateFormat, int days) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat s = new SimpleDateFormat(dateFormat);
    try {
        cal.setTime(s.parse(dateString));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    cal.add(Calendar.DATE, days);
    return s.format(cal.getTime());
}

How to serialize Joda DateTime with Jackson JSON processor?

Meanwhile Jackson registers the Joda module automatically when the JodaModule is in classpath. I just added jackson-datatype-joda to Maven and it worked instantly.

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
  <version>2.8.7</version>
</dependency>

JSON output:

{"created" : "2017-03-28T05:59:27.258Z"}

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Go through C:\apache-tomcat-7.0.47\lib path (this path may be differ based on where you installed the Tomcat server) then past ojdbc14.jar if its not contain.

Then restart the server in eclipse then run your app on server

overlay two images in android to set an imageview

this is my solution:

    public Bitmap Blend(Bitmap topImage1, Bitmap bottomImage1, PorterDuff.Mode Type) {

        Bitmap workingBitmap = Bitmap.createBitmap(topImage1);
        Bitmap topImage = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);

        Bitmap workingBitmap2 = Bitmap.createBitmap(bottomImage1);
        Bitmap bottomImage = workingBitmap2.copy(Bitmap.Config.ARGB_8888, true);

        Rect dest = new Rect(0, 0, bottomImage.getWidth(), bottomImage.getHeight());
        new BitmapFactory.Options().inPreferredConfig = Bitmap.Config.ARGB_8888;
        bottomImage.setHasAlpha(true);
        Canvas canvas = new Canvas(bottomImage);
        Paint paint = new Paint();

        paint.setXfermode(new PorterDuffXfermode(Type));

        paint.setFilterBitmap(true);
        canvas.drawBitmap(topImage, null, dest, paint);
        return bottomImage;
    }

usage :

imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.SCREEN));

or

imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.OVERLAY));

and the results :

Overlay mode : Overlay mode

Screen mode: Screen mode

Python Error: "ValueError: need more than 1 value to unpack"

You should run your code in a following manner in order get your output,

python file_name.py user_name

How to pass a value from one jsp to another jsp page?

Use sessions

On your search.jsp

Put your scard in sessions using session.setAttribute("scard","scard")

//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.

And in your next page you retrieve it using session.getAttribute("scard")

UPDATE

<input type="text" value="<%=session.getAttribute("scard")%>"/>

Is there a way to change the spacing between legend items in ggplot2?

To add spacing between entries in a legend, adjust the margins of the theme element legend.text.

To add 30pt of space to the right of each legend label (may be useful for a horizontal legend):

p + theme(legend.text = element_text(
    margin = margin(r = 30, unit = "pt")))

To add 30pt of space to the left of each legend label (may be useful for a vertical legend):

p + theme(legend.text = element_text(
    margin = margin(l = 30, unit = "pt")))

for a ggplot2 object p. The keywords are legend.text and margin.

[Note about edit: When this answer was first posted, there was a bug. The bug has now been fixed]

Does Index of Array Exist

Assuming you also want to check if the item is not null

if (array.Length > 25 && array[25] != null)
{
    //it exists
}

How do I multiply each element in a list by a number?

from functools import partial as p
from operator import mul
map(p(mul,5),my_list)

is one way you could do it ... your teacher probably knows a much less complicated way that was probably covered in class

How to convert a data frame column to numeric type?

with hablar::convert

To easily convert multiple columns to different data types you can use hablar::convert. Simple syntax: df %>% convert(num(a)) converts the column a from df to numeric.

Detailed example

Lets convert all columns of mtcars to character.

df <- mtcars %>% mutate_all(as.character) %>% as_tibble()

> df
# A tibble: 32 x 11
   mpg   cyl   disp  hp    drat  wt    qsec  vs    am    gear  carb 
   <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
 1 21    6     160   110   3.9   2.62  16.46 0     1     4     4    
 2 21    6     160   110   3.9   2.875 17.02 0     1     4     4    
 3 22.8  4     108   93    3.85  2.32  18.61 1     1     4     1    

With hablar::convert:

library(hablar)

# Convert columns to integer, numeric and factor
df %>% 
  convert(int(cyl, vs),
          num(disp:wt),
          fct(gear))

results in:

# A tibble: 32 x 11
   mpg     cyl  disp    hp  drat    wt qsec     vs am    gear  carb 
   <chr> <int> <dbl> <dbl> <dbl> <dbl> <chr> <int> <chr> <fct> <chr>
 1 21        6  160    110  3.9   2.62 16.46     0 1     4     4    
 2 21        6  160    110  3.9   2.88 17.02     0 1     4     4    
 3 22.8      4  108     93  3.85  2.32 18.61     1 1     4     1    
 4 21.4      6  258    110  3.08  3.22 19.44     1 0     3     1   

UILabel text margin

With Swift 3, you can have the desired effect by creating a subclass of UILabel. In this subclass, you will have to add a UIEdgeInsets property with the required insets and override drawText(in:) method, intrinsicContentSize property (for Auto layout code) and/or sizeThatFits(_:) method (for Springs & Struts code).

import UIKit

class PaddingLabel: UILabel {

    let padding: UIEdgeInsets

    // Create a new PaddingLabel instance programamtically with the desired insets
    required init(padding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)) {
        self.padding = padding
        super.init(frame: CGRect.zero)
    }

    // Create a new PaddingLabel instance programamtically with default insets
    override init(frame: CGRect) {
        padding = UIEdgeInsets.zero // set desired insets value according to your needs
        super.init(frame: frame)
    }

    // Create a new PaddingLabel instance from Storyboard with default insets
    required init?(coder aDecoder: NSCoder) {
        padding = UIEdgeInsets.zero // set desired insets value according to your needs
        super.init(coder: aDecoder)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
    }

    // Override `intrinsicContentSize` property for Auto layout code
    override var intrinsicContentSize: CGSize {
        let superContentSize = super.intrinsicContentSize
        let width = superContentSize.width + padding.left + padding.right
        let height = superContentSize.height + padding.top + padding.bottom
        return CGSize(width: width, height: height)
    }

    // Override `sizeThatFits(_:)` method for Springs & Struts code
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let superSizeThatFits = super.sizeThatFits(size)
        let width = superSizeThatFits.width + padding.left + padding.right
        let heigth = superSizeThatFits.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }

}

The following example shows how to use PaddingLabel instances in a UIViewController:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var storyboardAutoLayoutLabel: PaddingLabel!
    let autoLayoutLabel = PaddingLabel(padding: UIEdgeInsets(top: 20, left: 40, bottom: 20, right: 40))
    let springsAndStructsLabel = PaddingLabel(frame: CGRect.zero)
    var textToDisplay = "Lorem ipsum dolor sit er elit lamet."

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set autoLayoutLabel
        autoLayoutLabel.text = textToDisplay
        autoLayoutLabel.backgroundColor = .red
        autoLayoutLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(autoLayoutLabel)
        autoLayoutLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
        autoLayoutLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        // Set springsAndStructsLabel
        springsAndStructsLabel.text = textToDisplay
        springsAndStructsLabel.backgroundColor = .green
        view.addSubview(springsAndStructsLabel)
        springsAndStructsLabel.frame.origin = CGPoint(x: 30, y: 90)
        springsAndStructsLabel.sizeToFit()

        // Set storyboardAutoLayoutLabel
        storyboardAutoLayoutLabel.text = textToDisplay
        storyboardAutoLayoutLabel.backgroundColor = .blue
    }

    // Link this IBAction to a UIButton or a UIBarButtonItem in Storyboard
    @IBAction func updateLabelText(_ sender: Any) {
        textToDisplay = textToDisplay == "Lorem ipsum dolor sit er elit lamet." ? "Lorem ipsum." : "Lorem ipsum dolor sit er elit lamet."

        // autoLayoutLabel
        autoLayoutLabel.text = textToDisplay

        // springsAndStructsLabel
        springsAndStructsLabel.text = textToDisplay
        springsAndStructsLabel.sizeToFit()

        // storyboardAutoLayoutLabel
        storyboardAutoLayoutLabel.text = textToDisplay
    }

}

Can anyone explain IEnumerable and IEnumerator to me?

Explanation via Analogy + Code Walkthrough

First an explanation without code, then I'll add it in later.

Let's say you are running an airline company. And in each plane you want to know information about the passengers flying in the plane. Basically you want to be able to "traverse" the plane. In other words, you want to be able to start at the front seat, and to then work your way towards the back of the plane, asking passengers some information: who they are, where they are from etc. An aeroplane can only do this, if it is:

  1. countable, and
  2. if it has a counter.

Why these requirements? Because that's what the interface requires.

If this is information overload, all you need to know is that you want to be able to ask each passenger in the plane some questions, starting from the first and making your way to the last.

What does countable mean?

If an airline is "countable", this means that there MUST be a flight attendant present on the plane, whose sole job is to count - and this flight attendant MUST count in a very specific manner:

  1. The counter/flight attendant MUST start before the first passenger (at the front of everyone where they demo safety, how to put the life jacket on etc).
  2. He/she (i.e. the flight attendant) MUST "move next" up the aisle to the first seat.
  3. He/she is to then record: (i) who the person is in the seat, and (ii) their current location in the aisle.

Counting Procedures

The captain of the airline wants a report on every passenger as and when they are investigated or counted. So after speaking to the person in the first seat, the flight-attendant/counter then reports to the captain, and when the report is given, the counter remembers his/her exact position in the aisle and continues counting right where he/she left off.

In this manner the captain is always able to have information on the current person being investigated. That way, if he finds out that this individual likes Manchester City, then he can give that passenger preferential treatment etc.

  • The counter keeps going till he reaches the end of the plane.

Let's tie this with the IEnumerables

  • An enumerable is just a collection of passengers on a plane. The Civil Aviation Law - these are basically the rules which all IEnumerables must follow. Everytime the airline attendant goes to the captain with the passeger information, we are basically 'yielding' the passenger to the captain. The captain can basically do whatever he wants with the passenger - except rearranging the passengers on the plane. In this case, they are given preferential treatment if they follow Manchester City (ugh!)

     foreach (Passenger passenger in Plane)
     // the airline hostess is now at the front of the plane
     // and slowly making her way towards the back
     // when she get to a particular passenger she gets some information
     // about the passenger and then immediately heads to the cabin
     // to let the captain decide what to do with it
     { // <---------- Note the curly bracket that is here.
         // we are now cockpit of the plane with the captain.
         // the captain wants to give the passenger free 
         // champaign if they support manchester city
         if (passenger.supports_mancestercity())
         {
             passenger.getFreeChampaign();
         } else
         {
             // you get nothing! GOOD DAY SIR!
         }
     } //  <---- Note the curly bracket that is here!
           the hostess has delivered the information 
           to the captain and goes to the next person
           on the plane (if she has not reached the 
           end of the plane)
    

Summary

In other words, something is countable if it has a counter. And counter must (basically): (i) remember its place (state), (ii) be able to move next, (iii) and know about the current person he is dealing with.

Enumerable is just a fancy word for "countable". In other words, an enumerable allows you to 'enumerate' (i.e. count).

Has an event handler already been added?

From outside the defining class, as @Telos mentions, you can only use EventHandler on the left-hand side of a += or a -=. So, if you have the ability to modify the defining class, you could provide a method to perform the check by checking if the event handler is null - if so, then no event handler has been added. If not, then maybe and you can loop through the values in Delegate.GetInvocationList. If one is equal to the delegate that you want to add as event handler, then you know it's there.

public bool IsEventHandlerRegistered(Delegate prospectiveHandler)
{   
    if ( this.EventHandler != null )
    {
        foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
        {
            if ( existingHandler == prospectiveHandler )
            {
                return true;
            }
        }
    }
    return false;
}

And this could easily be modified to become "add the handler if it's not there". If you don't have access to the innards of the class that's exposing the event, you may need to explore -= and +=, as suggested by @Lou Franco.

However, you may be better off reexamining the way you're commissioning and decommissioning these objects, to see if you can't find a way to track this information yourself.

JQuery create a form and add elements to it programmatically

Using Jquery

Rather than creating temp variables it can be written in a continuous flow pattern as follows:

$('</form>', { action: url, method: 'POST' }).append(
    $('<input>', {type: 'hidden', id: 'id_field_1', name: 'name_field_1', value: val_field_1}),
    $('<input>', {type: 'hidden', id: 'id_field_2', name: 'name_field_2', value: val_field_2}),
).appendTo('body').submit();

Error: could not find function "%>%"

the following can be used:

 install.packages("data.table")
 library(data.table)

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

jQuery count number of divs with a certain class?

For better performance you should use:

var numItems = $('div.item').length;

Since it will only look for the div elements in DOM and will be quick.

Suggestion: using size() instead of length property means one extra step in the processing since SIZE() uses length property in the function definition and returns the result.

curl_init() function not working

In my case, in Xubuntu, I had to install libcurl3 libcurl3-dev libraries. With this command everything worked:

sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

How to make a div have a fixed size?

Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.

max-width:something px;
max-height:something px;

The other option would be to use the devlopr tools and see if you can remove the natural padding.

padding: 0;

How to efficiently use try...catch blocks in PHP

There is no any problem to write multiple lines of execution withing a single try catch block like below

try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}

The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.

When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:

try{
    install_engine();
    install_break();
    }
    catch(Exception $e){
    show_exception($e->getMessage());
    }
try{
install_body();
paint_body();
install_interiour();
}
catch(Exception $e){
throw new exception('Body Makeover faield')
}

How to add MVC5 to Visual Studio 2013?

Also, while installing Visual Studio 2013, ensure that you have checked "Web Developer Tools"

Create a button with rounded border

So I did mine with the full styling and border colors like this:

new OutlineButton(
    shape: StadiumBorder(),
    textColor: Colors.blue,
    child: Text('Button Text'),
    borderSide: BorderSide(
        color: Colors.blue, style: BorderStyle.solid, 
        width: 1),
    onPressed: () {},
)

How do I call one constructor from another in Java?

Yes, any number of constructors can be present in a class and they can be called by another constructor using this() [Please do not confuse this() constructor call with this keyword]. this() or this(args) should be the first line in the constructor.

Example:

Class Test {
    Test() {
        this(10); // calls the constructor with integer args, Test(int a)
    }
    Test(int a) {
        this(10.5); // call the constructor with double arg, Test(double a)
    }
    Test(double a) {
        System.out.println("I am a double arg constructor");
    }
}

This is known as constructor overloading.
Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.

jQuery equivalent to Prototype array.last()

Why not just use simple javascript?

var array=[1,2,3,4];
var lastEl = array[array.length-1];

You can write it as a method too, if you like (assuming prototype has not been included on your page):

Array.prototype.last = function() {return this[this.length-1];}

Converting JSON String to Dictionary Not List

You can use the following:

import json

 with open('<yourFile>.json', 'r') as JSON:
       json_dict = json.load(JSON)

 # Now you can use it like dictionary
 # For example:

 print(json_dict["username"])

Adding a stylesheet to asp.net (using Visual Studio 2010)

The only thing you have to do is to add in the cshtml file, in the head, the following line:

        @Styles.Render("~/Content/Main.css")

The entire head will look somethink like that:

    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>HTML Page</title>
         @Styles.Render("~/Content/main.css")
    </head>

Hope it helps!!

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

With Hibernate 5.2, you can now force the UTC time zone using the following configuration property:

<property name="hibernate.jdbc.time_zone" value="UTC"/>

POST: sending a post request in a url itself

You can use postman.

Where select Post as method. and In Request Body send JSON Object.

Invalid argument supplied for foreach()

What about defining an empty array as fallback if get_value() is empty?
I can't think of a shortest way.

$values = get_values() ?: [];

foreach ($values as $value){
  ...
}

How to open a new tab in GNOME Terminal from command line?

Consider using Roxterm instead.

roxterm --tab

opens a tab in the current window.

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

Including more than one reference to Jquery library is the reason for the error Only Include one reference to the Jquery library and that will resolve the issue

to_string not declared in scope

//Try this if you can't use -std=c++11:-
int number=55;
char tempStr[32] = {0};
sprintf(tempStr, "%d", number);

Screen width in React Native

React Native Dimensions is only a partial answer to this question, I came here looking for the actual pixel size of the screen, and the Dimensions actually gives you density independent layout size.

You can use React Native Pixel Ratio to get the actual pixel size of the screen.

You need the import statement for both Dimenions and PixelRatio

import { Dimensions, PixelRatio } from 'react-native';

You can use object destructuring to create width and height globals or put it in stylesheets as others suggest, but beware this won't update on device reorientation.

const { width, height } = Dimensions.get('window');

From React Native Dimension Docs:

Note: Although dimensions are available immediately, they may change (e.g due to >device rotation) so any rendering logic or styles that depend on these constants >should try to call this function on every render, rather than caching the value >(for example, using inline styles rather than setting a value in a StyleSheet).

PixelRatio Docs link for those who are curious, but not much more there.

To actually get the screen size use:

PixelRatio.getPixelSizeForLayoutSize(width);

or if you don't want width and height to be globals you can use it anywhere like this

PixelRatio.getPixelSizeForLayoutSize(Dimensions.get('window').width);

Getting number of elements in an iterator in Python

No, any method will require you to resolve every result. You can do

iter_length = len(list(iterable))

but running that on an infinite iterator will of course never return. It also will consume the iterator and it will need to be reset if you want to use the contents.

Telling us what real problem you're trying to solve might help us find you a better way to accomplish your actual goal.

Edit: Using list() will read the whole iterable into memory at once, which may be undesirable. Another way is to do

sum(1 for _ in iterable)

as another person posted. That will avoid keeping it in memory.

How to use if-else logic in Java 8 stream forEach

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.


Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:

    animalMap.forEach(
            (key, value) -> {
                if (value != null) {
                    myMap.put(key, value);
                } else {
                    myList.add(key);
                }
            }
    );

Provide an image for WhatsApp link sharing

enter image description here After looking through lot of answers and yet unable to fix the issue, I finally got it working after lot of iterations. Here is the exact code I used:

In <head> tag:

<meta property="og:title" content="ABC Blabla 2020 Friday" />
<meta property="og:url" content="https://bla123.neocities.org/mp/friday.html" />
<meta property="og:description" content="Photo Album">
<meta property="og:image" itemprop="image" content="https://bla123.neocities.org/mp/images/thumbs/IMG_327.JPG"/>
<meta property="og:type" content="article" />
<meta property="og:locale" content="en_GB" />

In <body> tag:

<link itemprop="thumbnailUrl" href="https://bla123.neocities.org/mp/images/thumbs/IMG_327.JPG">

<span itemprop="thumbnail" itemscope itemtype="http://schema.org/ImageObject">
<link itemprop="url" href="https://bla123.neocities.org/mp/images/thumbs/IMG_327.JPG">
</span>

These 8 tags ( 6 in head , 2 in body) worked perfectly.

Tips:

1.Use the exact image location URL instead of directory format i.e. don't use images/OG_thumb.jpg

2.Case sensitive file extension: If the image extension name on your hosting provider is ".JPG" then do not use ".jpg" or ".jpeg' . I observed that based on hosting provider and browser combination error may or may not occur, so to be safe its easier to just match the case of file extension.

3.After doing above steps if the thumbnail preview is still not showing up in WhatsApp message then:

a. Force stop the mobile app ( I tried in Android) and try again

b.Use online tool to preview the OG tag eg I used : https://searchenginereports.net/open-graph-checker

c. In mobile browser paste direct link to the OG thumb and refresh the browser 4-5 times . eg https://bla123neocities.org/nmp/images/thumbs/IMG_327.JPG

adb command not found in linux environment

I have same problem as you. finally as i know, in linux & mac OS, we use ./adb instead of adb

Windows service on Local Computer started and then stopped error

If the service starts and stops like that, it means your code is throwing an unhandled exception. This is pretty difficult to debug, but there are a few options.

  1. Consult the Windows Event Viewer. Normally you can get to this by going to the computer/server manager, then clicking Event Viewer -> Windows Logs -> Application. You can see what threw the exception here, which may help, but you don't get the stack trace.
  2. Extract your program logic into a library class project. Now create two different versions of the program: a console app (for debugging), and the windows service. (This is a bit of initial effort, but saves a lot of angst in the long run.)
  3. Add more try/catch blocks and logging to the app to get a better picture of what's going on.

How to make a smaller RatingBar?

How to glue the code given here ...

Step-1. You need your own rating stars in res/drawable ...

A full star

Empty star

Step-2 In res/drawable you need ratingstars.xml as follow ...

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
          android:drawable="@drawable/star_empty" />
    <item android:id="@android:id/secondaryProgress"
          android:drawable="@drawable/star_empty" />
    <item android:id="@android:id/progress"
          android:drawable="@drawable/star" />
</layer-list>

Step-3 In res/values you need styles.xml as follow ...

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="foodRatingBar" parent="@android:style/Widget.RatingBar">
        <item name="android:progressDrawable">@drawable/ratingstars</item>
        <item name="android:minHeight">22dip</item>
        <item name="android:maxHeight">22dip</item>
    </style>
</resources>

Step-4 In your layout ...

<RatingBar 
      android:id="@+id/rtbProductRating"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:numStars="5"
      android:rating="3.5"
      android:isIndicator="false"
      style="@style/foodRatingBar"    
/>  

How does the "final" keyword in Java work? (I can still modify an object.)

Above all are correct. Further if you do not want others to create sub classes from your class, then declare your class as final. Then it becomes the leaf level of your class tree hierarchy that no one can extend it further. It is a good practice to avoid huge hierarchy of classes.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

You can pass $state to your controller and then when the page loads and calls the getter in the controller you call $state.go('index') or whatever partial you want to load. Done.

Pipenv: Command Not Found

You might consider installing pipenv via pipsi.

curl https://raw.githubusercontent.com/mitsuhiko/pipsi/master/get -pipsi.py | python3
pipsi install pew
pipsi install pipenv

Unfortunately there are some issues with macOS + python3 at the time of writing, see 1, 2. In my case I had to change the bashprompt to #!/Users/einselbst/.local/venvs/pipsi/bin/python

Can I redirect the stdout in python into some sort of string buffer?

Starting with Python 2.6 you can use anything implementing the TextIOBase API from the io module as a replacement. This solution also enables you to use sys.stdout.buffer.write() in Python 3 to write (already) encoded byte strings to stdout (see stdout in Python 3). Using StringIO wouldn't work then, because neither sys.stdout.encoding nor sys.stdout.buffer would be available.

A solution using TextIOWrapper:

import sys
from io import TextIOWrapper, BytesIO

# setup the environment
old_stdout = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), sys.stdout.encoding)

# do something that writes to stdout or stdout.buffer

# get output
sys.stdout.seek(0)      # jump to the start
out = sys.stdout.read() # read output

# restore stdout
sys.stdout.close()
sys.stdout = old_stdout

This solution works for Python 2 >= 2.6 and Python 3.

Please note that our new sys.stdout.write() only accepts unicode strings and sys.stdout.buffer.write() only accepts byte strings. This might not be the case for old code, but is often the case for code that is built to run on Python 2 and 3 without changes, which again often makes use of sys.stdout.buffer.

You can build a slight variation that accepts unicode and byte strings for write():

class StdoutBuffer(TextIOWrapper):
    def write(self, string):
        try:
            return super(StdoutBuffer, self).write(string)
        except TypeError:
            # redirect encoded byte strings directly to buffer
            return super(StdoutBuffer, self).buffer.write(string)

You don't have to set the encoding of the buffer the sys.stdout.encoding, but this helps when using this method for testing/comparing script output.

How to set selected value from Combobox?

Try this:

KeyValuePair<string, string> pair = (KeyValuePair<string,string>)this.ComboBox.SelectedItem;

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

What it is telling you is - the 2nd guard let or the if let check is not happening on an Optional Int or Optional String. You already have a non-optional value, so guarding or if-letting is not needed anymore

What causes a Python segmentation fault?

Updating the ulimit worked for my Kosaraju's SCC implementation by fixing the segfault on both Python (Python segfault.. who knew!) and C++ implementations.

For my MAC, I found out the possible maximum via :

$ ulimit -s -H
65532

How to get database structure in MySQL via query

using this:

SHOW CREATE TABLE `users`;

will give you the DDL for that table

DESCRIBE `users`

will list the columns in that table

How do I run git log to see changes only for a specific branch?

The problem I was having, which I think is similar to this, is that master was too far ahead of my branch point for the history to be useful. (Navigating to the branch point would take too long.)

After some trial and error, this gave me roughly what I wanted:

git log --graph --decorate --oneline --all ^master^!

How can I convert a DateTime to the number of seconds since 1970?

That's basically it. These are the methods I use to convert to and from Unix epoch time:

public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    return origin.AddSeconds(timestamp);
}

public static double ConvertToUnixTimestamp(DateTime date)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan diff = date.ToUniversalTime() - origin;
    return Math.Floor(diff.TotalSeconds);
}

Update: As of .Net Core 2.1 and .Net Standard 2.1 a DateTime equal to the Unix Epoch can be obtained from the static DateTime.UnixEpoch.

Check whether an input string contains a number in javascript

We can check it by using !/[^a-zA-Z]/.test(e)
Just run snippet and check.

_x000D_
_x000D_
function handleValueChange() {
  if (!/[^a-zA-Z]/.test(document.getElementById('textbox_id').value)) {
      var x = document.getElementById('result');
      x.innerHTML = 'String does not contain number';
  } else {
    var x = document.getElementById('result');
    x.innerHTML = 'String does contains number';
  }
}
_x000D_
input {
  padding: 5px;
}
_x000D_
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
_x000D_
_x000D_
_x000D_

How to import cv2 in python3?

The best way is to create a virtual env. first and then do pip install , everything will work fine

How to convert a negative number to positive?

If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use abs():

>>> abs(-1)
1
>>> abs(1)
1

How to calculate the CPU usage of a process by PID in Linux from C?

You need to parse out the data from /proc/<PID>/stat. These are the first few fields (from Documentation/filesystems/proc.txt in your kernel source):

Table 1-3: Contents of the stat files (as of 2.6.22-rc3)
..............................................................................
 Field          Content
  pid           process id
  tcomm         filename of the executable
  state         state (R is running, S is sleeping, D is sleeping in an
                uninterruptible wait, Z is zombie, T is traced or stopped)
  ppid          process id of the parent process
  pgrp          pgrp of the process
  sid           session id
  tty_nr        tty the process uses
  tty_pgrp      pgrp of the tty
  flags         task flags
  min_flt       number of minor faults
  cmin_flt      number of minor faults with child's
  maj_flt       number of major faults
  cmaj_flt      number of major faults with child's
  utime         user mode jiffies
  stime         kernel mode jiffies
  cutime        user mode jiffies with child's
  cstime        kernel mode jiffies with child's

You're probably after utime and/or stime. You'll also need to read the cpu line from /proc/stat, which looks like:

cpu  192369 7119 480152 122044337 14142 9937 26747 0 0

This tells you the cumulative CPU time that's been used in various categories, in units of jiffies. You need to take the sum of the values on this line to get a time_total measure.

Read both utime and stime for the process you're interested in, and read time_total from /proc/stat. Then sleep for a second or so, and read them all again. You can now calculate the CPU usage of the process over the sampling time, with:

user_util = 100 * (utime_after - utime_before) / (time_total_after - time_total_before);
sys_util = 100 * (stime_after - stime_before) / (time_total_after - time_total_before);

Make sense?

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

if you are using visual studio , enable the build property "Prefer 32-bit". see image below.

enter image description here

Java: How to set Precision for double value?

You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.

You will have to convert into a decimal radix, either via BigDecimal or DecimalFormat, depending on what you want to do with the value later.

See also my answer to this question for a refutation of the inevitable *100/100 answers.

Anaconda version with Python 3.5

command install:

  • python3.5: conda install python=3.5
  • python3.6: conda install python=3.6

download the most recent Anaconda installer:

  • python3.5: Anaconda 4.2.0
  • python3.6: Anaconda 5.2.0

reference from anaconda doc:

Use jQuery to scroll to the bottom of a div with lots of text

jQuery simple solution, one line, no external lib required :

$("#myDivID").animate({ scrollTop: $('#myDivID')[0].scrollHeight }, 1000);

Change 1000 to another value (this is the duration of the animation).

Editing specific line in text file in Python

I have been practising working on files this evening and realised that I can build on Jochen's answer to provide greater functionality for repeated/multiple use. Unfortunately my answer does not address issue of dealing with large files but does make life easier in smaller files.

with open('filetochange.txt', 'r+') as foo:
    data = foo.readlines()                  #reads file as list
    pos = int(input("Which position in list to edit? "))-1  #list position to edit
    data.insert(pos, "more foo"+"\n")           #inserts before item to edit
    x = data[pos+1]
    data.remove(x)                      #removes item to edit
    foo.seek(0)                     #seeks beginning of file
    for i in data:
        i.strip()                   #strips "\n" from list items
        foo.write(str(i))

How to convert "0" and "1" to false and true

How about:

return (returnValue == "1");

or as suggested below:

return (returnValue != "0");

The correct one will depend on what you are looking for as a success result.

Subscripts in plots in R

As other users have pointed out, we use expression(). I'd like to answer the original question which involves a comma in the subscript:

How can I write v 1,2 with 1,2 as subscripts?

plot(1:10, 11:20 , main=expression(v["1,2"]))

Also, I'd like to add the reference for those looking to find the full expression syntax in R plotting: For more information see the ?plotmath help page. Running demo(plotmath) will showcase many expressions and relevant syntax.

Remember to use * to join different types of text within an expression.

Here is some of the sample output from demo(plotmath):

enter image description here

Android Studio error: "Environment variable does not point to a valid JVM installation"

All you need to do is, set the JAVA_HOME and JDK_HOME environment variables by following the steps:

1)Right click on

My Computer.->>Properties->>Advanced System Settings.->>Environment Variables

.

2)In user variables for (Your PC name),click on new at botton of the tab.

3)In variable name,type JAVA_HOME

4)In variable value,type

C:\Program Files\Java\jdk1.8.0_25

(path where your jdk folder is located on the system ).

5)Do it again with JDK_HOME

with same path.

Docker is installed but Docker Compose is not ? why?

docker-compose is currently a tool that utilizes docker(-engine) but is not included in the distribution of docker.

Here is the link to the installation manual: https://docs.docker.com/compose/install/

TL;DR:

curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
chmod +x /usr/bin/docker-compose

(1.8.0 will change in the future)

Get first and last day of month using threeten, LocalDate

 LocalDate monthstart = LocalDate.of(year,month,1);
 LocalDate monthend = monthstart.plusDays(monthstart.lengthOfMonth()-1);

How to install wkhtmltopdf on a linux based (shared hosting) web server

Version 12.5 of wkhtmltopdf only lists DEB files on their download page now. Being a mac user and not knowing much linux or what DEB files were I couldn't use the solutions posted.

This page helped me get past the knew twist of downloading a DEB file: http://www.g-loaded.eu/2008/01/28/how-to-extract-rpm-or-deb-packages/

Basically what I did was:

  1. Downloaded from https://wkhtmltopdf.org/downloads.html
  2. Unzipped the DEB file.
  3. Unzipped data.tar.xz
  4. Uploaded the binary in the unzipped 'usr' folder from step 3 (usr/local/bin/wkhtmltopdf)

Then I found out that the 'exec' function was disabled on my host. So make sure you can specifically run 'exec' if you're using PHP to run this. "Can I run the wkhtmltopdf binary" isn't specific enough. My fault.

Android Imagebutton change Image OnClick

<ImageButton android:src="@drawable/image_btn_src" ... />

image_btn_src.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/icon_pressed"/>
<item android:state_pressed="false" android:drawable="@drawable/icon_unpressed"/>
</selector>

How to copy file from host to container using Dockerfile

If you want to copy the current dir's contents, you can run:

docker build  -t <imagename:tag> -f- ./ < Dockerfile

how to update spyder on anaconda

In iOS,

  • Open Anaconda Navigator
  • Launch Spyder
  • Click on the tab "Consoles" (menu bar)
  • Then, "New Console"
  • Finally, in the console window, type conda update spyder

Your computer is going to start downloading and installing the new version. After finishing, just restart Spyder and that's it.

Error: Cannot access file bin/Debug/... because it is being used by another process

Make sure that any previous run of the application (for example, start without debugging option) is actually stopped. I was working on a WPF application, started without debugging and had it minimized when I kept getting the error. After closing the application VS behavior got back to normal.

How to fill 100% of remaining height?

_x000D_
_x000D_
    html,_x000D_
    body {_x000D_
        height: 100%;_x000D_
    }_x000D_
_x000D_
    .parent {_x000D_
        display: flex;_x000D_
        flex-flow:column;_x000D_
        height: 100%;_x000D_
        background: white;_x000D_
    }_x000D_
_x000D_
    .child-top {_x000D_
        flex: 0 1 auto;_x000D_
        background: pink;_x000D_
    }_x000D_
_x000D_
    .child-bottom {_x000D_
        flex: 1 1 auto;_x000D_
        background: green;_x000D_
    }
_x000D_
    <div class="parent">_x000D_
        <div class="child-top">_x000D_
          This child has just a bit of content_x000D_
        </div>_x000D_
        <div class="child-bottom">_x000D_
          And this one fills the rest_x000D_
        </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Best way to run scheduled tasks

You can easily create a Windows Service that runs code on interval using the 'ThreadPool.RegisterWaitForSingleObject' method. It is really slick and quite easy to get set up. This method is a more streamlined approach then to use any of the Timers in the Framework.

Have a look at the link below for more information:

Running a Periodic Process in .NET using a Windows Service:
http://allen-conway-dotnet.blogspot.com/2009/12/running-periodic-process-in-net-using.html

go to character in vim

vim +21490go script.py

From the command line will open the file and take you to position 21490 in the buffer.

Triggering it from the command line like this allows you to automate a script to parse the exception message and open the file to the problem position.


Excerpt from man vim:

+{command}

-c {command}

{command} will be executed after the first file has been read. {command} is interpreted as an Ex command. If the {command} contains spaces it must be enclosed in double quotes (this depends on the shell that is used).

Python: For each list element apply a function across the list

You can do this using list comprehensions and min() (Python 3.0 code):

>>> nums = [1,2,3,4,5]
>>> [(x,y) for x in nums for y in nums]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
>>> min(_, key=lambda pair: pair[0]/pair[1])
(1, 5)

Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do from __future__ import division so that 1/5 correctly equals 0.2 instead of 0.

How do I diff the same file between two different commits on the same branch?

Here is a Perl script that prints out Git diff commands for a given file as found in a Git log command.

E.g.

git log pom.xml | perl gldiff.pl 3 pom.xml

Yields:

git diff 5cc287:pom.xml e8e420:pom.xml
git diff 3aa914:pom.xml 7476e1:pom.xml
git diff 422bfd:pom.xml f92ad8:pom.xml

which could then be cut and pasted in a shell window session or piped to /bin/sh.

Notes:

  1. the number (3 in this case) specifies how many lines to print
  2. the file (pom.xml in this case) must agree in both places (you could wrap it in a shell function to provide the same file in both places) or put it in a binary directory as a shell script

Code:

# gldiff.pl
use strict;

my $max  = shift;
my $file = shift;

die "not a number" unless $max =~ m/\d+/;
die "not a file"   unless -f $file;

my $count;
my @lines;

while (<>) {
    chomp;
    next unless s/^commit\s+(.*)//;
    my $commit = $1;
    push @lines, sprintf "%s:%s", substr($commit,0,6),$file;
    if (@lines == 2) {
        printf "git diff %s %s\n", @lines;
        @lines = ();
    }
    last if ++$count >= $max *2;
}

WCF service startup error "This collection already contains an address with scheme http"

In my case root cause of this issue was multiple http bindings defined at parent web site i.e. InetMgr->Sites->Mysite->properties->EditBindings. I deleted one http binding which was not required and problem got resolved.

Path.Combine for URLs?

Rules while combining URLs with a URI

To avoid strange behaviour there's one rule to follow:

  • The path (directory) must end with '/'. If the path ends without '/', the last part is treated like a file-name, and it'll be concatenated when trying to combine with the next URL part.
  • There's one exception: the base URL address (without directory info) needs not to end with '/'
  • the path part must not start with '/'. If it start with '/', every existing relative information from URL is dropped...adding a string.Empty part path will remove the relative directory from the URL too!

If you follow rules above, you can combine URLs with the code below. Depending on your situation, you can add multiple 'directory' parts to the URL...

        var pathParts = new string[] { destinationBaseUrl, destinationFolderUrl, fileName };

        var destination = pathParts.Aggregate((left, right) =>
        {
            if (string.IsNullOrWhiteSpace(right))
                return left;

            return new Uri(new Uri(left), right).ToString();
        });

How to edit a text file in my terminal

Open the file again using vi. and then press the insert button to begin editing it.

Get index of clicked element in collection with jQuery

Just do this way:-

$('ul li').on('click', function(e) {
    alert($(this).index()); 
});

OR

$('ul li').click(function() {
    alert($(this).index());
});

Create a string of variable length, filled with a repeated character

A great ES6 option would be to padStart an empty string. Like this:

var str = ''.padStart(10, "#");

Note: this won't work in IE (without a polyfill).

How to replace innerHTML of a div using jQuery?

you can use either html or text function in jquery to achieve it

$("#regTitle").html("hello world");

OR

$("#regTitle").text("hello world");

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

HTTP authentication logout via PHP

AFAIK, there's no clean way to implement a "logout" function when using htaccess (i.e. HTTP-based) authentication.

This is because such authentication uses the HTTP error code '401' to tell the browser that credentials are required, at which point the browser prompts the user for the details. From then on, until the browser is closed, it will always send the credentials without further prompting.

How open PowerShell as administrator from the run window

The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":

[Windows 10/Windows 8 Power User menu with "Windows Powershell (Admin)

Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:

[Taskbar and Start Menu Properties: "Replace Command Prompt With Windows Powershell"

Create a circular button in BS3

This is the best reference using font-awesome.

http://bootsnipp.com/snippets/featured/circle-button?

CSS:

    .btn-circle { width: 30px; height: 30px; text-align: center;padding: 6px 0;font-size: 12px;line-height: 1.428571429;border-radius: 15px;}.btn-circle.btn-lg {width: 50px;height: 50px;padding: 10px 16px;font-size: 18px;line-height:1.33;border-radius: 25px;} 

How do you check current view controller class in Swift?

Swift 3

Not sure about you guys, but I'm having a hard time with this one. I did something like this:

if let window = UIApplication.shared.delegate?.window {
    if var viewController = window?.rootViewController {
        // handle navigation controllers
        if(viewController is UINavigationController){
            viewController = (viewController as! UINavigationController).visibleViewController!
        }
        print(viewController)
    }
}

I kept getting the initial view controller of my app. For some reason it wanted to stay the root view controller no matter what. So I just made a global string type variable currentViewController and set its value myself in each viewDidLoad(). All I needed was to tell which screen I was on & this works perfectly for me.

Execution time of C program

I've found that the usual clock(), everyone recommends here, for some reason deviates wildly from run to run, even for static code without any side effects, like drawing to screen or reading files. It could be because CPU changes power consumption modes, OS giving different priorities, etc...

So the only way to reliably get the same result every time with clock() is to run the measured code in a loop multiple times (for several minutes), taking precautions to prevent the compiler from optimizing it out: modern compilers can precompute the code without side effects running in a loop, and move it out of the loop., like i.e. using random input for each iteration.

After enough samples are collected into an array, one sorts that array, and takes the middle element, called median. Median is better than average, because it throws away extreme deviations, like say antivirus taking up all CPU up or OS doing some update.

Here is a simple utility to measure execution performance of C/C++ code, averaging the values near median: https://github.com/saniv/gauge

I'm myself still looking for a more robust and faster way to measure code. One could probably try running the code in controlled conditions on bare metal without any OS, but that will give unrealistic result, because in reality OS does get involved.

x86 has these hardware performance counters, which including the actual number of instructions executed, but they are tricky to access without OS help, hard to interpret and have their own issues ( http://archive.gamedev.net/archive/reference/articles/article213.html ). Still they could be helpful investigating the nature of the bottle neck (data access or actual computations on that data).

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

Python 2.7.10 error "from urllib.request import urlopen" no module named request

Change

from urllib.request import urlopen

to

from urllib import urlopen

I was able to solve this problem by changing like this. For Python2.7 in macOS10.14

Use Robocopy to copy only changed files?

To answer all your questions:

Can I use ROBOCOPY for this?

Yes, RC should fit your requirements (simplicity, only copy what needed)


What exactly does it mean to exclude?

It will exclude copying - RC calls it skipping


Would the /XO option copy only newer files, not files of the same age?

Yes, RC will only copy newer files. Files of the same age will be skipped.

(the correct command would be robocopy C:\SourceFolder D:\DestinationFolder ABC.dll /XO)


Maybe in your case using the /MIR option could be useful. In general RC is rather targeted at directories and directory trees than single files.

Display Back Arrow on Toolbar

This worked perfectly

public class BackButton extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_box);
        Toolbar chatbox_toolbar=(Toolbar)findViewById(R.id.chat_box_toolbar);
        chatbox_toolbar.setTitle("Demo Back Button");
        chatbox_toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        setSupportActionBar(chatbox_toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        chatbox_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Define Back Button Function
            }
        });
    }
}

Capitalize first letter. MySQL

This should work nicely:

UPDATE tb_Company SET CompanyIndustry = 
CONCAT(UPPER(LEFT(CompanyIndustry, 1)), SUBSTRING(CompanyIndustry, 2))

Use a normal link to submit a form

Definitely, there is no solution with pure HTML to submit a form with a link (a) tag. The standard HTML accepts only buttons or images. As some other collaborators have said, one can simulate the appearance of a link using a button, but I guess that's not the purpose of the question.

IMHO, I believe that the proposed and accepted solution does not work.

I have tested it on a form and the browser didn't find the reference to the form.

So it is possible to solve it using a single line of JavaScript, using this object, which references the element being clicked, which is a child node of the form, that needs to be submitted. So this.parentNode is the form node. After it's just calling submit() method in that form. It's no necessary research from whole document to find the right form.

<form action="http://www.greatsolutions.com.br/indexint.htm"                   
   method="get">
    <h3> Enter your name</h3>
    First Name <input type="text"  name="fname"  size="30"><br>
    Last Name <input type="text" name="lname" size="30"><br>
    <a href="#" onclick="this.parentNode.submit();"> Submit here</a>
</form>

Suppose that I enter with my own name:

Filled form

I've used get in form method attribute because it's possible to see the right parameters in the URL at loaded page after submit.

http://www.greatsolutions.com.br/indexint.htm?fname=Paulo&lname=Buchsbaum

This solution obviously applies to any tag that accepts the onclick event or some similar event.

this is a excellent choice to recover the context together with event variable (available in all major browsers and IE9 onwards) that can be used directly or passed as an argument to a function.

In this case, replace the line with a tag by the line below, using the property target, that indicates the element that has started the event.

<a href="#" onclick="event.target.parentNode.submit();"> Submit here</a>

force client disconnect from server with socket.io and nodejs

This didn't work for me:

`socket.disconnect()` 

This did work for me:

socket.disconnect(true)

Handing over true will close the underlaying connection to the client and not just the namespace the client is connected to Socket IO Documentation.


An example use case: Client did connect to web socket server with invalid access token (access token handed over to web socket server with connection params). Web socket server notifies the client that it is going to close the connection, because of his invalid access token:

// (1) the server code emits
socket.emit('invalidAccessToken', function(data) {
    console.log(data);       // (4) server receives 'invalidAccessTokenEmitReceived' from client
    socket.disconnect(true); // (5) force disconnect client 
});

// (2) the client code listens to event
// client.on('invalidAccessToken', (name, fn) => { 
//     // (3) the client ack emits to server
//     fn('invalidAccessTokenEmitReceived');
// });

How to convert Json array to list of objects in c#

Did you check this line works perfectly & your string have value in it ?

string jsonString = sr.ReadToEnd();

if yes, try this code for last line:

ValueSet items = JsonConvert.DeserializeObject<ValueSet>(jsonString);

or if you have an array of json you can use list like this :

List<ValueSet> items = JsonConvert.DeserializeObject<List<ValueSet>>(jsonString);

good luck

Flexbox not working in Internet Explorer 11

According to Flexbugs:

In IE 10-11, min-height declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.

Here are a couple of workarounds:

1. Always fill the viewport + scrollable <aside> and <section>:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1;
  display: flex;
}

aside, section {
  overflow: auto;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

2. Fill the viewport initially + normal page scroll with more content:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1 0 auto;
  display: flex;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

regex with space and letters only?

use this expression

var RegExpression = /^[a-zA-Z\s]*$/;  

for more refer this http://tools.netshiftmedia.com

How can I turn a DataTable to a CSV?

A new extension function based on Paul Grimshaw's answer. I cleaned it up and added the ability to handle unexpected data. (Empty Data, Embedded Quotes, and comma's in the headings...)

It also returns a string which is more flexible. It returns Null if the table object does not contain any structure.

    public static string ToCsv(this DataTable dataTable) {
        StringBuilder sbData = new StringBuilder();

        // Only return Null if there is no structure.
        if (dataTable.Columns.Count == 0)
            return null;

        foreach (var col in dataTable.Columns) {
            if (col == null)
                sbData.Append(",");
            else
                sbData.Append("\"" + col.ToString().Replace("\"", "\"\"") + "\",");
        }

        sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);

        foreach (DataRow dr in dataTable.Rows) {
            foreach (var column in dr.ItemArray) {
                if (column == null)
                    sbData.Append(",");
                else
                    sbData.Append("\"" + column.ToString().Replace("\"", "\"\"") + "\",");
            }
            sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);
        }

        return sbData.ToString();
    }

You call it as follows:

var csvData = dataTableOject.ToCsv();

Delete topic in Kafka 0.8.1.1

bin/kafka-topics.sh –delete –zookeeper localhost:2181 –topic <topic-name>

SQL Server query to find all current database names

SELECT datname FROM pg_database WHERE datistemplate = false

#for postgres

Java: Replace all ' in a string with \'

Let's take a tour of String#repalceAll(String regex, String replacement)

You will see that:

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceAll(repl)

So lets take a look at Matcher.html#replaceAll(java.lang.String) documentation

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

You can see that in replacement we have special character $ which can be used as reference to captured group like

System.out.println("aHellob,aWorldb".replaceAll("a(\\w+?)b", "$1"));
// result Hello,World

But sometimes we don't want $ to be such special because we want to use it as simple dollar character, so we need a way to escape it.
And here comes \, because since it is used to escape metacharacters in regex, Strings and probably in other places it is good convention to use it here to escape $.

So now \ is also metacharacter in replacing part, so if you want to make it simple \ literal in replacement you need to escape it somehow. And guess what? You escape it the same way as you escape it in regex or String. You just need to place another \ before one you escaping.

So if you want to create \ in replacement part you need to add another \ before it. But remember that to write \ literal in String you need to write it as "\\" so to create two \\ in replacement you need to write it as "\\\\".


So try

s = s.replaceAll("'", "\\\\'");

Or even better

to reduce explicit escaping in replacement part (and also in regex part - forgot to mentioned that earlier) just use replace instead replaceAll which adds regex escaping for us

s = s.replace("'", "\\'");

How to output (to a log) a multi-level array in a format that is human-readable?

http://php.net/manual/en/function.print-r.php This function can be used to format output,

$output = print_r($array,1);

$output is a string variable, it can be logged like every other string. In pure php you can use trigger_error

Ex. trigger_error($output);

http://php.net/manual/en/function.trigger-error.php

if you need to format it also in html, you can use <pre> tag

wamp server does not start: Windows 7, 64Bit

Follow these steps (taken from this Youtube video).

  1. Quit Skype
  2. Uninstall IIS
    • Go to control panel
    • Refer to PROGRAMS AND FEATURES
    • Go to TURN WINDOWS FEATURES ON OR OFF
    • Look for INTERNET information service
    • Uninstall

List of all special characters that need to be escaped in a regex

According to the String Literals / Metacharacters documentation page, they are:

<([{\^-=$!|]})?*+.>

Also it would be cool to have that list refereed somewhere in code, but I don't know where that could be...

How to securely save username/password (local)?

I have used this before and I think in order to make sure credential persist and in a best secure way is

  1. you can write them to the app config file using the ConfigurationManager class
  2. securing the password using the SecureString class
  3. then encrypting it using tools in the Cryptography namespace.

This link will be of great help I hope : Click here

How to get active user's UserDetails

Implement the HandlerInterceptor interface, and then inject the UserDetails into each request that has a Model, as follows:

@Component 
public class UserInterceptor implements HandlerInterceptor {
    ....other methods not shown....
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(modelAndView != null){
            modelAndView.addObject("user", (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        }
}

How to replace comma (,) with a dot (.) using java

if(str.indexOf(",")!=-1) { str = str.replaceAll(",","."); }

or even better

str = str.replace(',', '.');

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

Installing cmake with home-brew

  1. Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)

  2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

  3. Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"

  4. Reload your .bashrc file: source ~/.bashrc

  5. Verify the latest cmake version is installed: cmake --version

  6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

Java random number with given length

If you need to specify the exact charactor length, we have to avoid values with 0 in-front.

Final String representation must have that exact character length.

String GenerateRandomNumber(int charLength) {
        return String.valueOf(charLength < 1 ? 0 : new Random()
                .nextInt((9 * (int) Math.pow(10, charLength - 1)) - 1)
                + (int) Math.pow(10, charLength - 1));
    }

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

Real escape string and PDO

PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.

Here is an excerpt from the PHP website:

<?php
    $conn = new PDO('sqlite:/home/lynn/music.sql3');

    /* Simple string */
    $string = 'Nice';
    print "Unquoted string: $string\n";
    print "Quoted string: " . $conn->quote($string) . "\n";
?>

The above code will output:

Unquoted string: Nice
Quoted string: 'Nice'

map vs. hash_map in C++

They are implemented in very different ways.

hash_map (unordered_map in TR1 and Boost; use those instead) use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.

map is implemented as a balanced binary search tree (usually a red/black tree).

An unordered_map should give slightly better performance for accessing known elements of the collection, but a map will have additional useful characteristics (e.g. it is stored in sorted order, which allows traversal from start to finish). unordered_map will be faster on insert and delete than a map.

Python loop counter in a for loop

enumerate is what you are looking for.

You might also be interested in unpacking:

# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

Also, there is itertools.count() so you could do something like

import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990

Rename Excel Sheet with VBA Macro

This should do it:

WS.Name = WS.Name & "_v1"

Access 2010 VBA query a table and iterate through results

I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:

Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Dim SQL As String
SQL = _
    "SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
    "c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
    "FROM tblClient AS c " & _
    "WHERE c.ClientID = @ClientID"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
    Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
    .Parameters.Append prm
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
        Do Until .EOF
            mstrLastName = Nz(!LastName, "")
            mstrFirstName = Nz(!FirstName, "")
            mstrMI = Nz(!MI, "")
            mdDOB = !DOB
            mstrSSN = Nz(!SSN, "")
            mlngRaceID = Nz(!RaceID, -1)
            mlngEthnicityID = Nz(!EthnicityID, -1)
            mlngGenderID = Nz(!GenderID, -1)
            mbooDeleted = Deleted
            mdRecordDate = Nz(!RecordDate, "")

            .MoveNext
        Loop
    End If
    .Close
End With

cn.Close

Set rs = Nothing
Set cn = Nothing

ActionBarActivity cannot resolve a symbol

Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.

How to pass variables from one php page to another without form?

check to make sure the variable is set. Then clean it before using it:

isset($_GET['var'])?$var=mysql_escape_string($_GET['var']):$var='SomeDefaualtValue';

Otherwise, assign it a default value ($var='' is fine) to avoid the error you mentioned.

Run php script as daemon process

I run a large number of PHP daemons.

I agree with you that PHP is not the best (or even a good) language for doing this, but the daemons share code with the web-facing components so overall it is a good solution for us.

We use daemontools for this. It is smart, clean and reliable. In fact we use it for running all of our daemons.

You can check this out at http://cr.yp.to/daemontools.html.

EDIT: A quick list of features.

  • Automatically starts the daemon on reboot
  • Automatically restart dameon on failure
  • Logging is handled for you, including rollover and pruning
  • Management interface: 'svc' and 'svstat'
  • UNIX friendly (not a plus for everyone perhaps)

Replace words in a string - Ruby

sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

How to replace all instances?

The above replaces only the first instance of "Robert".

To replace all instances use gsub/gsub! (ie. "global substitution"):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.

Extending the User model with custom fields in Django

Simple and effective approach is models.py

from django.contrib.auth.models import User
class CustomUser(User):
     profile_pic = models.ImageField(upload_to='...')
     other_field = models.CharField()

How do I get the list of keys in a Dictionary?

Or like this:

List< KeyValuePair< string, int > > theList =
    new List< KeyValuePair< string,int > >(this.yourDictionary);

for ( int i = 0; i < theList.Count; i++)
{ 
  // the key
  Console.WriteLine(theList[i].Key);
}

How to style a disabled checkbox?

This is supported by IE too:

HTML

class="disabled"

CSS

.disabled{
...
}

Cloud Firestore collection count

firebaseFirestore.collection("...").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

            int Counter = documentSnapshots.size();

        }
    });

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

JPA CascadeType.ALL does not delete orphans

According to Java Persistence with Hibernate, cascade orphan delete is not available as a JPA annotation.

It is also not supported in JPA XML.

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

How to fix on Laravel 7:

Download the latest cacert.pem file from cURL website.

wget https://curl.haxx.se/ca/cacert.pem

Edit php.ini (you can do php --ini to find it), update (or create if they don't exist already) those two lines:

curl.cainfo="/path/to/downloaded/cacert.pem"
...
openssl.cafile="/path/to/downloaded/cacert.pem"

Those lines should already exist but commented out, so uncomment them and edit both values with the path to the downloaded cacert.pem

Restart PHP and Nginx/Apache.

Edit: You may need to chown/chmod the downloaded certificate file so PHP (and its user) can read it.

source

How do I write a batch script that copies one directory to another, replaces old files?

Have you considered using the "xcopy" command?

The xcopy command will do all that for you.

Countdown timer using Moment js

The following also requires the moment-duration-format plugin:

$.fn.countdown = function ( options ) {
    var $target = $(this);
    var defaults = {
        seconds: 0,
        format: 'hh:mm:ss',
        stopAtZero: true
    };
    var settings = $.extend(defaults, options);
    var eventTime = Date.now() + ( settings.seconds * 1000 );
    var diffTime = eventTime - Date.now();
    var duration = moment.duration( diffTime, 'milliseconds' );
    var interval = 0;
    $target.text( duration.format( settings.format, { trim: false }) );
    var counter = setInterval(function () {
        $target.text( moment.duration( duration.asSeconds() - ++interval, 'seconds' ).format( settings.format, { trim: false }) );
        if( settings.stopAtZero && interval >= settings.seconds ) clearInterval( counter );
    }, 1000);
};

Usage example:

$('#someDiv').countdown({
    seconds: 30*60,
    format: 'mm:ss'
});

Testing Spring's @RequestBody using Spring MockMVC

I have encountered a similar problem with a more recent version of Spring. I tried to use a new ObjectMapper().writeValueAsString(...) but it would not work in my case.

I actually had a String in a JSON format, but I feel like it is literally transforming the toString() method of every field into JSON. In my case, a date LocalDate field would end up as:

"date":{"year":2021,"month":"JANUARY","monthValue":1,"dayOfMonth":1,"chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfWeek":"FRIDAY","leapYear":false,"dayOfYear":1,"era":"CE"}

which is not the best date format to send in a request ...

In the end, the simplest solution in my case is to use the Spring ObjectMapper. Its behaviour is better since it uses Jackson to build your JSON with complex types.

@Autowired
private ObjectMapper objectMapper;

and I simply used it in mytest:

mockMvc.perform(post("/api/")
                .content(objectMapper.writeValueAsString(...))
                .contentType(MediaType.APPLICATION_JSON)
);

What’s the best way to load a JSONObject from a json text file?

try this:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils; 

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );
        }
    }

and this is your sample-json.txt , should be in json format

{
 'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':
     {
         'firstName':'Buzz',
         'lastName':'Aldrin'
     },
 'mission':'apollo 11'
}

Convert a positive number to negative in C#

Just for fun:

int negativeInt = int.Parse(String.Format("{0}{1}", 
    "-", positiveInt.ToString()));

Update: the beauty of this approach is that you can easily refactor it into an exception generator:

int negativeInt = int.Parse(String.Format("{0}{1}", 
    "thisisthedumbestquestioninstackoverflowhistory", positiveInt.ToString()));

undefined reference to WinMain@16 (codeblocks)

Well I know this answer is not an experienced programmer's approach and of an Old It consultant , but it worked for me .

the answer is "TRY TURNING IT ON AND OFF" . restart codeblocks and it works well reminds me of the 2006 comedy show It Crowd .

Access Enum value using EL with JSTL

<%@ page import="com.example.Status" %>

1. ${dp.status eq Title.VALID.getStatus()}
2. ${dp.status eq Title.VALID}
3. ${dp.status eq Title.VALID.toString()}
  • Put the import at the top, in JSP page header
  • If you want to work with getStatus method, use #1
  • If you want to work with the enum element itself, use either #2 or #3
  • You can use == instead of eq

How can I enable Assembly binding logging?

When I had the same problem I fixed it by deleting the existing key.snk in that project and adding a new key.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

I love jQuery's method chaining. Simply do...

    var value = $("#text").val().replace('.',':');

    //Or if you want to return the value:
    return $("#text").val().replace('.',':');

remove space between paragraph and unordered list

You can use CSS selectors in a way similar to the following:

p + ul {
    margin-top: -10px;
}

This could be helpful because p + ul means select any <ul> element after a <p> element.

You'll have to adapt this to how much padding or margin you have on your <p> tags generally.

Original answer to original question:

p, ul {
    padding: 0;
    margin: 0;
}

That will take any EXTRA white space away.

p, ul {
    display: inline;
}

That will make all the elements inline instead of blocks. (So, for instance, the <p> won't cause a line break before and after it.)

Online code beautifier and formatter

It depends of the language, and of the architecture you are using.

alt text alt text

For example, in a php platform, you can format almost language with GeSHi

As bluish comments, GeSHi is a generic syntax highlighter, with no beautification feature. It is more used on the server side, and combine it with a beautification tool can be tricky, as illustrated with this GeSHi drupal ticket.

How to run Spyder in virtual environment?

I follow one of the advice above and indeed it works. In summary while you download Anaconda on Ubuntu using the advice given above can help you to 'create' environments. The default when you download Spyder in my case is: (base) smith@ubuntu ~$. After you create the environment, i.e. fenics and activate it with $ conda activate fenics the prompt change to (fenics) smith@ubuntu ~$. Then you launch Spyder from this prompt, i.e $ spyder and your system open the Spyder IDE, and you can write fenics code on it. Remember every time you open a terminal your system open the default prompt. You have to activate your environment where your package is and the prompt change to it i.e. (fenics).

how to end ng serve or firebase serve

----Ctrl + c then choose Y from the Y/N option provided.

Why does JSHint throw a warning if I am using const?

May 2020 Here's a simple solution i found and it will resolve for all of my projects ,on windows if your project is somewhere inside c: directory , create new file .jshintrc and save it in C directory open this .jshintrc file and write { "esversion": 6} and that's it. the warnings should go away , same will work in d directory

enter image description here

enter image description here yes you can also enable this setting for the specific project only by same creating a .jshintrc file in your project's root and adding { "esversion": 6}

Remove title in Toolbar in appcompat-v7

getSupportActionBar().setDisplayShowTitleEnabled(false);

LINQ Group By and select collection

I think you want:

items.GroupBy(item => item.Order.Customer)
     .Select(group => new { Customer = group.Key, Items = group.ToList() })
     .ToList() 

If you want to continue use the overload of GroupBy you are currently using, you can do:

items.GroupBy(item => item.Order.Customer, 
              (key, group) =>  new { Customer = key, Items = group.ToList() })
     .ToList() 

...but I personally find that less clear.

How to make HTML open a hyperlink in another window or tab?

Simplest way is to add a target tag.

<a href="http://www.starfall.com/" target="Starfall">Starfall</a>

Use a different value for the target attribute for each link if you want them to open in different tabs, the same value for the target attribute if you want them to replace the other ones.

Turning a Comma Separated string into individual rows

DECLARE @id_list VARCHAR(MAX) = '1234,23,56,576,1231,567,122,87876,57553,1216'
DECLARE @table TABLE ( id VARCHAR(50) )
DECLARE @x INT = 0
DECLARE @firstcomma INT = 0
DECLARE @nextcomma INT = 0

SET @x = LEN(@id_list) - LEN(REPLACE(@id_list, ',', '')) + 1 -- number of ids in id_list

WHILE @x > 0
    BEGIN
        SET @nextcomma = CASE WHEN CHARINDEX(',', @id_list, @firstcomma + 1) = 0
                              THEN LEN(@id_list) + 1
                              ELSE CHARINDEX(',', @id_list, @firstcomma + 1)
                         END
        INSERT  INTO @table
        VALUES  ( SUBSTRING(@id_list, @firstcomma + 1, (@nextcomma - @firstcomma) - 1) )
        SET @firstcomma = CHARINDEX(',', @id_list, @firstcomma + 1)
        SET @x = @x - 1
    END

SELECT  *
FROM    @table

casting int to char using C++ style casting

You can implicitly convert between numerical types, even when that loses precision:

char c = i;

However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast for the conversion.

Of the other casts:

  • dynamic_cast only works for pointers or references to polymorphic class types;
  • const_cast can't change types, only const or volatile qualifiers;
  • reinterpret_cast is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.
  • C-style and function-style casts do whatever combination of static_cast, const_cast and reinterpret_cast is needed to get the job done.

Good ways to sort a queryset? - Django

I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):

>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:

>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
... 
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)

And now the combined order_by call:

>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

As you can see it is the same result as the first one, meaning it doesn't work as you would expect.

Remove duplicates from an array of objects in JavaScript

Shortest one liners for ES6+

Find unique id's in an array.

arr.filter((v,i,a)=>a.findIndex(t=>(t.id === v.id))===i)

Unique by multiple properties ( place and name )

arr.filter((v,i,a)=>a.findIndex(t=>(t.place === v.place && t.name===v.name))===i)

Unique by all properties (This will be slow for large arrays)

arr.filter((v,i,a)=>a.findIndex(t=>(JSON.stringify(t) === JSON.stringify(v)))===i)

Keep the last occurrence.

arr.slice().reverse().filter((v,i,a)=>a.findIndex(t=>(t.id === v.id))===i).reverse()

Edit seaborn legend

If you just want to change the legend title, you can do the following:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=True
)

g._legend.set_title("New Title")

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

top -c command in linux to filter processes listed based on processname

Using pgrep to get pid's of matching command lines:

top -c -p $(pgrep -d',' -f string_to_match_in_cmd_line)

top -p expects a comma separated list of pids so we use -d',' in pgrep. The -f flag in pgrep makes it match the command line instead of program name.

pip install access denied on Windows

Running cmd as administrator solved for me. You can also try --user. If you do not want to repeat the steps you need to give full access to anaconda folder.

Convert a String to a byte array and then back to the original String

You can do it like this.

String to byte array

String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
byte[] theByteArray = stringToConvert.getBytes();

http://www.javadb.com/convert-string-to-byte-array

Byte array to String

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);

http://www.javadb.com/convert-byte-array-to-string

How to calculate number of days between two dates

This works for me:

_x000D_
_x000D_
const from = '2019-01-01';_x000D_
const to   = '2019-01-08';_x000D_
_x000D_
Math.abs(_x000D_
    moment(from, 'YYYY-MM-DD')_x000D_
      .startOf('day')_x000D_
      .diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
  ) + 1_x000D_
);
_x000D_
_x000D_
_x000D_

How to clear https proxy setting of NPM?

This works

npm config delete http-proxy
npm config delete https-proxy

npm config rm proxy
npm config rm https-proxy

set HTTP_PROXY=null
set HTTPS_PROXY=null

Transpose a range in VBA

You do not need to do this. Here is how to create a co-variance method:

http://www.youtube.com/watch?v=RqAfC4JXd4A

Alternatively you can use statistical analysis package that Excel has.

How to overlay one div over another div

I am not much of a coder nor an expert in CSS, but I am still using your idea in my web designs. I have tried different resolutions too:

_x000D_
_x000D_
#wrapper {_x000D_
  margin: 0 auto;_x000D_
  width: 901px;_x000D_
  height: 100%;_x000D_
  background-color: #f7f7f7;_x000D_
  background-image: url(images/wrapperback.gif);_x000D_
  color: #000;_x000D_
}_x000D_
#header {_x000D_
  float: left;_x000D_
  width: 100.00%;_x000D_
  height: 122px;_x000D_
  background-color: #00314e;_x000D_
  background-image: url(images/header.jpg);_x000D_
  color: #fff;_x000D_
}_x000D_
#menu {_x000D_
  float: left;_x000D_
  padding-top: 20px;_x000D_
  margin-left: 495px;_x000D_
  width: 390px;_x000D_
  color: #f1f1f1;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="header">_x000D_
    <div id="menu">_x000D_
      menu will go here_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Of course there will be a wrapper around both of them. You can control the location of the menu div which will be displayed within the header div with left margins and top positions. You can also set the div menu to float right if you like.

How can I convert IPV6 address to IPV4 address?

There isn't a 1-1 correspondence between IPv4 and IPv6 addresses (nor between IP addresses and devices), so what you're asking for generally isn't possible.

There is a particular range of IPv6 addresses that actually represent the IPv4 address space, but general IPv6 addresses will not be from this range.

Put spacing between divs in a horizontal row?

Put all the divs in a individual table cells and set the table style to padding: 5px;.

E.g.

_x000D_
_x000D_
<table style="width: 100%; padding: 5px;">_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
<div style="background-color: red;">A</div>_x000D_
</td>_x000D_
<td>_x000D_
<div style="background-color: orange;">B</div>_x000D_
</td>_x000D_
<td>_x000D_
<div style="background-color: green;">C</div>_x000D_
</td>_x000D_
<td>_x000D_
<div style="background-color: blue;">D</div>_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do you run your own code alongside Tkinter's event loop?

This is the first working version of what will be a GPS reader and data presenter. tkinter is a very fragile thing with way too few error messages. It does not put stuff up and does not tell why much of the time. Very difficult coming from a good WYSIWYG form developer. Anyway, this runs a small routine 10 times a second and presents the information on a form. Took a while to make it happen. When I tried a timer value of 0, the form never came up. My head now hurts! 10 or more times per second is good enough for me. I hope it helps someone else. Mike Morrow

import tkinter as tk
import time

def GetDateTime():
  # Get current date and time in ISO8601
  # https://en.wikipedia.org/wiki/ISO_8601 
  # https://xkcd.com/1179/
  return (time.strftime("%Y%m%d", time.gmtime()),
          time.strftime("%H%M%S", time.gmtime()),
          time.strftime("%Y%m%d", time.localtime()),
          time.strftime("%H%M%S", time.localtime()))

class Application(tk.Frame):

  def __init__(self, master):

    fontsize = 12
    textwidth = 9

    tk.Frame.__init__(self, master)
    self.pack()

    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             text='Local Time').grid(row=0, column=0)
    self.LocalDate = tk.StringVar()
    self.LocalDate.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             textvariable=self.LocalDate).grid(row=0, column=1)

    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             text='Local Date').grid(row=1, column=0)
    self.LocalTime = tk.StringVar()
    self.LocalTime.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             textvariable=self.LocalTime).grid(row=1, column=1)

    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             text='GMT Time').grid(row=2, column=0)
    self.nowGdate = tk.StringVar()
    self.nowGdate.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             textvariable=self.nowGdate).grid(row=2, column=1)

    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             text='GMT Date').grid(row=3, column=0)
    self.nowGtime = tk.StringVar()
    self.nowGtime.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             textvariable=self.nowGtime).grid(row=3, column=1)

    tk.Button(self, text='Exit', width = 10, bg = '#FF8080', command=root.destroy).grid(row=4, columnspan=2)

    self.gettime()
  pass

  def gettime(self):
    gdt, gtm, ldt, ltm = GetDateTime()
    gdt = gdt[0:4] + '/' + gdt[4:6] + '/' + gdt[6:8]
    gtm = gtm[0:2] + ':' + gtm[2:4] + ':' + gtm[4:6] + ' Z'  
    ldt = ldt[0:4] + '/' + ldt[4:6] + '/' + ldt[6:8]
    ltm = ltm[0:2] + ':' + ltm[2:4] + ':' + ltm[4:6]  
    self.nowGtime.set(gdt)
    self.nowGdate.set(gtm)
    self.LocalTime.set(ldt)
    self.LocalDate.set(ltm)

    self.after(100, self.gettime)
   #print (ltm)  # Prove it is running this and the external code, too.
  pass

root = tk.Tk()
root.wm_title('Temp Converter')
app = Application(master=root)

w = 200 # width for the Tk root
h = 125 # height for the Tk root

# get display screen width and height
ws = root.winfo_screenwidth()  # width of the screen
hs = root.winfo_screenheight() # height of the screen

# calculate x and y coordinates for positioning the Tk root window

#centered
#x = (ws/2) - (w/2)
#y = (hs/2) - (h/2)

#right bottom corner (misfires in Win10 putting it too low. OK in Ubuntu)
x = ws - w
y = hs - h - 35  # -35 fixes it, more or less, for Win10

#set the dimensions of the screen and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

root.mainloop()

Temporary table in SQL server causing ' There is already an object named' error

You are dropping it, then creating it, then trying to create it again by using SELECT INTO. Change to:

DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))  

INSERT INTO #TMPGUARDIAN 
SELECT LAST_NAME,FRST_NAME  
FROM TBL_PEOPLE

In MS SQL Server you can create a table without a CREATE TABLE statement by using SELECT INTO

Where can I find free WPF controls and control templates?

Codeplex is definitively the right place. Recent "post": SofaWPF.codeplex.com based on AvalonDock.codeplex.com, an IDE like framework.

Count number of objects in list

Let's create an empty list (not required, but good to know):

> mylist <- vector(mode="list")

Let's put some stuff in it - 3 components/indexes/tags (whatever you want to call it) each with differing amounts of elements:

> mylist <- list(record1=c(1:10),record2=c(1:5),record3=c(1:2))

If you are interested in just the number of components in a list use:

> length(mylist)
[1] 3

If you are interested in the length of elements in a specific component of a list use: (both reference the same component here)

length(mylist[[1]])
[1] 10
length(mylist[["record1"]]
[1] 10

If you are interested in the length of all elements in all components of the list use:

> sum(sapply(mylist,length))
[1] 17

how to refresh page in angular 2

Without a bit more code ... its hard to say what's going on.

But if your code looks something like this:

<li routerLinkActive="active">
  <a [routerLink]="/categories"><p>Products Categories</p></a>
</li>
...
<router-outlet></router-outlet>
<myComponentA></myComponentA>
<myComponentB></myComponentB>

Then clicking on the router link will route to the categories route and display its template in the router outlet.

Hiding and showing the child components don't affect what is displayed in the router outlet.

So if you click the link again, the categories route is already displayed in the router outlet and it won't display/re-initialize again.

If you could be a bit more specific about what you are trying to do, we could provide more specific suggestions for you. :-)

What is the error "Every derived table must have its own alias" in MySQL?

Here's a different example that can't be rewritten without aliases ( can't GROUP BY DISTINCT).

Imagine a table called purchases that records purchases made by customers at stores, i.e. it's a many to many table and the software needs to know which customers have made purchases at more than one store:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases)
  GROUP BY customer_id HAVING 1 < SUM(1);

..will break with the error Every derived table must have its own alias. To fix:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases) AS custom
  GROUP BY customer_id HAVING 1 < SUM(1);

( Note the AS custom alias).

Capture the Screen into a Bitmap

I had two problems with the accepted answer.

  1. It doesn't capture all screens in a multi-monitor setup.
  2. The width and height returned by the Screen class are incorrect when display scaling is used and your application is not declared dpiAware.

Here's my updated solution using the Screen.AllScreens static property and calling EnumDisplaySettings using p/invoke to get the real screen resolution.

using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class Program
{
    const int ENUM_CURRENT_SETTINGS = -1;

    static void Main()
    {
        foreach (Screen screen in Screen.AllScreens)
        {
            DEVMODE dm = new DEVMODE();
            dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));
            EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref dm);

            using (Bitmap bmp = new Bitmap(dm.dmPelsWidth, dm.dmPelsHeight))
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.CopyFromScreen(dm.dmPositionX, dm.dmPositionY, 0, 0, bmp.Size);
                bmp.Save(screen.DeviceName.Split('\\').Last() + ".png");
            }
        }
    }

    [DllImport("user32.dll")]
    public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);

    [StructLayout(LayoutKind.Sequential)]
    public struct DEVMODE
    {
        private const int CCHDEVICENAME = 0x20;
        private const int CCHFORMNAME = 0x20;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
        public string dmDeviceName;
        public short dmSpecVersion;
        public short dmDriverVersion;
        public short dmSize;
        public short dmDriverExtra;
        public int dmFields;
        public int dmPositionX;
        public int dmPositionY;
        public ScreenOrientation dmDisplayOrientation;
        public int dmDisplayFixedOutput;
        public short dmColor;
        public short dmDuplex;
        public short dmYResolution;
        public short dmTTOption;
        public short dmCollate;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
        public string dmFormName;
        public short dmLogPixels;
        public int dmBitsPerPel;
        public int dmPelsWidth;
        public int dmPelsHeight;
        public int dmDisplayFlags;
        public int dmDisplayFrequency;
        public int dmICMMethod;
        public int dmICMIntent;
        public int dmMediaType;
        public int dmDitherType;
        public int dmReserved1;
        public int dmReserved2;
        public int dmPanningWidth;
        public int dmPanningHeight;
    }
}

References:

https://stackoverflow.com/a/36864741/987968 http://pinvoke.net/default.aspx/user32/EnumDisplaySettings.html?diff=y

How to call javascript function on page load in asp.net

Place this line before the closing script tag,writing from memory:

window.onload  = GetTimeZoneOffset;

i think the question is how to call the javascript function on pageload

Find all files with name containing string

Use grep as follows:

grep -R "touch" .

-R means recurse. If you would rather not go into the subdirectories, then skip it.

-i means "ignore case". You might find this worth a try as well.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

How to select min and max values of a column in a datatable?

This worked fine for me

int  max = Convert.ToInt32(datatable_name.AsEnumerable()
                        .Max(row => row["column_Name"]));

Change One Cell's Data in mysql

My answer is repeating what others have said before, but I thought I'd add an example, using MySQL, only because the previous answers were a little bit cryptic to me.

The general form of the command you need to use to update a single row's column:

UPDATE my_table SET my_column='new value' WHERE something='some value';

And here's an example.

BEFORE

mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 | 
| CDRECORD   | 10104 | 
+------------+-------+
2 rows in set (0.00 sec)

MAKING THE CHANGE

mysql> update ae set port='10105' where aet='CDRECORD';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

AFTER

mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 | 
| CDRECORD   | 10105 | 
+------------+-------+
2 rows in set (0.00 sec)

How can I loop through all rows of a table? (MySQL)

Since the suggestion of a loop implies the request for a procedure type solution. Here is mine.

Any query which works on any single record taken from a table can be wrapped in a procedure to make it run through each row of a table like so:

First delete any existing procedure with the same name, and change the delimiter so your SQL doesn't try to run each line as you're trying to write the procedure.

DROP PROCEDURE IF EXISTS ROWPERROW;
DELIMITER ;;

Then here's the procedure as per your example (table_A and table_B used for clarity)

CREATE PROCEDURE ROWPERROW()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM table_A INTO n;
SET i=0;
WHILE i<n DO 
  INSERT INTO table_B(ID, VAL) SELECT (ID, VAL) FROM table_A LIMIT i,1;
  SET i = i + 1;
END WHILE;
End;
;;

Then dont forget to reset the delimiter

DELIMITER ;

And run the new procedure

CALL ROWPERROW();

You can do whatever you like at the "INSERT INTO" line which I simply copied from your example request.

Note CAREFULLY that the "INSERT INTO" line used here mirrors the line in the question. As per the comments to this answer you need to ensure that your query is syntactically correct for which ever version of SQL you are running.

In the simple case where your ID field is incremented and starts at 1 the line in the example could become:

INSERT INTO table_B(ID, VAL) VALUES(ID, VAL) FROM table_A WHERE ID=i;

Replacing the "SELECT COUNT" line with

SET n=10;

Will let you test your query on the first 10 record in table_A only.

One last thing. This process is also very easy to nest across different tables and was the only way I could carry out a process on one table which dynamically inserted different numbers of records into a new table from each row of a parent table.

If you need it to run faster then sure try to make it set based, if not then this is fine. You could also rewrite the above in cursor form but it may not improve performance. eg:

DROP PROCEDURE IF EXISTS cursor_ROWPERROW;
DELIMITER ;;

CREATE PROCEDURE cursor_ROWPERROW()
BEGIN
  DECLARE cursor_ID INT;
  DECLARE cursor_VAL VARCHAR;
  DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT ID,VAL FROM table_A;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO cursor_ID, cursor_VAL;
    IF done THEN
      LEAVE read_loop;
    END IF;
    INSERT INTO table_B(ID, VAL) VALUES(cursor_ID, cursor_VAL);
  END LOOP;
  CLOSE cursor_i;
END;
;;

Remember to declare the variables you will use as the same type as those from the queried tables.

My advise is to go with setbased queries when you can, and only use simple loops or cursors if you have to.

How to make Bitmap compress without change the bitmap size?

i think you use this method to compress the bitmap

BitmapFactory.Option imageOpts = new BitmapFactory.Options ();
imageOpts.inSampleSize = 2;   // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap (BitmapFactory.decodeFile(photoPath, imageOpts), 96, 96, false);

MongoDB: Is it possible to make a case-insensitive query?

The aggregation framework was introduced in mongodb 2.2 . You can use the string operator "$strcasecmp" to make a case-insensitive comparison between strings. It's more recommended and easier than using regex.

Here's the official document on the aggregation command operator: https://docs.mongodb.com/manual/reference/operator/aggregation/strcasecmp/#exp._S_strcasecmp .