Programs & Examples On #Sevenzipsharp

C Sharp implementation of the 7 Zip library.

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Try the following code to display scroll bar always on your page,

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: rgba(0,0,0,.5);
  -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

this will always show the vertical and horizontal scroll bar on your page. If you need only a vertical scroll bar then put overflow-x: hidden

Plot multiple lines in one graph

You should bring your data into long (i.e. molten) format to use it with ggplot2:

library("reshape2")
mdf <- melt(mdf, id.vars="Company", value.name="value", variable.name="Year")

And then you have to use aes( ... , group = Company ) to group them:

ggplot(data=mdf, aes(x=Year, y=value, group = Company, colour = Company)) +
    geom_line() +
    geom_point( size=4, shape=21, fill="white")

enter image description here

Visual Studio 2015 Update 3 Offline Installer (ISO)

Its better to go through the Recommended Microsoft's Way to download Visual Studio 2015 Update 3 ISO (Community Edition).

The instructions below will help you to download any version of Visual Studio or even SQL Server etc provided by Microsoft in an easy to remember way. Though I recommend people using VS 2017 as there are not much big differences between 2015 and 2017.

Please follow the steps as mentioned below.

  1. Visit the standard URL www.visualstudio.com/downloads

  2. Scroll down and click on encircled below as shown in snapshot down Snapshot showing how to download older visual studio versions

  3. After that join Visual Studio Web Dev essentials for Free as shown below. Try loggin in with your microsoft account and see that if it works otherwise click on Joinenter image description here

  4. Click on Downloads ICON on the encircled as shown below. enter image description here

  5. Now Type Visual Studio Community in the Search Box as shown below in the snapshot enter image description here.
  6. From the drowdown select the DVD type and start downloading enter image description here

What is the --save option for npm install?

Update npm 5:

As of npm 5.0.0, installed modules are added as a dependency by default, so the --save option is no longer needed. The other save options still exist and are listed in the documentation for npm install.

Original answer:

Before version 5, NPM simply installed a package under node_modules by default. When you were trying to install dependencies for your app/module, you would need to first install them, and then add them (along with the appropriate version number) to the dependencies section of your package.json.

The --save option instructed NPM to include the package inside of the dependencies section of your package.json automatically, thus saving you an additional step.

In addition, there are the complementary options --save-dev and --save-optional which save the package under devDependencies and optionalDependencies, respectively. This is useful when installing development-only packages, like grunt or your testing library.

HTTP authentication logout via PHP

Maybe I'm missing the point.

The most reliable way I've found to end HTTP Authentication is to close the browser and all browser windows. You can close a browser window using Javascript but I don't think you can close all browser windows.

mysqli or PDO - what are the pros and cons?

Personally I use PDO, but I think that is mainly a question of preference.

PDO has some features that help agains SQL injection (prepared statements), but if you are careful with your SQL you can achieve that with mysqli, too.

Moving to another database is not so much a reason to use PDO. As long as you don't use "special SQL features", you can switch from one DB to another. However as soon as you use for example "SELECT ... LIMIT 1" you can't go to MS-SQL where it is "SELECT TOP 1 ...". So this is problematic anyway.

ORA-00979 not a group by expression

Include in the GROUP BY clause all SELECT expressions that are not group function arguments.

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

If B is a Boolean array, write

B = B*1

(A bit code golfy.)

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

How do I remove an object from an array with JavaScript?

_x000D_
_x000D_
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];_x000D_
var ind = arr.findIndex(function(element){_x000D_
   return element.id===2;_x000D_
})_x000D_
if(ind!==-1){_x000D_
arr.splice(ind, 1)_x000D_
}_x000D_
console.log (arr)
_x000D_
_x000D_
_x000D_

Please note that findIndex method is not supported in Internet Explorer but polyfill can be used from here

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

How to set margin of ImageView using code, not xml

We can create Linear LayoutParams & use resources.getDimensionPixelSize for dp value.

    val mContext = parent.context
    val mImageView = AppCompatImageView(mContext)
    mImageView.setBackgroundResource(R.drawable.payment_method_selector)

    val height = mContext.resources.getDimensionPixelSize(R.dimen.payment_logo_height)
    val width = mContext.resources.getDimensionPixelSize(R.dimen.payment_logo_width)
    val padding = mContext.resources.getDimensionPixelSize(R.dimen.spacing_small_tiny)
    val margin = mContext.resources.getDimensionPixelSize(R.dimen.spacing_small)

    mImageView.layoutParams = LinearLayout.LayoutParams(width, height).apply {
        setMargins(margin, margin, 0, 0)
    }
    mImageView.setPadding(padding, padding, padding, padding)

create table in postgreSQL

First the bigint(20) not null auto_increment will not work, simply use bigserial primary key. Then datetime is timestamp in PostgreSQL. All in all:

CREATE TABLE article (
    article_id bigserial primary key,
    article_name varchar(20) NOT NULL,
    article_desc text NOT NULL,
    date_added timestamp default NULL
);

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You can also use the ignore syntax instead of using (or better the 'as any') notation:

// @ts-ignore
$("div.printArea").printArea();

Can You Get A Users Local LAN IP Address Via JavaScript?

You can find more info about what limitations browsers will likely add to mitigate this and what IETF is doing about it as well as why this is needed at IETF SPEC on IP handling

Does "display:none" prevent an image from loading?

Hi guys I was struggling with the same issue, how to not load an image on mobile.

But I figured out a good solution. First make an img tag and then load a blank svg in the src attribute. Now you can set your URL to the image as an inline style with content: url('link to your image');. Now wrap your img tag in a wrapper of your choice.

<div class="test">
  <img src="data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/??svg%22/%3E" style="content:url('https://blog.prepscholar.com/hubfs/body_testinprogress.gif?t=1495225010554')">
</div>

  @media only screen and (max-width: 800px) {
      .test{
       display: none;
      }
    }

Set the wrapper to display none on the breakpoint where you dont want to load the image. The inline css of the img tag is now ignored since the style of an element wrapped in a wrapper with display none will be ignored, therefore the image is not loaded, until you reach a breakpoint where the wrapper has display block.

There you go, really easy way not to load an img on mobile breakpoint :)

Check out this codepen, for a working example: http://codepen.io/fennefoss/pen/jmXjvo

Determine Pixel Length of String in Javascript/jQuery?

First replicate the location and styling of the text and then use Jquery width() function. This will make the measurements accurate. For example you have css styling with a selector of:

.style-head span
{
  //Some style set
}

You would need to do this with Jquery already included above this script:

var measuringSpan = document.createElement("span");
measuringSpan.innerText = 'text to measure';
measuringSpan.style.display = 'none'; /*so you don't show that you are measuring*/
$('.style-head')[0].appendChild(measuringSpan);
var theWidthYouWant = $(measuringSpan).width();

Needless to say

theWidthYouWant

will hold the pixel length. Then remove the created elements after you are done or you will get several if this is done a several times. Or add an ID to reference instead.

How to return multiple values in one column (T-SQL)?

group_concat() sounds like what you're looking for.

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:

http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html

How to capture Curl output to a file?

For those of you want to copy the cURL output in the clipboard instead of outputting to a file, you can use pbcopy by using the pipe | after the cURL command.

Example: curl https://www.google.com/robots.txt | pbcopy. This will copy all the content from the given URL to your clipboard.

How are VST Plugins made?

I wrote up a HOWTO for VST development on C++ with Visual Studio awhile back which details the steps necessary to create a basic plugin for the Windows platform (the Mac version of this article is forthcoming). On Windows, a VST plugin is just a normal DLL, but there are a number of "gotchas", and you need to build the plugin using some specific compiler/linker switches or else it won't be recognized by some hosts.

As for the Mac, a VST plugin is just a bundle with the .vst extension, though there are also a few settings which must be configured correctly in order to generate a valid plugin. You can also download a set of Xcode VST plugin project templates I made awhile back which can help you to write a working plugin on that platform.

As for AudioUnits, Apple has provided their own project templates which are included with Xcode. Apple also has very good tutorials and documentation online:

I would also highly recommend checking out the Juce Framework, which has excellent support for creating cross-platform VST/AU plugins. If you're going open-source, then Juce is a no-brainer, but you will need to pay licensing fees for it if you plan on releasing your work without source code.

Custom Listview Adapter with filter Android

In your CustomAdapter class implement filterable.

listview with search search listview

 public class CustomAdapter extends BaseAdapter implements Filterable {

    private List<ItemsModel> itemsModelsl;
    private List<ItemsModel> itemsModelListFiltered;
    private Context context;

    public CustomAdapter(List<ItemsModel> itemsModelsl, Context context) {
        this.itemsModelsl = itemsModelsl;
        this.itemsModelListFiltered = itemsModelsl;
        this.context = context;
    }



    @Override
    public int getCount() {
        return itemsModelListFiltered.size();
    }

    @Override
    public Object getItem(int position) {
        return itemsModelListFiltered.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = getLayoutInflater().inflate(R.layout.row_items,null);


        TextView names = view.findViewById(R.id.name);
        TextView emails = view.findViewById(R.id.email);
        ImageView imageView = view.findViewById(R.id.images);

        names.setText(itemsModelListFiltered.get(position).getName());
        emails.setText(itemsModelListFiltered.get(position).getEmail());
        imageView.setImageResource(itemsModelListFiltered.get(position).getImages());

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("main activity","item clicked");
                startActivity(new Intent(MainActivity.this,ItemsPreviewActivity.class).putExtra("items",itemsModelListFiltered.get(position)));

            }
        });

        return view;
    }



    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults filterResults = new FilterResults();
                if(constraint == null || constraint.length() == 0){
                    filterResults.count = itemsModelsl.size();
                    filterResults.values = itemsModelsl;

                }else{
                    List<ItemsModel> resultsModel = new ArrayList<>();
                    String searchStr = constraint.toString().toLowerCase();

                    for(ItemsModel itemsModel:itemsModelsl){
                        if(itemsModel.getName().contains(searchStr) || itemsModel.getEmail().contains(searchStr)){
                            resultsModel.add(itemsModel);

                        }
                         filterResults.count = resultsModel.size();
                            filterResults.values = resultsModel;
                    }


                }

                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                itemsModelListFiltered = (List<ItemsModel>) results.values;
                notifyDataSetChanged();

            }
        };
        return filter;
    }
}

}

You can get the whole tutorial here: ListView With Search/Filter and OnItemClickListener

Github Source Code

Convert ASCII number to ASCII Character in C

You can assign int to char directly.

int a = 65;
char c = a;
printf("%c", c);

In fact this will also work.

printf("%c", a);  // assuming a is in valid range

Sorting a vector of custom objects

Sorting such a vector or any other applicable (mutable input iterator) range of custom objects of type X can be achieved using various methods, especially including the use of standard library algorithms like

Since most of the techniques, to obtain relative ordering of X elements, have already been posted, I'll start by some notes on "why" and "when" to use the various approaches.

The "best" approach will depend on different factors:

  1. Is sorting ranges of X objects a common or a rare task (will such ranges be sorted a mutiple different places in the program or by library users)?
  2. Is the required sorting "natural" (expected) or are there multiple ways the type could be compared to itself?
  3. Is performance an issue or should sorting ranges of X objects be foolproof?

If sorting ranges of X is a common task and the achieved sorting is to be expected (i.e. X just wraps a single fundamental value) then on would probably go for overloading operator< since it enables sorting without any fuzz (like correctly passing proper comparators) and repeatedly yields expected results.

If sorting is a common task or likely to be required in different contexts, but there are multiple criteria which can be used to sort X objects, I'd go for Functors (overloaded operator() functions of custom classes) or function pointers (i.e. one functor/function for lexical ordering and another one for natural ordering).

If sorting ranges of type X is uncommon or unlikely in other contexts I tend to use lambdas instead of cluttering any namespace with more functions or types.

This is especially true if the sorting is not "clear" or "natural" in some way. You can easily get the logic behind the ordering when looking at a lambda that is applied in-place whereas operator< is opague at first sight and you'd have to look the definition up to know what ordering logic will be applied.

Note however, that a single operator< definition is a single point of failure whereas multiple lambas are multiple points of failure and require a more caution.

If the definition of operator< isn't available where the sorting is done / the sort template is compiled, the compiler might be forced to make a function call when comparing objects, instead of inlining the ordering logic which might be a severe drawback (at least when link time optimization/code generation is not applied).

Ways to achieve comparability of class X in order to use standard library sorting algorithms

Let std::vector<X> vec_X; and std::vector<Y> vec_Y;

1. Overload T::operator<(T) or operator<(T, T) and use standard library templates that do not expect a comparison function.

Either overload member operator<:

struct X {
  int i{}; 
  bool operator<(X const &r) const { return i < r.i; } 
};
// ...
std::sort(vec_X.begin(), vec_X.end());

or free operator<:

struct Y {
  int j{}; 
};
bool operator<(Y const &l, Y const &r) { return l.j < r.j; }
// ...
std::sort(vec_Y.begin(), vec_Y.end());

2. Use a function pointer with a custom comparison function as sorting function parameter.

struct X {
  int i{};  
};
bool X_less(X const &l, X const &r) { return l.i < r.i; }
// ...
std::sort(vec_X.begin(), vec_X.end(), &X_less);

3. Create a bool operator()(T, T) overload for a custom type which can be passed as comparison functor.

struct X {
  int i{};  
  int j{};
};
struct less_X_i
{
    bool operator()(X const &l, X const &r) const { return l.i < r.i; }
};
struct less_X_j
{
    bool operator()(X const &l, X const &r) const { return l.j < r.j; }
};
// sort by i
std::sort(vec_X.begin(), vec_X.end(), less_X_i{});
// or sort by j
std::sort(vec_X.begin(), vec_X.end(), less_X_j{});

Those function object definitions can be written a little more generic using C++11 and templates:

struct less_i
{ 
    template<class T, class U>
    bool operator()(T&& l, U&& r) const { return std::forward<T>(l).i < std::forward<U>(r).i; }
};

which can be used to sort any type with member i supporting <.

4. Pass an anonymus closure (lambda) as comparison parameter to the sorting functions.

struct X {
  int i{}, j{};
};
std::sort(vec_X.begin(), vec_X.end(), [](X const &l, X const &r) { return l.i < r.i; });

Where C++14 enables a even more generic lambda expression:

std::sort(a.begin(), a.end(), [](auto && l, auto && r) { return l.i < r.i; });

which could be wrapped in a macro

#define COMPARATOR(code) [](auto && l, auto && r) -> bool { return code ; }

making ordinary comparator creation quite smooth:

// sort by i
std::sort(v.begin(), v.end(), COMPARATOR(l.i < r.i));
// sort by j
std::sort(v.begin(), v.end(), COMPARATOR(l.j < r.j));

Is there a way to set background-image as a base64 encoded image?

I tried to do the same as you, but apparently the backgroundImage doesn't work with encoded data. As an alternative, I suggest to use CSS classes and the change between those classes.

If you are generating the data "on the fly" you can load the CSS files dynamically.

CSS:

.backgroundA {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDUxRjY0ODgyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDUxRjY0ODkyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpENTFGNjQ4NjJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpENTFGNjQ4NzJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuT868wAAABESURBVHja7M4xEQAwDAOxuPw5uwi6ZeigB/CntJ2lkmytznwZFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW1qsrwABYuwNkimqm3gAAAABJRU5ErkJggg==");
}

.backgroundB {
    background-image:url("data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPbWLrc/jDKSVe4OOvNu/9gqARDSRBHegyGMahqO4R0bQcjIQ8E4BMCQc930JluyGRmdAAcdiigMLVrApTYWy5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KTkpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxMAF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=");
}

HTML:

<div id="test" height="20px" class="backgroundA"> 
  div test 1
</div>
<div id="test2" name="test2" height="20px" class="backgroundB">
  div test2
</div>
<input type="button" id="btn" />

Javascript:

function change() {
    if (document.getElementById("test").className =="backgroundA") {
        document.getElementById("test").className="backgroundB";
        document.getElementById("test2").className="backgroundA";
    } else {
        document.getElementById("test").className="backgroundA";
        document.getElementById("test2").className="backgroundB";
    }
}

btn.onclick= change;

I fiddled it here, press the button and it will switch the divs' backgrounds: http://jsfiddle.net/egorbatik/fFQC6/

React onClick and preventDefault() link refresh/redirect?

I've had some troubles with anchor tags and preventDefault in the past and I always forget what I'm doing wrong, so here's what I figured out.

The problem I often have is that I try to access the component's attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault():

function (e, { href }) {
  e.preventDefault();
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

It seems the destructuring causes an error (Cannot read property 'href' of undefined) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault doesn't get called. If the href is #, the error is displayed properly since there's no actual reload.

I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:

function (e) {
  e.preventDefault();
  const { href } = e.target;
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

I hope this helps other people like me puzzled by not shown errors!

How to display HTML tags as plain text

Replace < with &lt; and > with &gt;.

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.

For RESTeasy, you should use CorsFilter. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.

See Also:

inject bean reference into a Quartz job in Spring?

When you already use real AspectJ in your project, then you could annotate the job bean class with @Configurable. Then Spring will inject into this class, even if it is constructed via new

Local variable referenced before assignment?

In order for you to modify test1 while inside a function you will need to do define test1 as a global variable, for example:

test1 = 0
def testFunc():
    global test1 
    test1 += 1
testFunc()

However, if you only need to read the global variable you can print it without using the keyword global, like so:

test1 = 0
def testFunc():
     print test1 
testFunc()

But whenever you need to modify a global variable you must use the keyword global.

How to re-enable right click so that I can inspect HTML elements in Chrome?

If none of the other comments works, just do, open console line command and type:

document.oncontextmenu = null;

Python check if website exists

code:

a="http://www.example.com"
try:    
    print urllib.urlopen(a)
except:
    print a+"  site does not exist"

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    call('notepad.exe')
    print('hello')  # only executed when notepad is closed
    
  • Popen is non-blocking:

    Popen('notepad.exe')
    print('hello')  # immediately executed
    

Converting double to string

double priceG = Double.parseDouble(priceGal.getText().toString());

double valG = Double.parseDouble(volGal.toString());

double priceG = Double.parseDouble(priceGal.getText().toString());

double valG = Double.parseDouble(volGal.toString());

double priceG = Double.parseDouble(priceGal.getText().toString());

double valG = Double.parseDouble(volGal.toString());

it works. got to be repetitive.

Set Text property of asp:label in Javascript PROPER way

Use the following code

<span id="sptext" runat="server"></span>

Java Script

document.getElementById('<%=sptext'%>).innerHTML='change text';

C#

sptext.innerHTML

'JSON' is undefined error in JavaScript in Internet Explorer

<!DOCTYPE html>

Otherwise IE8 is not acting right. Also you should use:

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

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

Now that opts is deprecated in ggplot2 package, function theme should be used instead:

library(grid) # for unit()
... + theme(legend.key.height=unit(3,"line"))
... + theme(legend.key.width=unit(3,"line"))

Getting Serial Port Information

None of the answers here satisfies my needs.

The answer from Muno is wrong because it lists ONLY the USB ports.

The answer from code4life is wrong because it lists all EXCEPT the USB ports. (Nevertheless it has 44 up-votes!!!)

I have an EPSON printer simulation port on my computer which is not listed by any of the answers here. So I had to write my own solution. Additionally I want to display more information than just the caption string. I also need to separate the port name from the description.

My code has been tested on Windows XP, Windows 7 and Windows 10.

The Port Name (like "COM1") must be read from the registry because WMI does not give this information for all COM ports (EPSON).

If you use my code you do not need SerialPort.GetPortNames() anymore. My function returns the same ports, but with additional details. Why did Microsoft not implement such a function into the framework??

using System.Management;
using Microsoft.Win32;

using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
{
    foreach (ManagementObject i_Inst in i_Entity.GetInstances())
    {
        Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
        if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
            continue; // Skip all devices except device class "PORTS"

        String s_Caption  = i_Inst.GetPropertyValue("Caption")     .ToString();
        String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
        String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID") .ToString();
        String s_RegPath  = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
        String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();

        int s32_Pos = s_Caption.IndexOf(" (COM");
        if (s32_Pos > 0) // remove COM port from description
            s_Caption = s_Caption.Substring(0, s32_Pos);

        Console.WriteLine("Port Name:    " + s_PortName);
        Console.WriteLine("Description:  " + s_Caption);
        Console.WriteLine("Manufacturer: " + s_Manufact);
        Console.WriteLine("Device ID:    " + s_DeviceID);
        Console.WriteLine("-----------------------------------");
    }
}

I tested the code with a lot of COM ports. This is the Console output:

Port Name:    COM29
Description:  CDC Interface (Virtual COM Port) for USB Debug
Manufacturer: GHI Electronics, LLC
Device ID:    USB\VID_1B9F&PID_F003&MI_01\6&3009671A&0&0001
-----------------------------------
Port Name:    COM28
Description:  Teensy USB Serial
Manufacturer: PJRC.COM, LLC.
Device ID:    USB\VID_16C0&PID_0483\1256310
-----------------------------------
Port Name:    COM25
Description:  USB-SERIAL CH340
Manufacturer: wch.cn
Device ID:    USB\VID_1A86&PID_7523\5&2499667D&0&3
-----------------------------------
Port Name:    COM26
Description:  Prolific USB-to-Serial Comm Port
Manufacturer: Prolific
Device ID:    USB\VID_067B&PID_2303\5&2499667D&0&4
-----------------------------------
Port Name:    COM1
Description:  Comunications Port
Manufacturer: (Standard port types)
Device ID:    ACPI\PNP0501\1
-----------------------------------
Port Name:    COM999
Description:  EPSON TM Virtual Port Driver
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0000
-----------------------------------
Port Name:    COM20
Description:  EPSON COM Emulation USB Port
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0001
-----------------------------------
Port Name:    COM8
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&000F\8&3ADBDF90&0&001DA568988B_C00000000
-----------------------------------
Port Name:    COM9
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\8&3ADBDF90&0&000000000000_00000002
-----------------------------------
Port Name:    COM30
Description:  Arduino Uno
Manufacturer: Arduino LLC (www.arduino.cc)
Device ID:    USB\VID_2341&PID_0001\74132343530351F03132
-----------------------------------

COM1 is a COM port on the mainboard.

COM 8 and 9 are Buetooth COM ports.

COM 25 and 26 are USB to RS232 adapters.

COM 28 and 29 and 30 are Arduino-like boards.

COM 20 and 999 are EPSON ports.

C function that counts lines in file

Here is my function

char *fileName = "input-1.txt";
countOfLinesFromFile(fileName);

void countOfLinesFromFile(char *filename){
FILE* myfile = fopen(filename, "r");
int ch, number_of_lines = 0;
do
{
    ch = fgetc(myfile);
    if(ch == '\n')
        number_of_lines++;
}
while (ch != EOF);
if(ch != '\n' && number_of_lines != 0)
    number_of_lines++;
fclose(myfile);
printf("number of lines in  %s   = %d",filename, number_of_lines);

}

How to pass List<String> in post method using Spring MVC?

You are using wrong JSON. In this case you should use JSON that looks like this:

["orange", "apple"]

If you have to accept JSON in that form :

{"fruits":["apple","orange"]}

You'll have to create wrapper object:

public class FruitWrapper{

    List<String> fruits;

    //getter
    //setter
}

and then your controller method should look like this:

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST, 
    consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}

How to access command line arguments of the caller inside a function?

#!/usr/bin/env bash

echo name of script is $0
echo first argument is $1
echo second argument is $2
echo seventeenth argument is $17
echo number of arguments is $#

Edit: please see my comment on question

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region;

This should show you the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION

Now simply issue an:

alter table region drop foreign key region_ibfk_1;

And finally an:

alter table region drop column country_id;

And you are good to go!

Export and Import all MySQL databases at one time

All the answers I see on this question can have problems with the character sets in some databases due to the problem of redirecting the exit of mysqldump to a file within the shell operator >.

To solve this problem you should do the backup with a command like this

mysqldump -u root -p --opt --all-databases -r backup.sql

To do a good BD restore without any problem with character sets. Obviously you can change the default-character-set as you need.

mysql -uroot -p --default-character-set=utf8
mysql> SET names 'utf8';
mysql> SOURCE backup.sql;

How to make the python interpreter correctly handle non-ASCII characters in string operations?

This is a dirty hack, but may work.

s2 = ""
for i in s:
    if ord(i) < 128:
        s2 += i

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Both of these operations restore a set of files to a previous state and are essentially faster, safer ways of undoing mistakes than using the p4 obliterate command (and you don't need admin access to use them).

In the case of "Rollback...", this could be any number of files, even an entire depot. You can tell it to rollback to a specific revision, changelist, or label. The files are restored to the state they were in at the time of creation of that revision, changelist, or label.

In the case of "Back Out Submitted Changelist #####", the restore operation is restricted to the files that were submitted in changelist #####. Those files are restored to the state they were in before you submitted that changelist, provided no changes have been made to those files since. If subsequent changes have been made to any of those files, Perforce will tell you that those files are now out of date. You will have to sync to the head revision and then resolve the differences. This way you don't inadvertently clobber any changes that you actually want to keep.

Both operations work by essentially submitting old revisions as new revisions. When you perform a "Rollback...", you are restoring the files to the state they were in at a specific point in time, regardless of what has happened to them since. When you perform a "Back out...", you are attempting to undo the changes you made at a specific point in time, while maintaining the changes that have occurred since.

Get index of array element faster than O(n)

Is there a good reason not to use a hash? Lookups are O(1) vs. O(n) for the array.

How can I delay a method call for 1 second?

There are already a lot of answers and they are all correct. In case you want to use the dispatch_after you should be looking for the snippet which is included inside the Code Snippet Library at the right bottom (where you can select the UI elements).

enter image description here

So you just need to call this snippet by writing dispatch in code:

enter image description here

How to read appSettings section in the web.config file?

    using System.Configuration;

    /// <summary>
    /// For read one setting
    /// </summary>
    /// <param name="key">Key correspondent a your setting</param>
    /// <returns>Return the String contains the value to setting</returns>
    public string ReadSetting(string key)
    {
        var appSettings = ConfigurationManager.AppSettings;
        return appSettings[key] ?? string.Empty;
    }

    /// <summary>
    /// Read all settings for output Dictionary<string,string> 
    /// </summary>        
    /// <returns>Return the Dictionary<string,string> contains all settings</returns>
    public Dictionary<string, string> ReadAllSettings()
    {
        var result = new Dictionary<string, string>();
        foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            result.Add(key, ConfigurationManager.AppSettings[key]);
        return result;
    }

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

How to create .ipa file using Xcode?

At the time of Building select device as iOS device. Then build the application. Select Product->Archive then select Share and save the .ipa file. Rename the ipa file to .zip and double click on zip file and you will get .app file in the folder. then compress the .app file of the application and iTunesArtwork image. it will be in the format .zip rename .zip to .ipa file.

Lodash - difference between .extend() / .assign() and .merge()

If you want a deep copy without override while retaining the same obj reference

obj = _.assign(obj, _.merge(obj, [source]))

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

I had the same problem. I needed a 64-bit version of Python so I installed 3.5.0 (the most recent as of writing this). After switching to 3.4.3 all of my module installations worked.

Python Releases for Windows

write() versus writelines() and concatenated strings

if you just want to save and load a list try Pickle

Pickle saving:

with open("yourFile","wb")as file:
 pickle.dump(YourList,file)

and loading:

with open("yourFile","rb")as file:
 YourList=pickle.load(file)

Jquery Hide table rows

$('inputFile').parent().parent().children('td > label').hide();

can help you navigate two levels up ( to TD, to TR ) moving two levels back down ( all TD's in that TR and their LABEL tags ), applying the hide() function there.

if you want to stay at the TR level and hide them:

$('inputFile').parent().parent().hide();

… is sufficient.

you can navigate very easily through the elements using the jquery selectors.

parent is documented here: http://api.jquery.com/parent/

hide is documented here: http://api.jquery.com/hide/

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

PHP convert XML to JSON

If you would like to only convert a specific part of the XML to JSON, you can use XPath to retrieve this and convert that to JSON.

<?php
$file = @file_get_contents($xml_File, FILE_TEXT);
$xml = new SimpleXMLElement($file);
$xml_Excerpt = @$xml->xpath('/states/state[@id="AL"]')[0]; // [0] gets the node
echo json_encode($xml_Excerpt);
?>

Please note that if you Xpath is incorrect, this will die with an error. So if you're debugging this through AJAX calls I recommend you log the response bodies as well.

How to index characters in a Golang string?

String characters are runes, so to print them, you have to turn them back into String.

fmt.Print(string("HELLO"[1]))

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Adding an onclick function to go to url in JavaScript?

Simply use this

onclick="location.href='pageurl.html';"

How to check command line parameter in ".bat" file?

I've been struggling recently with the implementation of complex parameter switches in a batch file so here is the result of my research. None of the provided answers are fully safe, examples:

"%1"=="-?" will not match if the parameter is enclosed in quotes (needed for file names etc.) or will crash if the parameter is in quotes and has spaces (again often seen in file names)

@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
rem echo First parameter is %1
if "%1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -?

starting parameter test...

Condition is true, param=-?

C:\>test.bat "-?"

starting parameter test...

Condition is false, param="-?"

Any combination with square brackets [%1]==[-?] or [%~1]==[-?] will fail in case the parameter has spaces within quotes:

@ECHO OFF
SETLOCAL 
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if [%~1]==[-?] (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat "long file name"

starting parameter test...

First parameter is "long file name"
file was unexpected at this time.

The proposed safest solution "%~1"=="-?" will crash with a complex parameter that includes text outside the quotes and text with spaces within the quotes:

@ECHO OFF
SETLOCAL 
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if "%~1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat -source:"long file name"

starting parameter test...

First parameter is -source:"long file name"
file was unexpected at this time.

The only way to ensure all above scenarios are covered is to use EnableDelayedExpansion and to pass the parameters by reference (not by value) using variables. Then even the most complex scenario will work fine:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
echo.
echo starting parameter test...
echo.
echo First parameter is %1
:: we assign the parameter to a variable to pass by reference with delayed expansion
set "var1=%~1"
echo var1 is !var1!
:: we assign the value to compare with to a second variable to pass by reference with delayed expansion
set "var2=-source:"c:\app images"\image.png"
echo var2 is !var2!
if "!var1!"=="!var2!" (echo Condition is true, param=!var1!) else (echo Condition is false, param=!var1!)
C:\>test.bat -source:"c:\app images"\image.png

starting parameter test...

First parameter is -source:"c:\app images"\image.png
var1 is -source:"c:\app images"\image.png
var2 is -source:"c:\app images"\image.png
Condition is true, param=-source:"c:\app images"\image.png

C:\>test.bat -source:"c:\app images"\image1.png

starting parameter test...

First parameter is -source:"c:\app images"\image1.png
var1 is -source:"c:\app images"\image1.png
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images"\image1.png

C:\>test.bat -source:"c:\app images\image.png"

starting parameter test...

First parameter is -source:"c:\app images\image.png"
var1 is -source:"c:\app images\image.png"
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images\image.png"

Get full path of a file with FileUpload Control

FileUpload will never give you the full path for security reasons.

Hash table in JavaScript

You could use my JavaScript hash table implementation, jshashtable. It allows any object to be used as a key, not just strings.

bash: mkvirtualenv: command not found

Use this procedure to create virtual env in ubuntu

Step 1

Install pip

   sudo apt-get install python-pip

step 2

Install virtualenv

   sudo pip install virtualenv

step 3

Create a dir to store your virtualenvs (I use ~/.virtualenvs)

   mkdir ~/.virtualenvs

or use this command to install specific version of python in env

virtualenv -p /usr/bin/python3.6 venv

step 4

   sudo pip install virtualenvwrapper

step 5

   sudo nano ~/.bashrc

step 6

Add this two line code at the end of the bashrc file

  export WORKON_HOME=~/.virtualenvs
  source /usr/local/bin/virtualenvwrapper.sh

step 7

Open new terminal (recommended)

step 8

Create a new virtualenv

  mkvirtualenv myawesomeproject

step 9

To load or switch between virtualenvs, use the workon command:

  workon myawesomeproject

step 10

To exit your new virtualenv, use

 deactivate

and make sure using pip vs pip3

OR follow the steps below to install virtual environment using python3

Install env

python3 -m venv my-project-env

and activate your virtual environment using the following command:

source my-project-env/bin/activate

or if you want particular python version

virtualenv --python=python3.7.5 myenv

Concat strings by & and + in VB.Net

From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.

    Dim s1 As String
    Dim i As Integer
    s1 = "Hello"
    i = 1
    String.Format("{0} {1}", s1, i)

It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?

What is the difference between \r and \n?

They're different characters. \r is carriage return, and \n is line feed.

On "old" printers, \r sent the print head back to the start of the line, and \n advanced the paper by one line. Both were therefore necessary to start printing on the next line.

Obviously that's somewhat irrelevant now, although depending on the console you may still be able to use \r to move to the start of the line and overwrite the existing text.

More importantly, Unix tends to use \n as a line separator; Windows tends to use \r\n as a line separator and Macs (up to OS 9) used to use \r as the line separator. (Mac OS X is Unix-y, so uses \n instead; there may be some compatibility situations where \r is used instead though.)

For more information, see the Wikipedia newline article.

EDIT: This is language-sensitive. In C# and Java, for example, \n always means Unicode U+000A, which is defined as line feed. In C and C++ the water is somewhat muddier, as the meaning is platform-specific. See comments for details.

How to read a local text file?

Visit Javascripture ! And go the section readAsText and try the example. You will be able to know how the readAsText function of FileReader works.

    <html>
    <head>
    <script>
      var openFile = function(event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function(){
          var text = reader.result;
          var node = document.getElementById('output');
          node.innerText = text;
          console.log(reader.result.substring(0, 200));
        };
        reader.readAsText(input.files[0]);
      };
    </script>
    </head>
    <body>
    <input type='file' accept='text/plain' onchange='openFile(event)'><br>
    <div id='output'>
    ...
    </div>
    </body>
    </html>

Pointers in C: when to use the ampersand and the asterisk?

When you are declaring a pointer variable or function parameter, use the *:

int *x = NULL;
int *y = malloc(sizeof(int)), *z = NULL;
int* f(int *x) {
    ...
}

NB: each declared variable needs its own *.

When you want to take the address of a value, use &. When you want to read or write the value in a pointer, use *.

int a;
int *b;
b = f(&a);
a = *b;

a = *f(&a);

Arrays are usually just treated like pointers. When you declare an array parameter in a function, you can just as easily declare it is a pointer (it means the same thing). When you pass an array to a function, you are actually passing a pointer to the first element.

Function pointers are the only things that don't quite follow the rules. You can take the address of a function without using &, and you can call a function pointer without using *.

Rails Object to hash

You could definitely use the attributes to return all attributes but you could add an instance method to Post, call it "to_hash" and have it return the data you would like in a hash. Something like

def to_hash
 { name: self.name, active: true }
end

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Thank to Brian for the code. I was trying to connect to the sql server with {call spname(?,?)} and I got errors, but when I change my code to exec sp... it works very well.

I post my code in hope this helps others with problems like mine:

ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();

try {
    cs=conn.prepareStatement("exec sp_name ?,?,?,?,?,?,?");
    cs.setEscapeProcessing(true);
    cs.setQueryTimeout(90);

    cs.setString(1, "valueA");

    cs.setString(2, "valueB");

    cs.setString(3, "0418");

    //commented, because no need to register parameters out!, I got results from the resultset. 
    //cs.registerOutParameter(1, Types.VARCHAR);
    //cs.registerOutParameter(2, Types.VARCHAR);

    rs = cs.executeQuery();
    ArrayList<ObjectX> listaObjectX = new ArrayList<ObjectX>();
    while (rs.next()) {

        ObjectX to = new ObjectX();
        to.setFecha(rs.getString(1));
        to.setRefId(rs.getString(2));
        to.setRefNombre(rs.getString(3));
        to.setUrl(rs.getString(4));

        listaObjectX.add(to);

    }
    return listaObjectX;
     } catch (SQLException se) {
        System.out.println("Error al ejecutar SQL"+ se.getMessage());
        se.printStackTrace();
        throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());

    } finally {

        try {

            rs.close();
            cs.close();
          con.close();

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

HttpClient - A task was cancelled?

I ran into this issue because my Main() method wasn't waiting for the task to complete before returning, so the Task<HttpResponseMessage> myTask was being cancelled when my console program exited.

The solution was to call myTask.GetAwaiter().GetResult() in Main() (from this answer).

Understanding INADDR_ANY for socket programming

INADDR_ANY instructs listening socket to bind to all available interfaces. It's the same as trying to bind to inet_addr("0.0.0.0"). For completeness I'll also mention that there is also IN6ADDR_ANY_INIT for IPv6 and it's the same as trying to bind to :: address for IPv6 socket.

#include <netinet/in.h>

struct in6_addr addr = IN6ADDR_ANY_INIT;

Also, note that when you bind IPv6 socket to to IN6ADDR_ANY_INIT your socket will bind to all IPv6 interfaces, and should be able to accept connections from IPv4 clients as well (though IPv6-mapped addresses).

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

July 25, 2019 :

I was facing this issue in Android Studio 3.0.1 :

After checking lots of posts, here is Fix which works:

Go to module build.gradle and within Android block add this script:

splits {
    abi {
        enable true
        reset()
        include 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'mips', 'mips64', 'arm64-v8a'
        universalApk true
    }
}

Simple Solution. Feel free to comment. Thanks.

OWIN Startup Class Missing

Have a look for the Startup.cs file, you might be missing one of these. This file is the entry point for OWIN, so it sounds like this is missing. Take a look at OWIN Startup class here to understand whats going on.

As your error specifies, you can disable this in the web.config by doing the following...

To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config

How to convert a string to a date in sybase

102 is the rule of thumb, convert (varchar, creat_tms, 102) > '2011'

How to make a view with rounded corners?

Jaap van Hengstum's answer works great however I think it is expensive and if we apply this method on a Button for example, the touch effect is lost since the view is rendered as a bitmap.

For me the best method and the simplest one consists in applying a mask on the view, like that:

@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
    super.onSizeChanged(width, height, oldWidth, oldHeight);

    float cornerRadius = <whatever_you_want>;
    this.path = new Path();
    this.path.addRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, Path.Direction.CW);
}

@Override
protected void dispatchDraw(Canvas canvas) {
    if (this.path != null) {
        canvas.clipPath(this.path);
    }
    super.dispatchDraw(canvas);
}

Display Back Arrow on Toolbar

you can use the tool bar setNavigationIcon method. Android Doc

mToolBar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        handleOnBackPress();
    }
});

getaddrinfo: nodename nor servname provided, or not known

In my config/application.yml I have changed this

redis:
    url: "redis://redis:6379/0"

to this

redis:
    url: "redis://localhost:6379/0"

and it works for me

Adding a leading zero to some values in column in MySQL

A previous answer using LPAD() is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.

UPDATE
    mytable
SET
    mycolumn = CONCAT(
        REPEAT(
            "0",
            8 - LENGTH(mycolumn)
        ),
        mycolumn
    )
WHERE
    LENGTH(mycolumn) < 8;

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

How do I get the path and name of the file that is currently executing?

The __file__ attribute works for both the file containing the main execution code as well as imported modules.

See https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__

are there dictionaries in javascript like python?

There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6). Since then you can use the Map object as Robocat states. Look up the details in MDN. Example:

let map = new Map();
map.set('key', {'value1', 'value2'});
let values = map.get('key');

Without support for ES6 you can try using objects:

var x = new Object();
x["Key"] = "Value";

However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the "object-array" in a for-in-loop.

how to display variable value in alert box?

$(document).ready(function(){

//    alert("test");
$("#name").click(function(){
var content = document.getElementById("ghufran").innerHTML ;
   alert(content);
  });

 //var content = $('#one').text();

})

there u go buddy this code actually works

Auto-size dynamic text to fill fixed size container

You can use FitText.js (github page) to solve this problem. Is really small and efficient compared to TextFill. TextFill uses an expensive while loop and FitText don't.

Also FitText is more flexible (I use it in a proyect with very special requirements and works like a champ!).

HTML:

<div class="container">
  <h1 id="responsive_headline">Your fancy title</h1>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.fittext.js"></script>
<script>
  jQuery("#responsive_headline").fitText();
</script>

You also can set options to it:

<script>
  jQuery("#responsive_headline").fitText(1, { minFontSize: '30px', maxFontSize: '90px'});
</script>

CSS:

#responsive_headline {
   width: 100%;
   display: block;
}

And if you need it, FitText also has a no-jQuery version.

Exit while loop by user hitting ENTER key

if repr(User) == repr(''):
    break

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;
};

Cannot find Dumpbin.exe

By default, it's not in your PATH. You need to use the "Visual Studio 2005 Command Prompt". Alternatively, you can run the vsvars32 batch file, which will set up your environment correctly.

Conveniently, the path to this is stored in the VS80COMNTOOLS environment variable.

Div Scrollbar - Any way to style it?

This one does well its scrolling job. It's very easy to understand, just really few lines of code, well written and totally readable.

How can I generate a 6 digit unique number?

You can use $uniq = round(microtime(true));

it generates 10 digit base on time which is never be duplicated

Can pm2 run an 'npm start' script

I needed to run a specific npm script on my app in pm2 (for each env) In my case, it was when I created a staging/test service

The command that worked for me (the args must be forwarded that way):

pm2 start npm --name "my-app-name" -- run "npm:script"

examples:

pm2 start npm --name "myApp" -- run "start:test"

pm2 start npm --name "myApp" -- run "start:staging"

pm2 start npm --name "myApp" -- run "start:production"

Hope it helped

How can I enable the Windows Server Task Scheduler History recording?

The adjustment in the Task Scheduler app actually just controls the enabled state of a certain event log, so you can equivalently adjust the Task Scheduler "history" mode via the Windows command line:

wevtutil set-log Microsoft-Windows-TaskScheduler/Operational /enabled:true

To check the current state:

wevtutil get-log Microsoft-Windows-TaskScheduler/Operational

For the keystroke-averse, here are the slightly abbreviated versions of the above:

wevtutil sl Microsoft-Windows-TaskScheduler/Operational /e:true
wevtutil gl Microsoft-Windows-TaskScheduler/Operational

Postgresql - unable to drop database because of some auto connections to DB

In my case, I am using AWS Redshift (based on Postgres). And it appears there are no other connections to the DB, but I am getting this same error.

ERROR:  database "XYZ" is being accessed by other users

In my case, it seems the database cluster is still doing some processing on the database, and while there are no other external/user connections, the database is still internally in use. I found this by running the following:

SELECT * FROM stv_sessions;

So my hack was to write a loop in my code, looking for rows with my database name in it. (of course the loop is not infinite, and is a sleepy loop, etc)

SELECT * FROM stv_sessions where db_name = 'XYZ';

If rows found, proceed to delete each PID, one by one.

SELECT pg_terminate_backend(PUT_PID_HERE);

If no rows found, proceed to drop the database

DROP DATABASE XYZ;

Note: In my case, I am writing Java unit/system tests, where this could be considered acceptable. This is not acceptable for production code.


Here is the complete hack, in Java (ignore my test/utility classes).

  int i = 0;
  while (i < 10) {
    try {
      i++;
      logStandardOut("First try to delete session PIDs, before dropping the DB");
      String getSessionPIDs = String.format("SELECT stv_sessions.process, stv_sessions.* FROM stv_sessions where db_name = '%s'", dbNameToReset);
      ResultSet resultSet = databaseConnection.execQuery(getSessionPIDs);
      while (resultSet.next()) {
        int sessionPID = resultSet.getInt(1);
        logStandardOut("killPID: %s", sessionPID);
        String killSessionPID = String.format("select pg_terminate_backend(%s)", sessionPID);
        try {
          databaseConnection.execQuery(killSessionPID);
        } catch (DatabaseException dbEx) {
          //This is most commonly when a session PID is transient, where it ended between my query and kill lines
          logStandardOut("Ignore it, you did your best: %s, %s", dbEx.getMessage(), dbEx.getCause());
        }
      }

      //Drop the DB now
      String dropDbSQL = String.format("DROP DATABASE %s", dbNameToReset);
      logStandardOut(dropDbSQL);
      databaseConnection.execStatement(dropDbSQL);
      break;
    } catch (MissingDatabaseException ex) {
      //ignore, if the DB was not there (to be dropped)
      logStandardOut(ex.getMessage());
      break;
    } catch (Exception ex) {
      logStandardOut("Something went wrong, sleeping for a bit: %s, %s", ex.getMessage(), ex.getCause());
      sleepMilliSec(1000);
    }
  }

Convert datatable to JSON in C#

Try this custom function.

    public static string DataTableToJsonObj(DataTable dt)
    {
        DataSet ds = new DataSet();
        ds.Merge(dt);
        StringBuilder jsonString = new StringBuilder();

        if (ds.Tables[0].Rows.Count > 0)
        {
            jsonString.Append("[");
            for (int rows = 0; rows < ds.Tables[0].Rows.Count; rows++)
            {
                jsonString.Append("{");
                for (int cols = 0; cols < ds.Tables[0].Columns.Count; cols++)
                {
                    jsonString.Append(@"""" + ds.Tables[0].Columns[cols].ColumnName + @""":");

                    /* 
                    //IF NOT LAST PROPERTY

                    if (cols < ds.Tables[0].Columns.Count - 1)
                    {
                        GenerateJsonProperty(ds, rows, cols, jsonString);
                    }

                    //IF LAST PROPERTY

                    else if (cols == ds.Tables[0].Columns.Count - 1)
                    {
                        GenerateJsonProperty(ds, rows, cols, jsonString, true);
                    }
                    */

                    var b = (cols < ds.Tables[0].Columns.Count - 1)
                        ? GenerateJsonProperty(ds, rows, cols, jsonString)
                        : (cols != ds.Tables[0].Columns.Count - 1)
                          || GenerateJsonProperty(ds, rows, cols, jsonString, true);
                }
                jsonString.Append(rows == ds.Tables[0].Rows.Count - 1 ? "}" : "},");
            }
            jsonString.Append("]");
            return jsonString.ToString();
        }
        return null;
    }

    private static bool GenerateJsonProperty(DataSet ds, int rows, int cols, StringBuilder jsonString, bool isLast = false)
    {

        // IF LAST PROPERTY THEN REMOVE 'COMMA'  IF NOT LAST PROPERTY THEN ADD 'COMMA'
        string addComma = isLast ? "" : ",";

        if (ds.Tables[0].Rows[rows][cols] == DBNull.Value)
        {
            jsonString.Append(" null " + addComma);
        }
        else if (ds.Tables[0].Columns[cols].DataType == typeof(DateTime))
        {
            jsonString.Append(@"""" + (((DateTime)ds.Tables[0].Rows[rows][cols]).ToString("yyyy-MM-dd HH':'mm':'ss")) + @"""" + addComma);
        }
        else if (ds.Tables[0].Columns[cols].DataType == typeof(string))
        {
            jsonString.Append(@"""" + (ds.Tables[0].Rows[rows][cols]) + @"""" + addComma);
        }
        else if (ds.Tables[0].Columns[cols].DataType == typeof(bool))
        {
            jsonString.Append(Convert.ToBoolean(ds.Tables[0].Rows[rows][cols]) ? "true" : "fasle");
        }
        else
        {
            jsonString.Append(ds.Tables[0].Rows[rows][cols] + addComma);
        }

        return true;
    }

Can we use join for two different database tables?

You could use Synonyms part in the database.

enter image description here

Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply. enter image description here

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I implemented Joseph Johnson solution and it worked well, I noticed after using this solution sometimes the drawer on the application will not close properly. I added a functionality to remove the listener removeOnGlobalLayoutListener when the user closes the fragment where are edittexts located.

    //when the application uses full screen theme and the keyboard is shown the content not scrollable! 
//with this util it will be scrollable once again
//http://stackoverflow.com/questions/7417123/android-how-to-adjust-layout-in-full-screen-mode-when-softkeyboard-is-visible
public class AndroidBug5497Workaround {


    private static AndroidBug5497Workaround mInstance = null;
    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;
    private ViewTreeObserver.OnGlobalLayoutListener _globalListener;

    // For more information, see https://code.google.com/p/android/issues/detail?id=5497
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.

    public static AndroidBug5497Workaround getInstance (Activity activity) {
        if(mInstance==null)
        {
            synchronized (AndroidBug5497Workaround.class)
            {
                mInstance = new AndroidBug5497Workaround(activity);
            }
        }
        return mInstance;
    }

    private AndroidBug5497Workaround(Activity activity) {
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();

        _globalListener = new ViewTreeObserver.OnGlobalLayoutListener()
        {

            @Override
            public void onGlobalLayout()
            {
                 possiblyResizeChildOfContent();
            }
        };
    }

    public void setListener()
    {
         mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(_globalListener);
    }

    public void removeListener()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mChildOfContent.getViewTreeObserver().removeOnGlobalLayoutListener(_globalListener);
        } else {
            mChildOfContent.getViewTreeObserver().removeGlobalOnLayoutListener(_globalListener);
        }
    }

    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            if (heightDifference > (usableHeightSansKeyboard/4)) {
                // keyboard probably just became visible
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
            } else {
                // keyboard probably just became hidden
                frameLayoutParams.height = usableHeightSansKeyboard;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    } 
}

uses the class where is my edittexts located

@Override
public void onStart()
{
    super.onStart();
    AndroidBug5497Workaround.getInstance(getActivity()).setListener();
}

@Override
public void onStop()
{
    super.onStop();
    AndroidBug5497Workaround.getInstance(getActivity()).removeListener();
}

How to always show scrollbar

Setting the android:scrollbarFadeDuration="0" will do the trick.

JavaScript Chart Library

It maybe not exactly what you are looking for, but
Google's Chart API is pretty cool and easy to use.

Find the files that have been changed in last 24 hours

This command worked for me

find . -mtime -1 -print

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

Giving admin rights or full control to my database install location solved my problem

Angular 2: How to access an HTTP response body?

Both Request and Response extend Body. To get the contents, use the text() method.

this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10')
    .subscribe(response => console.log(response.text()))

That API was deprecated in Angular 5. The new HttpResponse<T> class instead has a .body() method. With a {responseType: 'text'} that should return a String.

iReport not starting using JRE 8

It works only with JRE 1.7 just download it and extract to your prefered location

and use the following command to open the iReport

ireport --jdkhome Path To JDK Home

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

In IntelliJ IDEA this is an open bug: https://youtrack.jetbrains.com/issue/IDEA-252823

As a workaround, you can change the build tools version as other people advise.

My project was failing with this dependency:

com.android.tools.build:gradle:7.0.0-alpha03

Now it's working with this:

com.android.tools.build:gradle:4.0.2

As a side note, you should change that dependency in build.gradle in some projects or in dependencies.kt in newer projects.

That was the most updated version that worked.

jQuery - determine if input element is textbox or select list

alternatively you can retrieve DOM properties with .prop

here is sample code for select box

if( ctrl.prop('type') == 'select-one' ) { // for single select }

if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }

for textbox

  if( ctrl.prop('type') == 'text' ) { // for text box }

Visual Studio Expand/Collapse keyboard shortcuts

You can use Ctrl + M and Ctrl + P

It's called Edit.StopOutlining

How can I add an item to a SelectList in ASP.net MVC

private SelectList AddFirstItem(SelectList list)
        {
            List<SelectListItem> _list = list.ToList();
            _list.Insert(0, new SelectListItem() { Value = "-1", Text = "This Is First Item" });
            return new SelectList((IEnumerable<SelectListItem>)_list, "Value", "Text");
        }

This Should do what you need ,just send your selectlist and it will return a select list with an item in index 0

You can custome the text,value or even the index of the item you need to insert

How do you clear a stringstream variable?

my 2 cents:

this seemed to work for me in xcode and dev-c++, I had a program in the form of a menu that if executed iteratively as per the request of a user will fill up a stringstream variable which would work ok the first time the code would run but would not clear the stringstream the next time the user will run the same code. but the two lines of code below finally cleared up the stringstream variable everytime before filling up the string variable. (2 hours of trial and error and google searches), btw, using each line on their own would not do the trick.

//clear the stringstream variable

sstm.str("");
sstm.clear();

//fill up the streamstream variable
sstm << "crap" << "morecrap";

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

How to check a channel is closed or not without reading it?

In a hacky way it can be done for channels which one attempts to write to by recovering the raised panic. But you cannot check if a read channel is closed without reading from it.

Either you will

  • eventually read the "true" value from it (v <- c)
  • read the "true" value and 'not closed' indicator (v, ok <- c)
  • read a zero value and the 'closed' indicator (v, ok <- c)
  • will block in the channel read forever (v <- c)

Only the last one technically doesn't read from the channel, but that's of little use.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

when reimporting your keys from the old keyring, you need to specify the command:

gpg --allow-secret-key-import --import <keyring>

otherwise it will only import the public keys, not the private keys.

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

Yes strings must be quoted and in some cases like in applescript, quotes must be escaped

do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

How to capitalize the first letter of a String in Java?

Just reworked Jorgesys code and added few checks because of few cases related to String length. Don't do for null reference check in my case.

 public static String capitalizeFirstLetter(@NonNull String customText){
        int count = customText.length();
        if (count == 0) {
            return customText;
        }
        if (count == 1) {
            return customText.toUpperCase();
        }
        return customText.substring(0, 1).toUpperCase() + customText.substring(1).toLowerCase();
    }

How to normalize a signal to zero mean and unit variance?

if your signal is in the matrix X, you make it zero-mean by removing the average:

X=X-mean(X(:));

and unit variance by dividing by the standard deviation:

X=X/std(X(:));

Best way to do multi-row insert in Oracle?

Cursors may also be used, although it is inefficient. The following stackoverflow post discusses the usage of cursors :

INSERT and UPDATE a record using cursors in oracle

Force git stash to overwrite added files

git stash show -p | git apply

and then git stash drop if you want to drop the stashed items.

How to set up a PostgreSQL database in Django

Step by step that I use:

 - sudo apt-get install python-dev
 - sudo apt-get install postgresql-server-dev-9.1
 - sudo apt-get install python-psycopg2 - Or sudo pip install psycopg2

You may want to install a graphic tool to manage your databases, for that you can do:

sudo apt-get install postgresql pgadmin3 

After, you must change Postgre user password, then do:

 - sudo su
 - su postgres -c psql postgres
 - ALTER USER postgres WITH PASSWORD 'YourPassWordHere';
 - \q

On your settings.py file you do:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': '',
        'PORT': '',
    }
}

Extra:

If you want to create the db using the command line you can just do:

- sudo su
- su postgres -c psql postgres
- CREATE DATABASE dbname;
- CREATE USER djangouser WITH ENCRYPTED PASSWORD 'myPasswordHere';
- GRANT ALL PRIVILEGES ON DATABASE dbname TO djangouser;

On your settings.py file you do:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'djangouser',
        'PASSWORD': 'myPasswordHere',
        'HOST': '',
        'PORT': '',
    }
}

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

justify-content property isn't working

Screenshot

Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.

If so, please update bootstrap, worked for me.

CLEAR SCREEN - Oracle SQL Developer shortcut?

In the Oracle SQL-plus:

shift+del

CSS property to pad text inside of div

Just use div { padding: 20px; } and substract 40px from your original div width.

Like Philip Wills pointed out, you can also use box-sizing instead of substracting 40px:

div {
    padding: 20px;
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

The -moz-box-sizing is for Firefox.

"Invalid signature file" when attempting to run a .jar

If you are looking for a Fat JAR solution without unpacking or tampering with the original libraries but with a special JAR classloader, take a look at my project here.

Disclaimer: I did not write the code, just package it and publish it on Maven Central and describe in my read-me how to use it.

I personally use it for creating runnable uber JARs containing BouncyCastle dependencies. Maybe it is useful for you, too.

Powershell command to hide user from exchange address lists

"WARNING: The command completed successfully but no settings of '[user id here]' have been modified."

This warning means the setting was already set like what you want it to be. So it didn't change anything for that object.

Linq to SQL .Sum() without group ... into

Try this:

var itemsInCart = from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select o.WishListItem.Price;

return Convert.ToDecimal(itemsInCart.Sum());

I think it's more simple!

WaitAll vs WhenAll

Task.WaitAll blocks the current thread until everything has completed.

Task.WhenAll returns a task which represents the action of waiting until everything has completed.

That means that from an async method, you can use:

await Task.WhenAll(tasks);

... which means your method will continue when everything's completed, but you won't tie up a thread to just hang around until that time.

JQuery .each() backwards

You can also try

var arr = [].reverse.call($('li'))
arr.each(function(){ ... })

How to check if a file exists in the Documents directory in Swift?

Swift 4.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    if let pathComponent = url.appendingPathComponent("nameOfFileHere") {
        let filePath = pathComponent.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) {
            print("FILE AVAILABLE")
        } else {
            print("FILE NOT AVAILABLE")
        }
    } else {
        print("FILE PATH NOT AVAILABLE")
    }

Swift 3.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = URL(fileURLWithPath: path)

    let filePath = url.appendingPathComponent("nameOfFileHere").path
    let fileManager = FileManager.default
    if fileManager.fileExists(atPath: filePath) {
        print("FILE AVAILABLE")
    } else {
        print("FILE NOT AVAILABLE")
    }

Swift 2.x version, need to use URLByAppendingPathComponent

    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    let filePath = url.URLByAppendingPathComponent("nameOfFileHere").path!
    let fileManager = NSFileManager.defaultManager()
    if fileManager.fileExistsAtPath(filePath) {
        print("FILE AVAILABLE")
    } else {
        print("FILE NOT AVAILABLE")
    }

What's the default password of mariadb on fedora?

Lucups, Floris is right, but you comment that this didn't solve your problem. I ran into the same symptoms, where mysql (mariadb) will not accept the blank password it should accept, and '/var/lib/mysql' does not exist.

I found that this Moonpoint.com page was on-point. Perhaps, like me, you tried to start the mysqld service instead of the mariadb service. Try:

systemctl start mariadb.service
systemctl status mysqld service

Followed by the usual:

mysql_secure_installation

How do I run a program with commandline arguments using GDB within a Bash script?

If the --args parameter is not working on your machine (i.e. on Solaris 8), you may start gdb like

gdb -ex "set args <arg 1> <arg 2> ... <arg n>"

And you can combine this with inputting a file to stdin and "running immediatelly":

gdb -ex "set args <arg 1> <arg 2> ... <arg n> < <input file>" -ex "r"

How to display images from a folder using php - PHP

You have two ways to do that:

METHOD 1. The secure way.

Put the images on /www/htdocs/

<?php
    $www_root = 'http://localhost/images';
    $dir = '/var/www/images';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

METHOD 2. Unsecure but more flexible.

Put the images on any directory (apache must have permission to read the file).

<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

And create another script to read the image file.

<?php
    $filename = base64_decode($_GET['file']);
    // Check the folder location to avoid exploit
    if (dirname($filename) == '/home/user/Pictures')
        echo file_get_contents($filename);
?>

Getting the ID of the element that fired an event

In case of Angular 7.x you can get the native element and its id or properties.

myClickHandler($event) {
    this.selectedElement = <Element>$event.target;
    console.log(this.selectedElement.id)
    this.selectedElement.classList.remove('some-class');
}

html:

<div class="list-item" (click)="myClickHandler($event)">...</div>

How to know function return type and argument types?

This is how dynamic languages work. It is not always a good thing though, especially if the documentation is poor - anyone tried to use a poorly documented python framework? Sometimes you have to revert to reading the source.

Here are some strategies to avoid problems with duck typing:

  • create a language for your problem domain
  • this will help you to name stuff properly
  • use types to represent concepts in your domain language
  • name function parameters using the domain language vocabulary

Also, one of the most important points:

  • keep data as local as possible!

There should only be a few well-defined and documented types being passed around. Anything else should be obvious by looking at the code: Don't have weird parameter types coming from far away that you can't figure out by looking in the vicinity of the code...

Related, (and also related to docstrings), there is a technique in python called doctests. Use that to document how your methods are expected to be used - and have nice unit test coverage at the same time!

How to get the last element of an array in Ruby?

Use -1 index (negative indices count backward from the end of the array):

a[-1] # => 5
b[-1] # => 6

or Array#last method:

a.last # => 5
b.last # => 6

How to save a bitmap on internal storage

To Save your bitmap in sdcard use the following code

Store Image

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

To Get the Path for Image Storage

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.

public onClick(View v){

switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
} 
}

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

Below are the differences between CrudRepository and JpaRepository as:

CrudRepository

  1. CrudRepository is a base interface and extends the Repository interface.
  2. CrudRepository mainly provides CRUD (Create, Read, Update, Delete) operations.
  3. Return type of saveAll() method is Iterable.
  4. Use Case - To perform CRUD operations, define repository extending CrudRepository.

JpaRepository

  1. JpaRepository extends PagingAndSortingRepository that extends CrudRepository.
  2. JpaRepository provides CRUD and pagination operations, along with additional methods like flush(), saveAndFlush(), and deleteInBatch(), etc.
  3. Return type of saveAll() method is a List.
  4. Use Case - To perform CRUD as well as batch operations, define repository extends JpaRepository.

Validate select box

Perhaps there is a shorter way but this works for me.

<script language='JavaScript' type='text/javascript'>
    function validateThisFrom(thisForm) {
        if (thisForm.FIELDNAME.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME.focus();
            return false;
        }
        if (thisForm.FIELDNAME2.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME2.focus();
            return false;
        }
    }
</script>
<form onSubmit="return validateThisFrom (this);">
    <select name="FIELDNAME" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
    <select name="FIELDNAME2" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
</form>

Can you append strings to variables in PHP?

PHP syntax is little different in case of concatenation from JavaScript. Instead of (+) plus a (.) period is used for string concatenation.

<?php

$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
    $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;

?>

What is trunk, branch and tag in Subversion?

The answer by David Schmitt sums things up very well, but I think it is important to note that, to SVN, the terms 'branch', 'tag', and 'trunk' don't mean anything. These terms are purely semantic and only affect the way we, as users of the system, treat those directories. One could easily name them 'main', 'test', and 'releases.'; As long as everyone using the system understands how to use each section properly, it really doesn't matter what they're called.

jQuery DIV click, with anchors

$("div.clickable").click( function(event) { window.location = $(this).attr("url"); event.preventDefault(); });

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));  //copy
2.List<Integer> list2 = Arrays.asList(ia);

In line 2, Arrays.asList(ia) returns a List reference of inner class object defined within Arrays, which is also called ArrayList but is private and only extends AbstractList. This means what returned from Arrays.asList(ia) is a class object different from what you get from new ArrayList<Integer>.

You cannot use some operations to line 2 because the inner private class within Arrays does not provide those methods.

Take a look at this link and see what you can do with the private inner class: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.ArrayList

Line 1 creates a new ArrayList object copying elements from what you get from line 2. So you can do whatever you want since java.util.ArrayList provides all those methods.

How to parse a text file with C#

Try regular expressions. You can find a certain pattern in your text and replace it with something that you want. I can't give you the exact code right now but you can test out your expressions using this.

http://www.radsoftware.com.au/regexdesigner/

How to trigger Jenkins builds remotely and to pass parameters

When we have to send multiple trigger parameters to jenkins job, the following commands works.

curl -X POST -i -u "auto_user":"xxxauthentication_tokenxxx" "JENKINS_URL/view/tests/job/helloworld/buildWithParameters?param1=162&param2=store"

Input Type image submit form value?

To submit a form you could use:

<input type="submit">

or

<input type="button"> + Javascript 

I never heard of such a crazy guy to try to send a form using a image or a checkbox as you want :))

Are members of a C++ struct initialized to 0 by default?

I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.

how to check if string contains '+' character

You need this instead:

if(s.contains("+"))

contains() method of String class does not take regular expression as a parameter, it takes normal text.


EDIT:

String s = "ddjdjdj+kfkfkf";

if(s.contains("+"))
{
    String parts[] = s.split("\\+");
    System.out.print(parts[0]);
}

OUTPUT:

ddjdjdj

How do I get the "id" after INSERT into MySQL database with Python?

SELECT @@IDENTITY AS 'Identity';

or

SELECT last_insert_id();

Adding value labels on a matplotlib bar chart

Based on a feature mentioned in this answer to another question I have found a very generally applicable solution for placing labels on a bar chart.

Other solutions unfortunately do not work in many cases, because the spacing between label and bar is either given in absolute units of the bars or is scaled by the height of the bar. The former only works for a narrow range of values and the latter gives inconsistent spacing within one plot. Neither works well with logarithmic axes.

The solution I propose works independent of scale (i.e. for small and large numbers) and even correctly places labels for negative values and with logarithmic scales because it uses the visual unit points for offsets.

I have added a negative number to showcase the correct placement of labels in such a case.

The value of the height of each bar is used as a label for it. Other labels can easily be used with Simon's for rect, label in zip(rects, labels) snippet.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]

# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)


def add_value_labels(ax, spacing=5):
    """Add labels to the end of each bar in a bar chart.

    Arguments:
        ax (matplotlib.axes.Axes): The matplotlib object containing the axes
            of the plot to annotate.
        spacing (int): The distance between the labels and the bars.
    """

    # For each bar: Place a label
    for rect in ax.patches:
        # Get X and Y placement of label from rect.
        y_value = rect.get_height()
        x_value = rect.get_x() + rect.get_width() / 2

        # Number of points between bar and label. Change to your liking.
        space = spacing
        # Vertical alignment for positive values
        va = 'bottom'

        # If value of bar is negative: Place label below bar
        if y_value < 0:
            # Invert space to place label below
            space *= -1
            # Vertically align label at top
            va = 'top'

        # Use Y value as label and format number with one decimal place
        label = "{:.1f}".format(y_value)

        # Create annotation
        ax.annotate(
            label,                      # Use `label` as label
            (x_value, y_value),         # Place label at end of the bar
            xytext=(0, space),          # Vertically shift label by `space`
            textcoords="offset points", # Interpret `xytext` as offset in points
            ha='center',                # Horizontally center label
            va=va)                      # Vertically align label differently for
                                        # positive and negative values.


# Call the function above. All the magic happens there.
add_value_labels(ax)

plt.savefig("image.png")

Edit: I have extracted the relevant functionality in a function, as suggested by barnhillec.

This produces the following output:

Bar chart with automatically placed labels on each bar

And with logarithmic scale (and some adjustment to the input data to showcase logarithmic scaling), this is the result:

Bar chart with logarithmic scale with automatically placed labels on each bar

Are querystring parameters secure in HTTPS (HTTP + SSL)?

I disagree with the advice given here - even the reference for the accepted answer concludes:

You can of course use query string parameters with HTTPS, but don’t use them for anything that could present a security problem. For example, you could safely use them to identity part numbers or types of display like ‘accountview’ or ‘printpage’, but don’t use them for passwords, credit card numbers or other pieces of information that should not be publicly available.

So, no they aren't really safe...!

What is a vertical tab?

In the medical industry, VT is used as the start of frame character in the MLLP/LLP/HLLP protocols that are used to frame HL-7 data, which has been a standard for medical exchange since the late 80s and is still in wide use.

It is more efficient to use if-return-return or if-else-return?

From Chromium's style guide:

Don't use else after return:

# Bad
if (foo)
  return 1
else
  return 2

# Good
if (foo)
  return 1
return 2

return 1 if foo else 2

How to correctly close a feature branch in Mercurial?

EDIT ouch, too late... I know read your comment stating that you want to keep the feature-x changeset around, so the cloning approach here doesn't work.

I'll still let the answer here for it may help others.

If you want to completely get rid of "feature X", because, for example, it didn't work, you can clone. This is one of the method explained in the article and it does work, and it talks specifically about heads.

As far as I understand you have this and want to get rid of the "feature-x" head once and for all:

@    changeset:   7:00a7f69c8335
|\   tag:         tip
| |  parent:      4:31b6f976956b
| |  parent:      2:0a834fa43688
| |  summary:     merge
| |
| | o  changeset:   5:013a3e954cfd
| |/   summary:     Closed branch feature-x
| |
| o  changeset:   4:31b6f976956b
| |  summary:     Changeset2
| |
| o  changeset:   3:5cb34be9e777
| |  parent:      1:1cc843e7f4b5
| |  summary:     Changeset 1
| |
o |  changeset:   2:0a834fa43688
|/   summary:     Changeset C
|
o  changeset:   1:1cc843e7f4b5
|  summary:     Changeset B
|
o  changeset:   0:a9afb25eaede
   summary:     Changeset A

So you do this:

hg clone . ../cleanedrepo --rev 7

And you'll have the following, and you'll see that feature-x is indeed gone:

@    changeset:   5:00a7f69c8335
|\   tag:         tip
| |  parent:      4:31b6f976956b
| |  parent:      2:0a834fa43688
| |  summary:     merge
| |
| o  changeset:   4:31b6f976956b
| |  summary:     Changeset2
| |
| o  changeset:   3:5cb34be9e777
| |  parent:      1:1cc843e7f4b5
| |  summary:     Changeset 1
| |
o |  changeset:   2:0a834fa43688
|/   summary:     Changeset C
|
o  changeset:   1:1cc843e7f4b5
|  summary:     Changeset B
|
o  changeset:   0:a9afb25eaede
   summary:     Changeset A

I may have misunderstood what you wanted but please don't mod down, I took time reproducing your use case : )

How to convert ActiveRecord results into an array of hashes

May be?

result.map(&:attributes)

If you need symbols keys:

result.map { |r| r.attributes.symbolize_keys }

Calculate difference between two datetimes in MySQL

USE TIMESTAMPDIFF MySQL function. For example, you can use:

SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')

In your case, the third parameter of TIMSTAMPDIFF function would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.

When to use RDLC over RDL reports?

From my experience there are few things to think about both things:

I. RDL reports are HOSTED reports generally. This means you need to implement SSRS Server. They are a built in extension of Visual Studio from SQL Server for the reporting language. When you install SSRS you should have an add on called 'Business Intelligence Development Studio' which is much easier to work with the reports than without it.

R eport

D efinition

L angauge

Benefits of RDL reports:

  1. You can host the reports in an environment that has services running for you on them.
  2. You can configure security on an item or inheriting level to handle security as a standalone concept
  3. You can configure the service to send out emails(provided you have an SMTP server you have access to) and save files on schedules
  4. You have a database generally called 'ReportServer' you can query for info on the reports once published.
  5. You can access these reports still through 'ReportViewer' in a client application written in ASP.NET, WPF (with a winform control bleh!), or Winforms in .NET using 'ProcessingMode.Remote'.
  6. You can set parameters a user can see and use to gain more flexibility.
  7. You can configure parts of a report to be used for connection strings as 'Data Sources' as well as a sql query, xml, or other datasets as a 'Dataset'. These parts and others can be stored and configured to cache data on a regular basis.
  8. You can write .NET proxy classes of the services http:// /ReportServer/ReportingService2010 or /ReportExecution2005. You can then make up your OWN methods in .NET for emailing, saving, or manipulating SSRS data from the service directly of a Server hosting SSRS reports in code. Programmatically Export SSRS report from sharepoint using ReportService2010.asmx

Downsides:

  1. SSRS is kind of wonkey compared to other things on getting it up fast. Most people get confused by the security policy and designing reports as an 'add on' to VS. SQL 2005 = VS BIDS 2005 , SQL 2008 = VS BIDS 2008, SQL 2012 = VS BIDS 2010(LOL).
  2. Continuing on 1 the policy for security settings IMHO are idiotically overcomplex. There is server security, database security and roles, two security settings on the page hosted for the service. Most people only set up an admin than can't get in and wonder why other users cannot. Most common complaint or question on SSRS is related to getting in generally from my experience.
  3. You can use 'expressions' that will supposeduly 'enhance' your report. Often times you do more than a few and your report goes to a crawl in performance.
  4. You have a set amount of things you can do and export to. SSRS has no hover over reporting I know of without a javascript hack.
  5. Speed and performance can take a hit as the stupid SSRS config recycles the system and a first report can take a while at times just loading the site. You can get around this by altering it but I have found making a keep alive service for it works better.

II. RDLC reports are CLIENT CONTAINED reports that are NOT HOSTED ANYWHERE. The extra c in the name means 'Client'. Generally this is an extension of the RDL language meant for use only in Visual Studio Client Applications. It exists in Visual Studio when you add a 'reporting' item.

Benefits of RDLC reports:

  1. You can hookup a wcf service much much much more easier to the dataset.
  2. You have more control over the dataset and can use POCO classes filled with Entity framework objects or ADO.NET directly as well as tables themselves. You can monkey with the data for optimization it before binding it to the report.
  3. You can customize the look more with add on's directly in code behind.

Downsides:

  1. You need to handle parameters on your own and while you can implement wrapper methods to help the legwork is a little more than expected and unfortunate.
  2. The user cannot SEE the parameters in a 'ReportViewer' control unless it is in remote mode and accessing an RLD report. Thus you need to make textboxes, dropdowns, radio buttons on your own outside the control to pass to it. Some people like this added control, I do not personally.
  3. Anything you want to do with servicing the reports for distribution you need to build yourself. Emailing, subscriptions, saving. Sorry you need to build that in .NET or else implement a proxy that already does that from above you could just be getting using hosted reports.

Honestly I like both for different purposes. If I want something to go out to analysts that they use all the time and tweak for graphs, charts, drill downs and exports to Excel I use RDL and just have SSRS's site do all the legwork of handling the email distributions. If I want an application that has a report section and I know that application is it's own module with rules and governance I use an RDLC and having the parameters be smaller and be driven by the decisions the user made before getting to the report part of what client they are on and site and then they usually just choose a time frame or type and nothing more. So generally a complex report I would use RDL and for something simple I would use RDLC IMHO.

I hope that helps.

what's the default value of char?

Note that there is a distinct difference between null and zero. In http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html (referenced above), the statement is made :-

There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.

That is why the following statements will give you an error and not the other :-

char a = null; //Type mismatch: cannot convert from null to char.

char b = 0; //Valid syntax.

Twitter Bootstrap onclick event on buttons-radio

I searched so many pages: I found a beautiful solution. Check it out:

git link

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

    <script>
        $(function() {
            $("#my_launch_today_chk").change(function() {
                var chk = $(this).prop('checked');
                if(chk == true){
                    console.log("On");
                }else{
                    console.log("OFF");
                }
            });
        });
    </script>
</head>
<body >

<input type="checkbox" id="my_launch_today_chk" checked data-on="Launch" data-off="OFF" data-toggle="toggle" data-size="small">
</body>
</html>

Operator overloading ==, !=, Equals

In fact, this is a "how to" subject. So, here is the reference implementation:

    public class BOX
    {
        double height, length, breadth;

        public static bool operator == (BOX b1, BOX b2)
        {
            if ((object)b1 == null)
                return (object)b2 == null;

            return b1.Equals(b2);
        }

        public static bool operator != (BOX b1, BOX b2)
        {
            return !(b1 == b2);
        }

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
                return false;

            var b2 = (BOX)obj;
            return (length == b2.length && breadth == b2.breadth && height == b2.height);
        }

        public override int GetHashCode()
        {
            return height.GetHashCode() ^ length.GetHashCode() ^ breadth.GetHashCode();
        }
    }

REF: https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx#Examples

UPDATE: the cast to (object) in the operator == implementation is important, otherwise, it would re-execute the operator == overload, leading to a stackoverflow. Credits to @grek40.

This (object) cast trick is from Microsoft String == implementaiton. SRC: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs#L643

How do I create directory if it doesn't exist to create a file?

You can use File.Exists to check if the file exists and create it using File.Create if required. Make sure you check if you have access to create files at that location.

Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.

Additional information for basic file I/O concepts.

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

The easiest way I've found is delete Android Studio from the applications folder, then download & install it again.

Perl regular expression (using a variable as a search string with Perl operator characters included)

You can use quotemeta (\Q \E) if your Perl is version 5.16 or later, but if below you can simply avoid using a regular expression at all.

For example, by using the index command:

if (index($text_to_search, $search_string) > -1) {
    print "wee";
}

rotating axis labels in R

You need to use theme() function as follows rotating x-axis labels by 90 degrees:

ggplot(...)+...+ theme(axis.text.x = element_text(angle=90, hjust=1))

How can I populate a select dropdown list from a JSON feed with AngularJS?

The proper way to do it is using the ng-options directive. The HTML would look like this.

<select ng-model="selectedTestAccount" 
        ng-options="item.Id as item.Name for item in testAccounts">
    <option value="">Select Account</option>
</select>

JavaScript:

angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.testAccounts = result;
    });
});

You'll also need to ensure angular is run on your html and that your module is loaded.

<html ng-app="test">
    <body ng-controller="DemoCtrl">
    ....
    </body>
</html>

How to add local .jar file dependency to build.gradle file?

A solution for those using Kotlin DSL

The solutions added so far are great for the OP, but can't be used with Kotlin DSL without first translating them. Here's an example of how I added a local .JAR to my build using Kotlin DSL:

dependencies {
    compile(files("/path/to/file.jar"))
    testCompile(files("/path/to/file.jar"))
    testCompile("junit", "junit", "4.12")
}

Remember that if you're using Windows, your backslashes will have to be escaped:

...
compile(files("C:\\path\\to\\file.jar"))
...

And also remember that quotation marks have to be double quotes, not single quotes.


Edit for 2020:

Gradle updates have deprecated compile and testCompile in favor of implementation and testImplementation. So the above dependency block would look like this for current Gradle versions:

dependencies {
    implementation(files("/path/to/file.jar"))
    testImplementation(files("/path/to/file.jar"))
    testImplementation("junit", "junit", "4.12")
}

How to remove last n characters from a string in Bash?

To remove four characters from the end of the string use ${var%????}.

To remove everything after the final . use ${var%.*}.

Removing a non empty directory programmatically in C or C++

You can use opendir and readdir to read directory entries and unlink to delete them.

Detect whether current Windows version is 32 bit or 64 bit

From a batch script:

IF PROCESSOR_ARCHITECTURE == x86 AND
   PROCESSOR_ARCHITEW6432 NOT DEFINED THEN
   // OS is 32bit
ELSE
   // OS is 64bit
END IF

Using Windows API:

if (GetSystemWow64Directory(Directory, MaxDirectory) > 0) 
   // OS is 64bit
else
   // OS is 32bit

Sources:

  1. HOWTO: Detect Process Bitness
  2. GetSystemWow64Directory function

What are the differences between WCF and ASMX web services?

This is a very old question, but I do not feel that the benefits of ASMX have been fairly portrayed. While not terribly flexible, ASMX web services are very simple to use and understand. While WCF is more flexible, it is also more complex to stand up and configure.

ASMX web services are ready to stand up and add as a webservice reference as soon as you add the file. (assuming your project builds)

For the simple development workflow of create webservice -> run webservice -> add webservice reference, an ASMX webservice has very little that can go wrong, not much that you can misconfigure, and that is it's strength.

In response to those that assert that WCF replaces ASMX, I would reply that WCF would need to add a streamlined K.I.S.S. configuration mode in order to completely replace ASMX.

Example web.config for an ASMX webservice:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings />
  <system.web>
    <compilation targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
</configuration>

Install GD library and freetype on Linux

Installing freetype:

sudo apt update && sudo apt install freetype2-demos

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

Python requests - print entire http request (raw)?

import requests

response = requests.post('http://httpbin.org/post', data={'key1':'value1'})
print(response.request.url)
print(response.request.body)
print(response.request.headers)

Response objects have a .request property which is the original PreparedRequest object that was sent.

Measuring execution time of a function in C++

It is a very easy-to-use method in C++11. You have to use std::chrono::high_resolution_clock from <chrono> header.

Use it like so:

#include <iostream>
#include <chrono>

void function()
{
    long long number = 0;

    for( long long i = 0; i != 2000000; ++i )
    {
       number += 5;
    }
}

int main()
{
    auto t1 = std::chrono::high_resolution_clock::now();
    function();
    auto t2 = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << duration;
    return 0;
}

This will measure the duration of the function.

NOTE: You will not always get the same timing for a function. This is because the CPU of your machine can be less or more used by other processes running on your computer, just as your mind can be more or less concentrated when you solve a math exercise. In the human mind, we can remember the solution of a math problem, but for a computer the same process will always be something new; thus, as I said, you will not always get the same result!

Finding second occurrence of a substring in a string in Java

You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy

public static ArrayList<Integer> occurrencesPos(String str, String substr) {
    final boolean ignoreCase = true;
    int substrLength = substr.length();
    int strLength = str.length();

    ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();

    for(int i = 0; i < strLength - substrLength + 1; i++) {
        if(str.regionMatches(ignoreCase, i, substr, 0, substrLength))  {
            occurrenceArr.add(i);
        }
    }
    return occurrenceArr;
}

How to start working with GTest and CMake

Having done some more digging, I think my issue is something to do with the type of library I am building gtest into. When building gtest with CMake, if BUILD_SHARED_LIBS is un-checked, and I link my program against these .lib files I get the errors mentioned above. However, if BUILD_SHARED_LIBS is checked then I produce a set of .lib and .dll files. When now linking against these .lib files the program compiles, but when run complains that it can't find gtest.dll.

That is because you have to add -DGTEST_LINKED_AS_SHARED_LIBRARY=1 to compiler definitions in your project if you want to use gtest as a shared library.

You could also use the static libraries, provided you compiled it with gtest_force_shared_crt option on to eliminate errors you have seen.

I like the library but adding it to the project is a real pain. And you have no chance to do it right unless you dig (and hack) into the gtest cmake files. Shame. In particular I do not like the idea of adding gtest as a source. :)

Bootstrap dropdown not working

Working demo: http://codebins.com/bin/4ldqp73

try this

<ul class='nav'>
  <li class='active'>Home</li>
  <li>
    <div class="dropdown">
      <a class="dropdown-toggle" data-toggle="dropdown" href="#">Personal asset loans</a>
      <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">            
        <li><a href="#">asds</a></li>
        <li class="divider"></li>
      </ul>
    </div>   
    </li>
    <li>Payday loans</li>
  <li>About</li>
  <li>Contact</li>
</ul>

How to update primary key

First, we choose stable (not static) data columns to form a Primary Key, precisely because updating Keys in a Relational database (in which the references are by Key) is something we wish to avoid.

  1. For this issue, it doesn't matter if the Key is a Relational Key ("made up from the data"), and thus has Relational Integrity, Power, and Speed, or if the "key" is a Record ID, with none of that Relational Integrity, Power, and Speed. The effect is the same.

  2. I state this because there are many posts by the clueless ones, who suggest that this is the exact reason that Record IDs are somehow better than Relational Keys.

  3. The point is, the Key or Record ID is migrated to wherever a reference is required.

Second, if you have to change the value of the Key or Record ID, well, you have to change it. Here is the OLTP Standard-compliant method. Note that the high-end vendors do not allow "cascade update".

  • Write a proc. Foo_UpdateCascade_tr @ID, where Foo is the table name

  • Begin a Transaction

  • First INSERT-SELECT a new row in the parent table, from the old row, with the new Key or RID value

  • Second, for all child tables, working top to bottom, INSERT-SELECT the new rows, from the old rows, with the new Key or RID value

  • Third, DELETE the rows in the child tables that have the old Key or RID value, working bottom to top

  • Last, DELETE the row in the parent table that has the old Key or RID value

  • Commit the Transaction

Re the Other Answers

The other answers are incorrect.

  • Disabling constraints and then enabling them, after UPDATing the required rows (parent plus all children) is not something that a person would do in an online production environment, if they wish to remain employed. That advice is good for single-user databases.

  • The need to change the value of a Key or RID is not indicative of a design flaw. It is an ordinary need. That is mitigated by choosing stable (not static) Keys. It can be mitigated, but it cannot be eliminated.

  • A surrogate substituting a natural Key, will not make any difference. In the example you have given, the "key" is a surrogate. And it needs to be updated.

    • Please, just surrogate, there is no such thing as a "surrogate key", because each word contradicts the other. Either it is a Key (made up from the data) xor it isn't. A surrogate is not made up from the data, it is explicitly non-data. It has none of the properties of a Key.
  • There is nothing "tricky" about cascading all the required changes. Refer to the steps given above.

  • There is nothing that can be prevented re the universe changing. It changes. Deal with it. And since the database is a collection of facts about the universe, when the universe changes, the database will have to change. That is life in the big city, it is not for new players.

  • People getting married and hedgehogs getting buried are not a problem (despite such examples being used to suggest that it is a problem). Because we do not use Names as Keys. We use small, stable Identifiers, such as are used to Identify the data in the universe.

    • Names, descriptions, etc, exist once, in one row. Keys exist wherever they have been migrated. And if the "key" is a RID, then the RID too, exists wherever it has been migrated.
  • Don't update the PK! is the second-most hilarious thing I have read in a while. Add a new column is the most.

.htaccess redirect http to https

Searching for the best way to redirect, i've found this (coming from html5boilerplate) :

# ----------------------------------------------------------------------
# | HTTP Strict Transport Security (HSTS)                              |
# ----------------------------------------------------------------------

# Force client-side SSL redirection.
#
# If a user types `example.com` in their browser, even if the server
# redirects them to the secure version of the website, that still leaves
# a window of opportunity (the initial HTTP connection) for an attacker
# to downgrade or redirect the request.
#
# The following header ensures that browser will ONLY connect to your
# server via HTTPS, regardless of what the users type in the browser's
# address bar.
#
# (!) Remove the `includeSubDomains` optional directive if the website's
# subdomains are not using HTTPS.
#
# http://www.html5rocks.com/en/tutorials/security/transport-layer-security/
# https://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14#section-6.1
# http://blogs.msdn.com/b/ieinternals/archive/2014/08/18/hsts-strict-transport-security-attacks-mitigations-deployment-https.aspx

Header set Strict-Transport-Security "max-age=16070400; includeSubDomains"

Maybe it will help someone in 2017 ! :)

Error CS2001: Source file '.cs' could not be found

I open the project,.csproj, using a notepad and delete that missing file reference.

aspx page to redirect to a new page

Darin's answer works great. It creates a 302 redirect. Here's the code modified so that it creates a permanent 301 redirect:

<%@ Page Language="C#" %>
<script runat="server">
  protected override void OnLoad(EventArgs e)
  {
      Response.RedirectPermanent("new.aspx");
      base.OnLoad(e);
  }
</script>

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

It would be more helpful if you posed a more complete working (or in this case non-working) example.

I tried the following:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()

This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1].

Further, as per the hist documentation (i.e. ax.hist? from ipython), I think the sum is fine too:

*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``.  In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::

    pdf, bins, patches = ax.hist(...)
    print np.sum(pdf * np.diff(bins))

Giving this a try after the commands above:

np.sum(n * np.diff(bins))

I get a return value of 1.0 as expected. Remember that normed=True doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n) returned approx 7.2767.

Bulk Record Update with SQL

You can do this through a regular UPDATE with a JOIN

UPDATE T1
SET Description = T2.Description
   FROM Table1 T1
      JOIN Table2 T2
         ON T2.ID = T1.DescriptionId

How to convert a pymongo.cursor.Cursor into a dict?

to_dict() Convert a SON document to a normal Python dictionary instance.

This is trickier than just dict(...) because it needs to be recursive.

http://api.mongodb.org/python/current/api/bson/son.html

sprintf like functionality in Python

Something like...

greetings = 'Hello {name}'.format(name = 'John')

Hello John

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:

@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })

The above format can of course be changed to whatever.

How to get rid of underline for Link component of React Router?

style={{ backgroundImage: "none" }}

Only this worked for me

Clearing all cookies with JavaScript

An answer influenced by both second answer here and W3Schools

document.cookie.split(';').forEach(function(c) {
  document.cookie = c.trim().split('=')[0] + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;';
});

Seems to be working

edit: wow almost exactly the same as Zach's interesting how Stack Overflow put them next to each other.

edit: nvm that was temporary apparently

Return from lambda forEach() in java

I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.

You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.

What I identified in your first case is the following:

  • You want to add elements of an input structure to an output list if they match some predicate.

Let's see how we do that, we can do it with the following:

List<Player> playersOfTeam = players.stream()
    .filter(player -> player.getTeam().equals(teamName))
    .collect(Collectors.toList());

What you do here is:

  1. Turn your input structure into a stream (I am assuming here that it is of type Collection<Player>, now you have a Stream<Player>.
  2. Filter out all unwanted elements with a Predicate<Player>, mapping every player to the boolean true if it is wished to be kept.
  3. Collect the resulting elements in a list, via a Collector, here we can use one of the standard library collectors, which is Collectors.toList().

This also incorporates two other points:

  1. Code against interfaces, so code against List<E> over ArrayList<E>.
  2. Use diamond inference for the type parameter in new ArrayList<>(), you are using Java 8 after all.

Now onto your second point:

You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)... over what he suggested.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

input type="submit" Vs button tag are they interchangeable?

If you are talking about <input type=button>, it won't automatically submit the form

if you are talking about the <button> tag, that's newer and doesn't automatically submit in all browsers.

Bottom line, if you want the form to submit on click in all browsers, use <input type="submit">

Twitter - share button, but with image

You're right in thinking that, in order to share an image in this way without going down the Twitter Cards route, you need to to have tweeted the image already. As you say, it's also important that you grab the image link that's of the form pic.twitter.com/NuDSx1ZKwy

This step-by-step guide is worth checking out for anyone looking to implement a 'tweet this' link or button: http://onlinejournalismblog.com/2015/02/11/how-to-make-a-tweetable-image-in-your-blog-post/.

How to use \n new line in VB msgbox() ...?

Try using vbcrlf for a newline

msgbox "This is how" & vbcrlf & "to get a new line"

Function to convert timestamp to human date in javascript

To calculate date in timestamp from the given date

//To get the timestamp date from normal date: In format - 1560105000000

//input date can be in format : "2019-06-09T18:30:00.000Z"

this.calculateDateInTimestamp = function (inputDate) {
    var date = new Date(inputDate);
    return date.getTime();
}

output : 1560018600000

Concatenate multiple node values in xpath

Try this expression...

string-join(//element3/(concat(element4/text(), '.', element5/text())), "&#10;")

C# : assign data to properties via constructor vs. instantiating

Both approaches call a constructor, they just call different ones. This code:

var albumData = new Album 
                {
                     Name = "Albumius",
                     Artist = "Artistus",
                     Year = 2013
                };

is syntactic shorthand for this equivalent code:

var albumData = new Album();
albumData.Name = "Albumius";
albumData.Artist = "Artistus";
albumData.Year = 2013;

The two are almost identical after compilation (close enough for nearly all intents and purposes). So if the parameterless constructor wasn't public:

public Album() { }

then you wouldn't be able to use the object initializer at all anyway. So the main question isn't which to use when initializing the object, but which constructor(s) the object exposes in the first place. If the object exposes two constructors (like the one in your example), then one can assume that both ways are equally valid for constructing an object.

Sometimes objects don't expose parameterless constructors because they require certain values for construction. Though in cases like that you can still use the initializer syntax for other values. For example, suppose you have these constructors on your object:

private Album() { }
public Album(string name)
{
    this.Name = name;
}

Since the parameterless constructor is private, you can't use that. But you can use the other one and still make use of the initializer syntax:

var albumData = new Album("Albumius")
                {
                     Artist = "Artistus",
                     Year = 2013
                };

The post-compilation result would then be identical to:

var albumData = new Album("Albumius");
albumData.Artist = "Artistus";
albumData.Year = 2013;

Adding and using header (HTTP) in nginx

You can use upstream headers (named starting with $http_) and additional custom headers. For example:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

next, go to console and make request with user's header:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

Display PDF file inside my android application

Maybe you can integrate MuPdf in your application. Here is I've described how to do this: Integrate MuPDF Reader in an app

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

nonatomic property means @synthesized methods are not going to be generated threadsafe -- but this is much faster than the atomic property since extra checks are eliminated.

strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

weak ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB; is used and a has weak property , than its value will only be valid till objectB remains in memory.

copy property is very well explained here

strong,weak,retain,copy,assign are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section

hoping this helps you out a bit...