Programs & Examples On #Automake

Automake is a tool provided by GNU for the purpose of automating the generation of portable, configurable Makefiles.

How to overcome "'aclocal-1.15' is missing on your system" warning?

The problem is not automake package, is the repository

sudo apt-get install automake

Installs version aclocal-1.4, that's why you can't find 1.5 (In Ubuntu 14,15)

Use this script to install latest https://github.com/gp187/nginx-builder/blob/master/fix/aclocal.sh

How to write multiple conditions in Makefile.am with "else if"

ifeq ($(CHIPSET),8960)
   BLD_ENV_BUILD_ID="8960"
else ifeq ($(CHIPSET),8930)
   BLD_ENV_BUILD_ID="8930"
else ifeq ($(CHIPSET),8064)
   BLD_ENV_BUILD_ID="8064"
else ifeq ($(CHIPSET), 9x15)
   BLD_ENV_BUILD_ID="9615"
else
   BLD_ENV_BUILD_ID=
endif

What are Makefile.am and Makefile.in?

DEVELOPER runs autoconf and automake:

  1. autoconf -- creates shippable configure script
    (which the installer will later run to make the Makefile)
  1. automake - creates shippable Makefile.in data file
    (which configure will later read to make the Makefile)

INSTALLER runs configure, make and sudo make install:

./configure       # Creates  Makefile        (from     Makefile.in).  
make              # Creates  the application (from the Makefile just created).  

sudo make install # Installs the application 
                  #   Often, by default its files are installed into /usr/local


INPUT/OUTPUT MAP

Notation below is roughly: inputs --> programs --> outputs

DEVELOPER runs these:

configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in depreciated. Use configure.ac)

Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)

INSTALLER runs these:

Makefile.in -> configure -> Makefile (*.in = input file)

Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)


"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."

"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."

Manuals:

Free online tutorials:


Example:

The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)

From this my generated configure is over 41k lines of code.

And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)

Input length must be multiple of 16 when decrypting with padded cipher

I know this message is old and was a long time ago - but i also had problem with with the exact same error:

the problem I had was relates to the fact the encrypted text was converted to String and to byte[] when trying to DECRYPT it.

    private Key getAesKey() throws Exception {
    return new SecretKeySpec(Arrays.copyOf(key.getBytes("UTF-8"), 16), "AES");
}

private Cipher getMutual() throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    return cipher;// cipher.doFinal(pass.getBytes());
}

public byte[] getEncryptedPass(String pass) throws Exception {
    Cipher cipher = getMutual();
    cipher.init(Cipher.ENCRYPT_MODE, getAesKey());
    byte[] encrypted = cipher.doFinal(pass.getBytes("UTF-8"));
    return encrypted;

}

public String getDecryptedPass(byte[] encrypted) throws Exception {
    Cipher cipher = getMutual();
    cipher.init(Cipher.DECRYPT_MODE, getAesKey());
    String realPass = new String(cipher.doFinal(encrypted));
    return realPass;
}

Is there a "not equal" operator in Python?

Use != or <>. Both stands for not equal.

The comparison operators <> and != are alternate spellings of the same operator. != is the preferred spelling; <> is obsolescent. [Reference: Python language reference]

Searching in a ArrayList with custom objects for certain strings

contains() method just calls equals() on ArrayList elements, so you can overload your class's equals() based on the name class variable. Return true from equals() if name is equal to the matching String. Hope this helps.

psql: could not connect to server: No such file or directory (Mac OS X)

This problema has many sources, and thus many answers. I've experienced each one of them.

1) If you have a crash of some sort, removing the /usr/local/var/postgres/postmaster.pid file is probably required as postgres may not have handled it properly. But ensure that no process is running.

2) Craig Ringer has pointed out in other posts that Apple's bundling of postgreSQL leads to pg gem installation issues Setting the PATH environment variable is a solution.

3) Another solution, is to uninstall and reinstall the gem. A brew update may be necessary as well.

If you stumble upon this post, if you can pinpoint one of the sources, you'll save time...

Remove final character from string

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

How to get current route in react-router 2.0.0-rc5

You can get the current route using

const currentRoute = this.props.routes[this.props.routes.length - 1];

...which gives you access to the props from the lowest-level active <Route ...> component.

Given...

<Route path="childpath" component={ChildComponent} />

currentRoute.path returns 'childpath' and currentRoute.component returns function _class() { ... }.

Properties file in python (similar to Java Properties)

if you don't have multi line properties and a very simple need, a few lines of code can solve it for you:

File t.properties:

a=b
c=d
e=f

Python code:

with open("t.properties") as f:
    l = [line.split("=") for line in f.readlines()]
    d = {key.strip(): value.strip() for key, value in l}

How to return a struct from a function in C++?

You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:

auto f()
{
    struct S
    {
      int a;
      double b;
    } s;
    s.a = 42;
    s.b = 42.0;
    return s;
}

auto x = f();
a = x.a;
b = x.b;

How can I turn a DataTable to a CSV?

Here is an enhancement to vc-74's post that handles commas the same way Excel does. Excel puts quotes around data if the data has a comma but doesn't quote if the data doesn't have a comma.

    public static string ToCsv(this DataTable inDataTable, bool inIncludeHeaders = true)
    {
        var builder = new StringBuilder();
        var columnNames = inDataTable.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
        if (inIncludeHeaders)
            builder.AppendLine(string.Join(",", columnNames));
        foreach (DataRow row in inDataTable.Rows)
        {
            var fields = row.ItemArray.Select(field => field.ToString().WrapInQuotesIfContains(","));
            builder.AppendLine(string.Join(",", fields));
        }

        return builder.ToString();
    }

    public static string WrapInQuotesIfContains(this string inString, string inSearchString)
    {
        if (inString.Contains(inSearchString))
            return "\"" + inString+ "\"";
        return inString;
    }

How can I create a memory leak in Java?

I think that a valid example could be using ThreadLocal variables in an environment where threads are pooled.

For instance, using ThreadLocal variables in Servlets to communicate with other web components, having the threads being created by the container and maintaining the idle ones in a pool. ThreadLocal variables, if not correctly cleaned up, will live there until, possibly, the same web component overwrites their values.

Of course, once identified, the problem can be solved easily.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

How can I get the URL of the current tab from a Google Chrome extension?

The problem is that chrome.tabs.getSelected is asynchronous. This code below will generally not work as expected. The value of 'tablink' will still be undefined when it is written to the console because getSelected has not yet invoked the callback that resets the value:

var tablink;
chrome.tabs.getSelected(null,function(tab) {
    tablink = tab.url;
});
console.log(tablink);

The solution is to wrap the code where you will be using the value in a function and have that invoked by getSelected. In this way you are guaranteed to always have a value set, because your code will have to wait for the value to be provided before it is executed.

Try something like:

chrome.tabs.getSelected(null, function(tab) {
    myFunction(tab.url);
});

function myFunction(tablink) {
  // do stuff here
  console.log(tablink);
}

How to count items in JSON object using command line?

Just throwing another solution in the mix...

Try jq, a lightweight and flexible command-line JSON processor:

jq length /tmp/test.json

Prints the length of the array of objects.

Loop through all the files with a specific extension

I found this solution to be quite handy. It uses the -or option in find:

find . -name \*.tex -or -name "*.png" -or -name "*.pdf"

It will find the files with extension tex, png, and pdf.

Screenshot sizes for publishing android app on Google Play

  • We require 2 screenshots.
  • Use: Displayed on the details page for your application in Google Play.
  • You may upload up to 8 screenshots each for phone, 7” tablet and 10” tablet.
  • Specs: Minimum dimension: 320 pixels. Maximum dimension: 3840 pixels. The maximum dimension of your screenshot cannot be more than twice as long as the minimum dimension. You may use 24 bit PNG or JPEG image (no alpha). Full bleed, no border in art.
  • We recommend adding screenshots of your app running on a 7" and 10" tablet. Go to ‘Store listing’ page in your Developer Console to add tablet apps screenshots.

https://support.google.com/googleplay/android-developer/answer/1078870?hl=en&ref_topic=2897459

instanceof Vs getClass( )

I know it has been a while since this was asked, but I learned an alternative yesterday

We all know you can do:

if(o instanceof String) {   // etc

but what if you dont know exactly what type of class it needs to be? you cannot generically do:

if(o instanceof <Class variable>.getClass()) {   

as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()

For example:

public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {

    return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}

Could not reliably determine the server's fully qualified domain name

If you are using windows, remove comment on these lines and set them as:

Line 227 : ServerName 127.0.0.1:80 
Line 235 : AllowOverride all 
Line 236 : Require all granted

Worked for me!

Why does "npm install" rewrite package-lock.json?

Use the npm ci command instead of npm install.

"ci" stands for "continuous integration".

It will install the project dependencies based on the package-lock.json file instead of the lenient package.json file dependencies.

It will produce identical builds to your team mates and it is also much faster.

You can read more about it in this blog post: https://blog.npmjs.org/post/171556855892/introducing-npm-ci-for-faster-more-reliable

Styling Google Maps InfoWindow

Use the InfoBox plugin from the Google Maps Utility Library. It makes styling/managing map pop-ups much easier.

Note that you'll need to make sure it loads after the google maps API:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap" async defer></script>
<script src="/js/infobox_packed.js" async defer></script>

LINQ query to find if items in a list are contained in another list

I think this would be easiest one:

test1.ForEach(str => test2.RemoveAll(x=>x.Contains(str)));

Javascript - sort array based on another array

Use intersection of two arrays.

Ex:

var sortArray = ['a', 'b', 'c',  'd', 'e'];

var arrayToBeSort = ['z', 's', 'b',  'e', 'a'];

_.intersection(sortArray, arrayToBeSort) 

=> ['a', 'b', 'e']

if 'z and 's' are out of range of first array, append it at the end of result

multiple axis in matplotlib with different scales

if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True, like this:

df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)

This would look something like below:

enter image description here

You can do few more things as well. Take a look at Pandas plotting doc.

How to calculate number of days between two given dates?

from datetime import date
def d(s):
  [month, day, year] = map(int, s.split('/'))
  return date(year, month, day)
def days(start, end):
  return (d(end) - d(start)).days
print days('8/18/2008', '9/26/2008')

This assumes, of course, that you've already verified that your dates are in the format r'\d+/\d+/\d+'.

How to write dynamic variable in Ansible playbook

I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

   vars:
    myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"

Scrollview vertical and horizontal in android

My solution based on Mahdi Hijazi answer, but without any custom views:

Layout:

<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/scrollHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ScrollView 
        android:id="@+id/scrollVertical"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >

        <WateverViewYouWant/>

    </ScrollView>
</HorizontalScrollView>

Code (onCreate/onCreateView):

    final HorizontalScrollView hScroll = (HorizontalScrollView) value.findViewById(R.id.scrollHorizontal);
    final ScrollView vScroll = (ScrollView) value.findViewById(R.id.scrollVertical);
    vScroll.setOnTouchListener(new View.OnTouchListener() { //inner scroll listener         
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return false;
        }
    });
    hScroll.setOnTouchListener(new View.OnTouchListener() { //outer scroll listener         
        private float mx, my, curX, curY;
        private boolean started = false;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            curX = event.getX();
            curY = event.getY();
            int dx = (int) (mx - curX);
            int dy = (int) (my - curY);
            switch (event.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    if (started) {
                        vScroll.scrollBy(0, dy);
                        hScroll.scrollBy(dx, 0);
                    } else {
                        started = true;
                    }
                    mx = curX;
                    my = curY;
                    break;
                case MotionEvent.ACTION_UP: 
                    vScroll.scrollBy(0, dy);
                    hScroll.scrollBy(dx, 0);
                    started = false;
                    break;
            }
            return true;
        }
    });

You can change the order of the scrollviews. Just change their order in layout and in the code. And obviously instead of WateverViewYouWant you put the layout/views you want to scroll both directions.

Why can I ping a server but not connect via SSH?

On the server, try:

netstat -an 

and look to see if tcp port 22 is opened (use findstr in Windows or grep in Unix).

How do you execute SQL from within a bash script?

Here is a simple way of running MySQL queries in the bash shell

mysql -u [database_username] -p [database_password] -D [database_name] -e "SELECT * FROM [table_name]"

What does <> mean?

Yes in SQl <> is the same as != which is not equal.....excepts for NULLS of course, in that case you need to use IS NULL or IS NOT NULL

error, string or binary data would be truncated when trying to insert

I had the same issue. The length of my column was too short.

What you can do is either increase the length or shorten the text you want to put in the database.

Getting file size in Python?

Use os.path.getsize(path) which will

Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.

import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')

Or use os.stat(path).st_size

import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size 

Or use Path(path).stat().st_size (Python 3.4+)

from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size

PostgreSQL error: Fatal: role "username" does not exist

After trying many other people's solutions, and without success, this answer finally helped me.

https://stackoverflow.com/a/16974197/2433309

In short, running

sudo -u postgres createuser owning_user

creates a role with name owning_user (in this case, h9uest). After that you can run rake db:create from the terminal under whatever account name you set up without having to enter into the Postgres environment.

How do I restart a program based on user input?

Using one while loop:

In [1]: start = 1
   ...: 
   ...: while True:
   ...:     if start != 1:        
   ...:         do_run = raw_input('Restart?  y/n:')
   ...:         if do_run == 'y':
   ...:             pass
   ...:         elif do_run == 'n':
   ...:             break
   ...:         else: 
   ...:             print 'Invalid input'
   ...:             continue
   ...: 
   ...:     print 'Doing stuff!!!'
   ...: 
   ...:     if start == 1:
   ...:         start = 0
   ...:         
Doing stuff!!!

Restart?  y/n:y
Doing stuff!!!

Restart?  y/n:f
Invalid input

Restart?  y/n:n

In [2]:

How to make scipy.interpolate give an extrapolated result beyond the input range?

The below code gives you the simple extrapolation module. k is the value to which the data set y has to be extrapolated based on the data set x. The numpy module is required.

 def extrapol(k,x,y):
        xm=np.mean(x);
        ym=np.mean(y);
        sumnr=0;
        sumdr=0;
        length=len(x);
        for i in range(0,length):
            sumnr=sumnr+((x[i]-xm)*(y[i]-ym));
            sumdr=sumdr+((x[i]-xm)*(x[i]-xm));

        m=sumnr/sumdr;
        c=ym-(m*xm);
        return((m*k)+c)

CSS: Creating textured backgrounds

You should try slicing the image if possible into a smaller piece which could be repeated. I have sliced that image to a 101x101px image.

BG Tile

CSS:

body{
  background-image: url(SO_texture_bg.jpg);
  background-repeat:repeat;
}

But in some cases, we wouldn't be able to slice the image to a smaller one. In that case, I would use the whole image. But you could also use the CSS3 methods like what Mustafa Kamal had mentioned.

Wish you good luck.

Receive result from DialogFragment

Or share ViewModel like showed here:

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

    public void select(Item item) {
        selected.setValue(item);
    }

    public LiveData<Item> getSelected() {
        return selected;
    }
}


public class MasterFragment extends Fragment {
    private SharedViewModel model;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {
            model.select(item);
        });
    }
}

public class DetailFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.getSelected().observe(this, { item ->
           // Update the UI.
        });
    }
}

https://developer.android.com/topic/libraries/architecture/viewmodel#sharing_data_between_fragments

set serveroutput on in oracle procedure

If you want to execute any procedure then firstly you have to set serveroutput on in the sqldeveloper work environment like.

->  SET SERVEROUTPUT ON;
-> BEGIN
dbms_output.put_line ('Hello World..');
dbms_output.put_line('Its displaying the values only for the Testing purpose');
END;
/

MYSQL query between two timestamps

@Amaynut Thanks

SELECT * 
FROM eventList 
WHERE date BETWEEN UNIX_TIMESTAMP('2017-08-01') AND UNIX_TIMESTAMP('2017/08/01');

above mention, code works and my problem solved.

how does unix handle full path name with space and arguments?

You can either quote it like your Windows example above, or escape the spaces with backslashes:

 "/foo folder with space/foo" --help
 /foo\ folder\ with\ space/foo --help

How to adjust layout when soft keyboard appears

Just add

android:windowSoftInputMode="adjustResize"

in your AndroidManifest.xml where you declare this particular activity and this will adjust the layout resize option.

enter image description here

some source code below for layout design

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="FaceBook"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="30dp"
        android:ems="10"
        android:hint="username" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="password" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="20dp"
        android:text="Log In" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="17dp"
        android:gravity="center"
        android:text="Sign up for facebook"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Kotlin's List missing "add", "remove", Map missing "put", etc?

https://kotlinlang.org/docs/reference/collections.html

According to above link List<E> is immutable in Kotlin. However this would work:

var list2 = ArrayList<String>()
list2.removeAt(1)

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

What is the difference between syntax and semantics in programming languages?

Syntax is about the structure or the grammar of the language. It answers the question: how do I construct a valid sentence? All languages, even English and other human (aka "natural") languages have grammars, that is, rules that define whether or not the sentence is properly constructed.

Here are some C language syntax rules:

  • separate statements with a semi-colon
  • enclose the conditional expression of an IF statement inside parentheses
  • group multiple statements into a single statement by enclosing in curly braces
  • data types and variables must be declared before the first executable statement (this feature has been dropped in C99. C99 and latter allow mixed type declarations.)

Semantics is about the meaning of the sentence. It answers the questions: is this sentence valid? If so, what does the sentence mean? For example:

x++;                  // increment
foo(xyz, --b, &qrs);  // call foo

are syntactically valid C statements. But what do they mean? Is it even valid to attempt to transform these statements into an executable sequence of instructions? These questions are at the heart of semantics.

Consider the ++ operator in the first statement. First of all, is it even valid to attempt this?

  • If x is a float data type, this statement has no meaning (according to the C language rules) and thus it is an error even though the statement is syntactically correct.
  • If x is a pointer to some data type, the meaning of the statement is to "add sizeof(some data type) to the value at address x and store the result into the location at address x".
  • If x is a scalar, the meaning of the statement is "add one to the value at address x and store the result into the location at address x".

Finally, note that some semantics cannot be determined at compile-time and must therefore must be evaluated at run-time. In the ++ operator example, if x is already at the maximum value for its data type, what happens when you try to add 1 to it? Another example: what happens if your program attempts to dereference a pointer whose value is NULL?

In summary, syntax is the concept that concerns itself only whether or not the sentence is valid for the grammar of the language . Semantics is about whether or not the sentence has a valid meaning.

MySQL: What's the difference between float and double?

Doubles are just like floats, except for the fact that they are twice as large. This allows for a greater accuracy.

Download image from the site in .NET/C#

The best practice to download an image from Server or from Website and store it locally.

WebClient client=new Webclient();
client.DownloadFile("WebSite URL","C:\\....image.jpg");
client.Dispose();

Java: Instanceof and Generics

Provided your class extends a class with a generic parameter, you can also get this at runtime via reflection, and then use that for comparison, i.e.

class YourClass extends SomeOtherClass<String>
{

   private Class<?> clazz;

   public Class<?> getParameterizedClass()
   {
      if(clazz == null)
      {
         ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
          clazz = (Class<?>)pt.getActualTypeArguments()[0];
       }
       return clazz;
    }
}

In the case above, at runtime you will get String.class from getParameterizedClass(), and it caches so you don't get any reflection overhead upon multiple checks. Note that you can get the other parameterized types by index from the ParameterizedType.getActualTypeArguments() method.

Column standard deviation R

The general idea is to sweep the function across. You have many options, one is apply():

R> set.seed(42)
R> M <- matrix(rnorm(40),ncol=4)
R> apply(M, 2, sd)
[1] 0.835449 1.630584 1.156058 1.115269
R> 

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

For those like me who wonder how legacy apps are treated, I did a bit of testing and computation on the subject.

Thanks to @hannes-sverrisson hint, I started on the assumption that a legacy app is treated with a 320x568 view in iPhone 6 and iPhone 6 plus.

The test was made with a simple black background [email protected] with a white border. The background has a size of 640x1136 pixels, and it is black with an inner white border of 1 pixel.

Below are the screenshots provided by the simulator:

On the iPhone 6 screenshot, we can see a 1 pixel margin on top and bottom of the white border, and a 2 pixel margin on the iPhone 6 plus screenshot. This gives us a used space of 1242x2204 on iPhone 6 plus, instead of 1242x2208, and 750x1332 on the iPhone 6, instead of 750x1334.

We can assume that those dead pixels are meant to respect the iPhone 5 aspect ratio:

iPhone 5               640 / 1136 = 0.5634
iPhone 6 (used)        750 / 1332 = 0.5631
iPhone 6 (real)        750 / 1334 = 0.5622
iPhone 6 plus (used)  1242 / 2204 = 0.5635
iPhone 6 plus (real)  1242 / 2208 = 0.5625

Second, it is important to know that @2x resources will be scaled not only on iPhone 6 plus (which expects @3x assets), but also on iPhone 6. This is probably because not scaling the resources would have led to unexpected layouts, due to the enlargement of the view.

However, that scaling is not equivalent in width and height. I tried it with a 264x264 @2x resource. Given the results, I have to assume that the scaling is directly proportional to the pixels / points ratio.

Device         Width scale             Computed width   Screenshot width
iPhone 5        640 /  640 = 1.0                        264 px
iPhone 6        750 /  640 = 1.171875  309.375          309 px
iPhone 6 plus  1242 /  640 = 1.940625  512.325          512 px

Device         Height scale            Computed height  Screenshot height
iPhone 5       1136 / 1136 = 1.0                        264 px
iPhone 6       1332 / 1136 = 1.172535  309.549          310 px
iPhone 6 plus  2204 / 1136 = 1.940141  512.197          512 px

It's important to note the iPhone 6 scaling is not the same in width and height (309x310). This tends to confirm the above theory that scaling is not proportional in width and height, but uses the pixels / points ratio.

I hope this helps.

Read binary file as string in Ruby

Ruby have binary reading

data = IO.binread(path/filaname)

or if less than Ruby 1.9.2

data = IO.read(path/file)

Newline in JLabel

You can use the MultilineLabel component in the Jide Open Source Components.

http://www.jidesoft.com/products/oss.htm

Java - remove last known item from ArrayList

You need to understand java generics. You have a list of ClientThread but trying to get String. You have other errors, but this one is very basic.

When to use IList and when to use List

It's always best to use the lowest base type possible. This gives the implementer of your interface, or consumer of your method, the opportunity to use whatever they like behind the scenes.

For collections you should aim to use IEnumerable where possible. This gives the most flexibility but is not always suited.

Using .text() to retrieve only text not nested in child tags

This is an old question but the top answer is very inefficient. Here's a better solution:

$.fn.myText = function() {
    var str = '';

    this.contents().each(function() {
        if (this.nodeType == 3) {
            str += this.textContent || this.innerText || '';
        }
    });

    return str;
};

And just do this:

$("#foo").myText();

Sorting Characters Of A C++ String

There is a sorting algorithm in the standard library, in the header <algorithm>. It sorts inplace, so if you do the following, your original word will become sorted.

std::sort(word.begin(), word.end());

If you don't want to lose the original, make a copy first.

std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());

Round integers to the nearest 10

About the round(..) function returning a float

That float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)

See the discussion here for details.

How to convert an array to object in PHP?

This requires PHP7 because I chose to use a lambda function to lock away the 'innerfunc' within the main function. The lambda function is called recursively, hence the need for: "use ( &$innerfunc )". You could do it in PHP5 but could not hide the innerfunc.

function convertArray2Object($defs) {
    $innerfunc = function ($a) use ( &$innerfunc ) {
       return (is_array($a)) ? (object) array_map($innerfunc, $a) : $a; 
    };
    return (object) array_map($innerfunc, $defs);
}

Python: convert string from UTF-8 to Latin-1

If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.

In my case, I was using json.load on data incorrectly read from file by not using the encoding="utf-8". Trying to de-/encode the resulting string to latin-1 just does not help...

Bootstrap col-md-offset-* not working

Where's the problem

In your HTML all h2s have the same off-set of 4 columns, so they won't make a diagonal.

How to fix it

A row has 12 columns, so we should put every h2 in it's own row. You should have something like this:

<div class="jumbotron">
    <div class="container">
        <div class="row">
                <h2 class="col-md-4 col-md-offset-1">Browse.</h2>
        </div>
        <div class="row">
                <h2 class="col-md-4 col-md-offset-2">create.</h2>
        </div>
        <div class="row">
                <h2 class="col-md-4 col-md-offset-3">share.</h2>
        </div>
    </div>
</div>

An alternative is to make every h2 width plus offset sum 12 columns, so each one automatically wraps in a new line.

<div class="jumbotron">
    <div class="container">
        <div class="row">
                <h2 class="col-md-11 col-md-offset-1">Browse.</h2>
                <h2 class="col-md-10 col-md-offset-2">create.</h2>
                <h2 class="col-md-9 col-md-offset-3">share.</h2>
        </div>
    </div>
</div>

Regular expression to limit number of characters to 10

grep '^[0-9]\{1,16\}' | wc -l

Gives the counts with exact match count with limit

How to get the cookie value in asp.net website

You may use Request.Cookies collection to read the cookies.

if(Request.Cookies["key"]!=null)
{
   var value=Request.Cookies["key"].Value;
}

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

Adjust UILabel height depending on the text

Since sizeWithFont is deprecated I use this one instead.

this one get label specific attributes.

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text{

    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];

    return ceil(rect.size.height);
}

How can I truncate a string to the first 20 words in PHP?

Its not my own creation, its a modification of previous posts. credits goes to karim79.

function limit_text($text, $limit) {
    $strings = $text;
      if (strlen($text) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          if(sizeof($pos) >$limit)
          {
            $text = substr($text, 0, $pos[$limit]) . '...';
          }
          return $text;
      }
      return $text;
    }

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

I have a a blank solution BuildRebuildClean and three class library Models,Repository,Notification.

I use Models and Repository in Notification class library.

Then:

  • Build solution Incremental build and compiles only the files that are changed. If an assembly has no changes, it won’t be re-built. Also, it will not delete any intermediate files. If Modify some code in Models library project, then BUILD solution. In the below screen shot, refer to the time stamp of DLL, EXE is updated in Models and Notification library.

enter image description here

  • Rebuild solution Deletes all compiled files and compiles all irrespective of changes, ignoring anything it’s done before. Right click on the solution name BuildRebuildClean. What it does is deletes all the assemblies, EXEs and referred files to compile again.

enter image description here

  • Clean Solution Deletes all compiled, intermediate files (i.e., EXEs and DLLs) from the bin/obj directory.

enter image description here

ITextSharp insert text to an existing pdf

Here is a method that uses stamper and absolute coordinates showed in the different PDF clients (Adobe, FoxIt and etc. )

public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point)
    {
        //variables
        string pathin = inputPdfPath;
        string pathout = outputPdfPath;

        //create PdfReader object to read from the existing document
        using (PdfReader reader = new PdfReader(pathin))
        //create PdfStamper object to write to get the pages from reader 
        using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
        {
            //select two pages from the original document
            reader.SelectPages("1-2");

            //gettins the page size in order to substract from the iTextSharp coordinates
            var pageSize = reader.GetPageSize(1);

            // PdfContentByte from stamper to add content to the pages over the original content
            PdfContentByte pbover = stamper.GetOverContent(1);

            //add content to the page using ColumnText
            Font font = new Font();
            font.Size = 45;

            //setting up the X and Y coordinates of the document
            int x = point.X;
            int y = point.Y;

            y = (int) (pageSize.Height - y);

            ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
        }
    }

Share data between html pages

Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)

I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.

But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.

These two links might help you, it shows the example via Node backend, but you get the point how it works:

Link 1

And, of course, the CORS spec:

Link 2

~Cheers

How can I insert binary file data into a binary SQL field using a simple insert statement?

If you mean using a literal, you simply have to create a binary string:

insert into Files (FileId, FileData) values (1, 0x010203040506)

And you will have a record with a six byte value for the FileData field.


You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).

You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).


In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.

How to export query result to csv in Oracle SQL Developer?

To take an export to your local system from sql developer.

Path : C:\Source_Table_Extract\des_loan_due_dtls_src_boaf.csv

    SPOOL "Path where you want to save the file"
    SELECT /*csv*/ * FROM TABLE_NAME;

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

You can use JavascriptResult to achieve this.

To redirect:

return JavaScript("window.location = 'http://www.google.co.uk'");

To reload the current page:

return JavaScript("location.reload(true)");

Seems the simplest option.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

tl;dr

java.sql.Timestamp.from (
    LocalDate.of ( 2007 , 9 , 23 )
             .atStartOfDay( ZoneId.of ( "America/Montreal" ) )
             .toInstant()
)

java.time

Let’s update this page by showing code using the java.time framework built into Java 8 and later.

These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They supplant the notoriously troublesome old date-time classes bundled with early versions of Java.

In java.time, an Instant is a moment on the timeline in UTC. A ZonedDateTime is an Instant adjusted into a time zone (ZoneId).

Time zone is crucial here. A date of September 23, 2007 cannot be translated to a moment on the timeline without applying a time zone. Consider that a new day dawns earlier in Paris than in Montréal where it is still “yesterday”.

Also, a java.sql.Timestamp represents both a date and time-of-day. So we must inject a time-of-day to go along with the date. We assume you want the first moment of the day as the time-of-day. Note that this is not always the time 00:00:00.0 because of Daylight Saving Time and possibly other anomalies.

Note that unlike the old java.util.Date class, and unlike Joda-Time, the java.time types have a resolution of nanoseconds rather than milliseconds. This matches the resolution of java.sql.Timestamp.

Note that the java.sql.Timestamp has a nasty habit of implicitly applying your JVM’s current default time zone to its date-time value when generating a string representation via its toString method. Here you see my America/Los_Angeles time zone applied. In contrast, the java.time classes are more sane, using standard ISO 8601 formats.

LocalDate d = LocalDate.of ( 2007 , 9 , 23 ) ;
ZoneId z = ZoneId.of ( "America/Montreal" ) ;
ZonedDateTime zdt = d.atStartOfDay( z ) ;
Instant instant = zdt.toInstant() ;
java.sql.Timestamp ts = java.sql.Timestamp.from ( instant ) ;

Dump to console.

System.out.println ( "d: " + d + " = zdt: " + zdt + " = instant: " + instant + " = ts: " + ts );

When run.

d: 2007-09-23 = zdt: 2007-09-23T00:00-04:00[America/Montreal] = instant: 2007-09-23T04:00:00Z = ts: 2007-09-22 21:00:00.0

By the way, as of JDBC 4.2, you can use the java.time types directly. No need for java.sql.Timestamp.

  • PreparedStatement.setObject
  • ResultSet.getObject

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Looping through the content of a file in Bash

Suppose you have this file:

$ cat /tmp/test.txt
Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR

There are four elements that will alter the meaning of the file output read by many Bash solutions:

  1. The blank line 4;
  2. Leading or trailing spaces on two lines;
  3. Maintaining the meaning of individual lines (i.e., each line is a record);
  4. The line 6 not terminated with a CR.

If you want the text file line by line including blank lines and terminating lines without CR, you must use a while loop and you must have an alternate test for the final line.

Here are the methods that may change the file (in comparison to what cat returns):

1) Lose the last line and leading and trailing spaces:

$ while read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'

(If you do while IFS= read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt instead, you preserve the leading and trailing spaces but still lose the last line if it is not terminated with CR)

2) Using process substitution with cat will reads the entire file in one gulp and loses the meaning of individual lines:

$ for p in "$(cat /tmp/test.txt)"; do printf "%s\n" "'$p'"; done
'Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR'

(If you remove the " from $(cat /tmp/test.txt) you read the file word by word rather than one gulp. Also probably not what is intended...)


The most robust and simplest way to read a file line-by-line and preserve all spacing is:

$ while IFS= read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'    Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space    '
'Line 6 has no ending CR'

If you want to strip leading and trading spaces, remove the IFS= part:

$ while read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'
'Line 6 has no ending CR'

(A text file without a terminating \n, while fairly common, is considered broken under POSIX. If you can count on the trailing \n you do not need || [[ -n $line ]] in the while loop.)

More at the BASH FAQ

Case insensitive regular expression without re.compile?

Pass re.IGNORECASE to the flags param of search, match, or sub:

re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)

Eclipse error ... cannot be resolved to a type

Project -> Build Path -> Configure Build Path
Select Java Build path on the left menu, and select "Source"
 click on Excluded and then Include(All) and then click OK
    Cause : The issue might because u might have deleted the CLASS files 
 or dependencies on the project

For maven users:

Right click on the project

Maven

Update Project

Ctrl+click doesn't work in Eclipse Juno

I had similar issue, along with this I found that java build path in project properties was missing. Project pulled from repository did not had .project file and eclipse created a default .project file, I copied content of .project.xml from other working project and removed the unsed imports, After which everything worked fine

<projectDescription>
<name>XYZ</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
    <buildCommand>
        <name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
        <arguments>
        </arguments>
    </buildCommand>
    <buildCommand>
        <name>org.eclipse.jdt.core.javabuilder</name>
    </buildCommand>
    <buildCommand>
        <name>org.eclipse.wst.common.project.facet.core.builder</name>
    </buildCommand>
    <buildCommand>
        <name>org.eclipse.wst.validation.validationbuilder</name>
    </buildCommand>
</buildSpec>
<natures>
    <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
    <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
    <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
    <nature>org.eclipse.jdt.core.javanature</nature>
    <nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>

why are there two different kinds of for loops in java?

The For-each loop, as it is called, is a type of for loop that is used with collections to guarantee that all items in a collection are iterated over. For example

for ( Object o : objects ) {
    System.out.println(o.toString());
}

Will call the toString() method on each object in the collection "objects". One nice thing about this is that you cannot get an out of bounds exception.

How do I run a Java program from the command line on Windows?

To complete the answer :

  1. The Java File

    TheJavaFile.java
    
  2. Compile the Java File to a *.class file

    javac TheJavaFile.java
    
    • This will create a TheJavaFile.class file
  3. Execution of the Java File

    java TheJavaFile
    
  4. Creation of an executable *.jar file

    • You've got two options here -

      1. With an external manifest file :

        • Create the manifest file say - MANIFEST.mf

        • The MANIFEST file is nothing but an explicit entry of the Main Class

        • jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class

      2. Executable by Entry Point:

        • jar -cvfe TheJavaFile.jar <MainClass> TheJavaFile.class
  5. To run the Jar File

    java -jar TheJavaFile.jar
    

Calculate age given the birth date in the format YYYYMMDD

Here's the simplest, most accurate solution I could come up with:

Date.prototype.getAge = function (date) {
    if (!date) date = new Date();
    return ~~((date.getFullYear() + date.getMonth() / 100
    + date.getDate() / 10000) - (this.getFullYear() + 
    this.getMonth() / 100 + this.getDate() / 10000));
}

And here is a sample that will consider Feb 29 -> Feb 28 a year.

Date.prototype.getAge = function (date) {
    if (!date) date = new Date();
    var feb = (date.getMonth() == 1 || this.getMonth() == 1);
    return ~~((date.getFullYear() + date.getMonth() / 100 + 
        (feb && date.getDate() == 29 ? 28 : date.getDate())
        / 10000) - (this.getFullYear() + this.getMonth() / 100 + 
        (feb && this.getDate() == 29 ? 28 : this.getDate()) 
        / 10000));
}

It even works with negative age!

How to refresh page on back button click?

Ahem u_u

As i've stated the back button is for every one of us a pain in some place... that said...

As long as you load the page normally it makes a lot of trouble... for a standard "site" it will not change that much... however i think you can make something like this

The user access everytime to your page .php that choose what to load. You can try to work a little with cache (to not cache page) and maybe expire date.

But the long term solution will be put a code on "onload" event to fetch the data trought Ajax, this way you can (with Javascript) run the code you want, and example refresh the page.

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

Here it is! - SP 25 works on Visual Studio 2019, SP 21 on Visual Studio 2017

SAP released SAP Crystal Reports, developer version for Microsoft Visual Studio

You can get it here (click "Installation package for Visual Studio IDE")

To integrate “SAP Crystal Reports, developer version for Microsoft Visual Studio” you must run the Install Executable. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.

New In SP25 Release

Visual Studio 2019, Addressed incidents, Win10 1809, Security update

How to read large text file on windows?

If all you need is a tool for reading, then this thing will open the file instantly http://www.readfileonline.com/

How to add items to array in nodejs

var array = [];

//length array now = 0
array[array.length] = 'hello';
//length array now = 1
//            0
//array = ['hello'];//length = 1

Using regular expression in css?

there is another simple way to select particular elements in css too...

#s1, #s2, #s3 {
    // set css attributes here
}

if you only have a few elements to choose from, and dont want to bother with classes, this will work easily too.

Html.ActionLink as a button or an image, not a link

I like to use Url.Action() and Url.Content() like this:

<a href='@Url.Action("MyAction", "MyController")'>
    <img src='@Url.Content("~/Content/Images/MyLinkImage.png")' />
</a>

Strictly speaking, the Url.Content is only needed for pathing is not really part of the answer to your question.

Thanks to @BrianLegg for pointing out that this should use the new Razor view syntax. Example has been updated accordingly.

Check if checkbox is checked with jQuery

Something like this can help

togglecheckBoxs =  function( objCheckBox ) {

    var boolAllChecked = true;

    if( false == objCheckBox.checked ) {
        $('#checkAll').prop( 'checked',false );
    } else {
        $( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
            if( false == chkbox.checked ) {
                $('#checkAll').prop( 'checked',false );
                boolAllChecked = false;
            }
        });

        if( true == boolAllChecked ) {
            $('#checkAll').prop( 'checked',true );
        }
    }
}

Nginx subdomain configuration

You could move the common parts to another configuration file and include from both server contexts. This should work:

server {
  listen 80;
  server_name server1.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

server {
  listen 80;
  server_name another-one.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled (normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org's configuration file is /etc/nginx/sites-enabled and it looks like this:

server {
  listen   80 default_server;
  listen   [2a01:4f8:120:3105::101:1]:80 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-80;
}

server {
  listen   443 default_server;
  listen   [2a01:4f8:120:3105::101:1]:443 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/ssl-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-443;
}

As an example here's the /etc/nginx/include.d/all-common file that's included from both server contexts:

index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;

location ~ /\.ht {
  deny all;
}

location = /favicon.ico {
  log_not_found off;
  access_log off;
}

location ~ /(README|ChangeLog)$ {
  types { }
  default_type text/plain;
}

Java: Reading integers from a file into an array

For comparison, here is another way to read the file. It has one advantage that you don't need to know how many integers there are in the file.

File file = new File("Tall.txt");
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
String[] valueStr = new String(bytes).trim().split("\\s+");
int[] tall = new int[valueStr.length];
for (int i = 0; i < valueStr.length; i++) 
    tall[i] = Integer.parseInt(valueStr[i]);
System.out.println(Arrays.asList(tall));

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

If you want to solve this issue using async/await:

(async function(){    
    try {        
        const response1, response2, response3
        response1 = await promise1()

        if(response1){
            response2 = await promise2()
        }
        if(response2){
            response3 = await promise3()
        }
        return [response1, response2, response3]
    } catch (error) {
        return []
    }

})()

Can I load a UIImage from a URL?

You can try SDWebImage, it provides:

  1. Asynchronous loading
  2. Caching for offline use
  3. Place holder image to appear while loading
  4. Works well with UITableView

Quick example:

    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Not able to start Genymotion device

I'm using Windows 10 and had the same problem. I resolved it updating the VirtualBox to version 5.1.5. I hope it can help.

How to get the part of a file after the first line that matches a regular expression?

Alternatives to the excellent sed answer by jfgagne, and which don't include the matching line :

How do I download a tarball from GitHub using cURL?

Use the -L option to follow redirects:

curl -L https://github.com/pinard/Pymacs/tarball/v0.24-beta2 | tar zx

javascript window.location in new tab

You can even use

window.open('https://support.wwf.org.uk', "_blank") || window.location.replace('https://support.wwf.org.uk');

This will open it on the same tab if the pop-up is blocked.

XAMPP - Apache could not start - Attempting to start Apache service

I had the same issue.Just click on services button.Then find apache and right cick > properties > set startup type as Automatic/ Manual. Now close apache and try again.It will work!

enter image description here

Testing Private method using mockito

Here is a small example how to do it with powermock

public class Hello {
    private Hello obj;
    private Integer method1(Long id) {
        return id + 10;
    }
} 

To test method1 use code:

Hello testObj = new Hello();
Integer result = Whitebox.invokeMethod(testObj, "method1", new Long(10L));

To set private object obj use this:

Hello testObj = new Hello();
Hello newObject = new Hello();
Whitebox.setInternalState(testObj, "obj", newObject);

Laravel whereIn OR whereIn

For example, if you have multiple whereIn OR whereIn conditions and you want to put brackets, do it like this:

$getrecord = DiamondMaster::where('is_delete','0')->where('user_id',Auth::user()->id);
if(!empty($request->stone_id))
{
    $postdata = $request->stone_id;
    $certi_id =trim($postdata,",");
    $getrecord = $getrecord->whereIn('id',explode(",", $certi_id))
                           ->orWhereIn('Certi_NO',explode(",", $certi_id));     
}
$getrecord = $getrecord->get();

Visual Studio Error: (407: Proxy Authentication Required)

The solution that worked for me in both Visual Studio 2013 and Microsoft Test Manager (MTM) was to ensure that both devenv.exe.config and mtm.exe.config included this configurations section:

<system.net>
    <settings>
        <ipv6 enabled="true"/>
        <servicePointManager expect100Continue="false"/>
    </settings>
    <defaultProxy useDefaultCredentials="true" enabled="true">
        <proxy usesystemdefault="True" />
    </defaultProxy>
</system.net>

MTM did not have a system.net setting and the whole section was added immediately following the closing xml tag </appSettings>.

How to compare two tags with git?

For a side-by-side visual representation, I use git difftool with openDiff set to the default viewer.

Example usage:

git difftool tags/<FIRST TAG> tags/<SECOND TAG>

If you are only interested in a specific file, you can use:

git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>

As a side-note, the tags/<TAG>s can be replaced with <BRANCH>es if you are interested in diffing branches.

Check whether a value exists in JSON object

You could improve on the answer from Ponmudi VN:

  • Shorter Code
  • Look for a key and a value

See this fiddle: https://jsfiddle.net/solarbaypilot/sn3wtea2/

function _isContains(json, keyname, value) {

return Object.keys(json).some(key => {
        return typeof json[key] === 'object' ? 
        _isContains(json[key], keyname, value) : key === keyname && json[key] === value;
    });
}

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};


document.getElementById('dog').innerHTML = _isContains(JSONObject, "name", "dog");
document.getElementById('puppy').innerHTML = _isContains(JSONObject, "name", "puppy");

Rails.env vs RAILS_ENV

ENV['RAILS_ENV'] is now deprecated.

You should use Rails.env which is clearly much nicer.

Heap vs Binary Search Tree (BST)

Heap just guarantees that elements on higher levels are greater (for max-heap) or smaller (for min-heap) than elements on lower levels, whereas BST guarantees order (from "left" to "right"). If you want sorted elements, go with BST.

How to send parameters from a notification-click to an activity?

In your notification implementation, use a code like this:

NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
...
Intent intent = new Intent(this, ExampleActivity.class);
intent.putExtra("EXTRA_KEY", "value");

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
nBuilder.setContentIntent(pendingIntent);
...

To Get Intent extra values in the ExampleActivity, use the following code:

...
Intent intent = getIntent();
if(intent!=null) {
    String extraKey = intent.getStringExtra("EXTRA_KEY");
}
...

VERY IMPORTANT NOTE: the Intent::putExtra() method is an Overloaded one. To get the extra key, you need to use Intent::get[Type]Extra() method.

Note: NOTIFICATION_ID and NOTIFICATION_CHANNEL_ID are an constants declared in ExampleActivity

How to write an inline IF statement in JavaScript?

FYI, you can compose conditional operators

var a = (truthy) ? 1 : (falsy) ? 2 : 3;

If your logic is sufficiently complex, then you might consider using an IIFE

var a = (function () {
  if (truthy) return 1;
  else if (falsy) return 2;
  return 3;
})();

Of course, if you plan to use this logic more than once, then you aught to encapsulate it in a function to keep things nice and DRY.

C# How do I click a button by hitting Enter whilst textbox has focus?

The usual way to do this is to set the Form's AcceptButton to the button you want "clicked". You can do this either in the VS designer or in code and the AcceptButton can be changed at any time.

This may or may not be applicable to your situation, but I have used this in conjunction with GotFocus events for different TextBoxes on my form to enable different behavior based on where the user hit Enter. For example:

void TextBox1_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox1;
}

void TextBox2_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox2;
}

One thing to be careful of when using this method is that you don't leave the AcceptButton set to ProcessTextBox1 when TextBox3 becomes focused. I would recommend using either the LostFocus event on the TextBoxes that set the AcceptButton, or create a GotFocus method that all of the controls that don't use a specific AcceptButton call.

How to copy marked text in notepad++

No, as of Notepad++ 5.6.2, this doesn't seem to be possible. Although column selection (Alt+Selection) is possible, multiple selections are obviously not implemented and thus also not supported by the search function.

How to close Browser Tab After Submitting a Form?

try onsubmit="submit(); window.close()"

Calculate the execution time of a method

If you are interested in understand performance, the best answer is to use a profiler.

Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.

Microsoft Excel ActiveX Controls Disabled?

It was KB2553154. Microsoft needs to release a fix. As a developer of Excel applications we can't go to all our clients computers and delete files off them. We are getting blamed for something Microsoft caused.

Single Result from Database by using mySQLi

Use mysqli_fetch_row(). Try this,

$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row   = mysqli_fetch_row($result);

$ssfullname = $row['ssfullname'];
$ssemail    = $row['ssemail'];

Add numpy array as column to Pandas data frame

Consider using a higher dimensional datastructure (a Panel), rather than storing an array in your column:

In [11]: p = pd.Panel({'df': df, 'csc': csc})

In [12]: p.df
Out[12]: 
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

In [13]: p.csc
Out[13]: 
   0  1  2
0  0  1  0
1  0  0  1
2  1  0  0

Look at cross-sections etc, etc, etc.

In [14]: p.xs(0)
Out[14]: 
   csc  df
0    0   1
1    1   2
2    0   3

See the docs for more on Panels.

bootstrap button shows blue outline when clicked

a:focus {
  outline: none;
}

this works for me on BS3

How to make Google Fonts work in IE?

After my investigation, I came up to this solution:

//writing the below line into the top of my style.css file
@import url('https://fonts.googleapis.com/css?family=Assistant:200,300,400,600,700,800&subset=hebrew');

MUST OBSERVE: We must need to write the font-weight correctly of this font. For example: font-weight:900; will not work as we have not included 900 like 200,300,400,600,700,800 into the URL address while importing from Google with the above link. We can add or include 900 to the above URL, but that will work only if the above Google Font has this option while embedding.

What's the best way to send a signal to all members of a process group?

brad's answer is what I'd recommend too, except that you can do away with awk altogether if you use the --ppid option to ps.

for child in $(ps -o pid -ax --ppid $PPID) do ....... done

maxlength ignored for input type="number" in Chrome

I have two ways for you do that

First: Use type="tel", it'll work like type="number" in mobile, and accept maxlength:

<input type="tel" />

Second: Use a little bit of JavaScript:

<!-- maxlength="2" -->
<input type="tel" onKeyDown="if(this.value.length==2 && event.keyCode!=8) return false;" />

Facebook how to check if user has liked page and show content?

You need to write a little PHP code. When user first click tab you can check is he like the page or not. Below is the sample code

include_once("facebook.php");

    // Create our Application instance.
    $facebook = new Facebook(array(
      'appId'  => FACEBOOK_APP_ID,
      'secret' => FACEBOOK_SECRET,
      'cookie' => true,
    ));

$signed_request = $facebook->getSignedRequest();

// Return you the Page like status
$like_status = $signed_request["page"]["liked"];

if($like_status)
{
    echo 'User Liked the page';
    // Place some content you wanna show to user

}else{
    echo 'User do not liked the page';
    // Place some content that encourage user to like the page
}

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

I had the same issue. My problem was it was missing “-Dfile.encoding=UTF8” argument under the JAVA_OPTION in statWeblogic.cmd file in WebLogic server.

MySQL: Error dropping database (errno 13; errno 17; errno 39)

in linux , Just go to "/var/lib/mysql" right click and (open as adminstrator), find the folder corresponding to your database name inside mysql folder and delete it. that's it. Database is dropped.

Identifying and removing null characters in UNIX

Use the following sed command for removing the null characters in a file.

sed -i 's/\x0//g' null.txt

this solution edits the file in place, important if the file is still being used. passing -i'ext' creates a backup of the original file with 'ext' suffix added.

Creating an empty file in C#

File.WriteAllText("path", String.Empty);

or

File.CreateText("path").Close();

angularjs make a simple countdown

As of version 1.3 there's a service in module ng: $interval

function countController($scope, $interval){
    $scope.countDown = 10;    
    $interval(function(){console.log($scope.countDown--)},1000,0);
}??

Use with caution:

Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.

From: Angular's official documentation.

Change hover color on a button with Bootstrap customization

This is the correct way to change btn color.

 .btn-primary:not(:disabled):not(.disabled).active, 
    .btn-primary:not(:disabled):not(.disabled):active, 
    .show>.btn-primary.dropdown-toggle{
        color: #fff;
        background-color: #F7B432;
        border-color: #F7B432;
    }

How to determine if binary tree is balanced?

Wouldn't this work?

return ( ( Math.abs( size( root.left ) - size( root.right ) ) < 2 );

Any unbalanced tree would always fail this.

JavaScript: Object Rename Key

Rename Key but Avoid changing original Objects parameters

oldJson=[{firstName:'s1',lastName:'v1'},
         {firstName:'s2',lastName:'v2'},
         {firstName:'s3',lastName:'v3'}]

newJson = oldJson.map(rec => {
  return {
    'Last Name': rec.lastName,
    'First Name': rec.firstName,  
     }
  })
output: [{Last Name:"v1",First Name:"s1"},
         {Last Name:"v2",First Name:"s2"},
         {Last Name:"v3",First Name:"s3"}]

better to have a new array

How do I check which version of NumPy I'm using?

You can get numpy version using Terminal or a Python code.

In a Terminal (bash) using Ubuntu:

pip list | grep numpy

In python 3.6.7, this code shows the numpy version:

import numpy
print (numpy.version.version)

If you insert this code in the file shownumpy.py, you can compile it:

python shownumpy.py

or

python3 shownumpy.py

I've got this output:

1.16.1

How to loop and render elements in React.js without an array of objects to map?

Here is more functional example with some ES6 features:

'use strict';

const React = require('react');

function renderArticles(articles) {
    if (articles.length > 0) {      
        return articles.map((article, index) => (
            <Article key={index} article={article} />
        ));
    }
    else return [];
}

const Article = ({article}) => {
    return ( 
        <article key={article.id}>
            <a href={article.link}>{article.title}</a>
            <p>{article.description}</p>
        </article>
    );
};

const Articles = React.createClass({
    render() {
        const articles = renderArticles(this.props.articles);

        return (
            <section>
                { articles }
            </section>
        );
    }
});

module.exports = Articles;

PHP - how to create a newline character?

Use the PHP nl2br to get the newlines in a text string..

$text = "Manu is a good boy.(Enter)He can code well.

echo nl2br($text);

Result.

Manu is a good boy.

He can code well.

How to limit the maximum value of a numeric field in a Django model?

Here is the best solution if you want some extra flexibility and don't want to change your model field. Just add this custom validator:

#Imports
from django.core.exceptions import ValidationError      

class validate_range_or_null(object):
    compare = lambda self, a, b, c: a > c or a < b
    clean = lambda self, x: x
    message = ('Ensure this value is between %(limit_min)s and %(limit_max)s (it is %(show_value)s).')
    code = 'limit_value'

    def __init__(self, limit_min, limit_max):
        self.limit_min = limit_min
        self.limit_max = limit_max

    def __call__(self, value):
        cleaned = self.clean(value)
        params = {'limit_min': self.limit_min, 'limit_max': self.limit_max, 'show_value': cleaned}
        if value:  # make it optional, remove it to make required, or make required on the model
            if self.compare(cleaned, self.limit_min, self.limit_max):
                raise ValidationError(self.message, code=self.code, params=params)

And it can be used as such:

class YourModel(models.Model):

    ....
    no_dependents = models.PositiveSmallIntegerField("How many dependants?", blank=True, null=True, default=0, validators=[validate_range_or_null(1,100)])

The two parameters are max and min, and it allows nulls. You can customize the validator if you like by getting rid of the marked if statement or change your field to be blank=False, null=False in the model. That will of course require a migration.

Note: I had to add the validator because Django does not validate the range on PositiveSmallIntegerField, instead it creates a smallint (in postgres) for this field and you get a DB error if the numeric specified is out of range.

Hope this helps :) More on Validators in Django.

PS. I based my answer on BaseValidator in django.core.validators, but everything is different except for the code.

'innerText' works in IE, but not in Firefox

Note that the Element::innerText property will not contain the text which has been hidden by CSS style "display:none" in Google Chrome (as well it will drop the content that has been masked by other CSS technics (including font-size:0, color:transparent, and a few other similar effects that cause the text not to be rendered in any visible way).

Other CSS properties are also considered :

  • First the "display:" style of inner elements is parsed to determine if it delimits a block content (such as "display:block" which is the default of HTML block elements in the browser's builtin stylesheet, and whose behavior as not been overriden by your own CSS style); if so a newline will be inserted in the value of the innerText property. This won't happen with the textContent property.
  • The CSS properties that generate inline contents will also be considered : for example the inline element <br \> that generates an inline newline will also generate an newline in the value of innerText.
  • The "display:inline" style causes no newline either in textContent or innerText.
  • The "display:table" style generates newlines around the table and between table rows, but"display:table-cell" will generate a tabulation character.
  • The "position:absolute" property (used with display:block or display:inline, it does not matter) will also cause a line break to be inserted.
  • Some browsers will also include a single space separation between spans

But Element::textContent will still contain ALL contents of inner text elements independantly of the applied CSS even if they are invisible. And no extra newlines or whitespaces will be generated in textContent, which just ignores all styles and the structure and inline/block or positioned types of inner elements.

A copy/paste operation using mouse selection will discard the hidden text in the plain-text format that is put in the clipboard, so it won't contain everything in the textContent, but only what is within innerText (after whitespace/newline generation as above).

Both properties are then supported in Google Chrome, but their content may then be different. Older browsers still included in innetText everything like what textContent now contains (but their behavior in relation with then generation of whitespaces/newlines was inconsistant).

jQuery will solve these inconsistencies between browsers using the ".text()" method added to the parsed elements it returns via a $() query. Internally, it solves the difficulties by looking into the HTML DOM, working only with the "node" level. So it will return something looking more like the standard textContent.

The caveat is that that this jQuery method will not insert any extra spaces or line breaks that may be visible on screen caused by subelements (like <br />) of the content.

If you design some scripts for accessibility and your stylesheet is parsed for non-aural rendering, such as plugins used to communicate with a Braille reader, this tool should use the textContent if it must include the specific punctuation signs that are added in spans styled with "display:none" and that are typically included in pages (for example for superscripts/subscripts), otherwise the innerText will be very confusive on the Braille reader.

Texts hidden by CSS tricks are now typically ignored by major search engines (that will also parse the CSS of your HTML pages, and will also ignore texts that are not in contrasting colors on the background) using an HTML/CSS parser and the DOM property "innerText" exactly like in modern visual browsers (at least this invisible content will not be indexed so hidden text cannot be used as a trick to force the inclusion of some keywords in the page to check its content) ; but this hidden text will be stil displayed in the result page (if the page was still qualified from the index to be included in results), using the "textContent" property instead of the full HTML to strip the extra styles and scripts.

IF you assign some plain-text in any one of these two properties, this will overwrite the inner markup and styles applied to it (only the assigned element will keep its type, attributes and styles), so both properties will then contain the same content. However, some browsers will now no longer honor the write to innerText, and will only let you overwrite the textContent property (you cannot insert HTML markup when writing to these properties, as HTML special characters will be properly encoded using numeric character references to appear literally, if you then read the innerHTML property after the assignment of innerText or textContent.

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

How to import functions from different js file in a Vue+webpack+vue-loader project

Say I want to import data into a component from src/mylib.js:

var test = {
  foo () { console.log('foo') },
  bar () { console.log('bar') },
  baz () { console.log('baz') }
}

export default test

In my .Vue file I simply imported test from src/mylib.js:

<script> 
  import test from '@/mylib'

  console.log(test.foo())
  ...
</script>

Jquery validation plugin - TypeError: $(...).validate is not a function

I had the same problem. I am using jquery-validation as an npm module and the fix for me was to require the module at the start of my js file:

require('jquery-validation');

Why I cannot cout a string?

If you are using linux system then you need to add

using namespace std;

Below headers

If windows then make sure you put headers correctly #include<iostream.h>

#include<string.h>

Refer this it work perfectly.

#include <iostream>
#include <string>

int main ()
{
std::string str="We think in generalities, but we live in details.";
                                       // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

   std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     
// get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

oracle SQL how to remove time from date

When you convert your string to a date you need to match the date mask to the format in the string. This includes a time element, which you need to remove with truncation:

select 
    p1.PA_VALUE as StartDate,
    p2.PA_VALUE as EndDate
from WP_Work p 
LEFT JOIN PARAMETER p1 on p1.WP_ID=p.WP_ID AND p1.NAME = 'StartDate'
LEFT JOIN PARAMETER p2 on p2.WP_ID=p.WP_ID AND p2.NAME = 'Date_To'
WHERE p.TYPE = 'EventManagement2'
AND trunc(TO_DATE(p1.PA_VALUE, 'DD-MM-YYYY HH24:MI')) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')
AND trunc(TO_DATE(p2.PA_VALUE, 'DD-MM-YYYY HH24:MI')) <= TO_DATE('26/10/2012', 'DD/MM/YYYY')

Composer: The requested PHP extension ext-intl * is missing from your system

just remove them

"ext-intl" : "*"

from your composer.json file.

Because sometimes for some helper functions, the IDE complains that the extension is missing from the composer.json file. Immediately press Alt+Enter to add it to the composer. But that doesn't mean that composer will count them in. The composer will complain next time while doing some operations. So that, we should not blindly type Alt+Enter rather than installing them manually in composer by doing composer install <package-name>.

As I think you have entered it manually, you should remove it, then install it in proper procedure composer install <package-name>

Or else you can run composer update to count that added dependencies in.

Implement division with bit-wise operator

All these solutions are too long. The base idea is to write the quotient (for example, 5=101) as 100 + 00 + 1 = 101.

public static Point divide(int a, int b) {

    if (a < b)
        return new Point(0,a);
    if (a == b)
        return new Point(1,0);
    int q = b;
    int c = 1;
    while (q<<1 < a) {
        q <<= 1;
        c <<= 1;
    }
    Point r = divide(a-q, b);
    return new Point(c + r.x, r.y);
}


public static class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int compare(Point b) {
        if (b.x - x != 0) {
            return x - b.x;
        } else {
            return y - b.y;
        }
    }

    @Override
    public String toString() {
        return " (" + x + " " + y + ") ";
    }
}

How to add a new row to an empty numpy array

In case of adding new rows for array in loop, Assign the array directly for firsttime in loop instead of initialising an empty array.

for i in range(0,len(0,100)):
    SOMECALCULATEDARRAY = .......
    if(i==0):
        finalArrayCollection = SOMECALCULATEDARRAY
    else:
        finalArrayCollection = np.vstack(finalArrayCollection,SOMECALCULATEDARRAY)

This is mainly useful when the shape of the array is unknown

What is function overloading and overriding in php?

I would like to point out over here that Overloading in PHP has a completely different meaning as compared to other programming languages. A lot of people have said that overloading isnt supported in PHP and by the conventional definition of overloading, yes that functionality isnt explicitly available.

However, the correct definition of overloading in PHP is completely different.

In PHP overloading refers to dynamically creating properties and methods using magic methods like __set() and __get(). These overloading methods are invoked when interacting with methods or properties that are not accessible or not declared.

Here is a link from the PHP manual : http://www.php.net/manual/en/language.oop5.overloading.php

Getting list of Facebook friends with latest API

header('Content-type: text/html; charset=utf-8');

input in your page.

How to change angular port from 4200 to any other

The solution worked for me was

ng serve --port 4401    

(You can change 4401 to whatever number you want)

Then launch browser -> http://localhost:4401/

Basically, I was having two Applications and with the help of the above approach now I am able to run both of them simultaneously in my development environment.

Loop until a specific user input

Your code won't work because you haven't assigned anything to n before you first use it. Try this:

def oracle():
    n = None
    while n != 'Correct':
        # etc...

A more readable approach is to move the test until later and use a break:

def oracle():
    guess = 50

    while True:
        print 'Current number = {0}'.format(guess)
        n = raw_input("lower, higher or stop?: ")
        if n == 'stop':
            break
        # etc...

Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.

Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

Automatic exit from Bash shell script on error

Use the set -e builtin:

#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately

Alternatively, you can pass -e on the command line:

bash -e my_script.sh

You can also disable this behavior with set +e.

You may also want to employ all or some of the the -e -u -x and -o pipefail options like so:

set -euxo pipefail

-e exits on error, -u errors on undefined variables, and -o (for option) pipefail exits on command pipe failures. Some gotchas and workarounds are documented well here.

(*) Note:

The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !

(from man bash)

How do I compile and run a program in Java on my Mac?

You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)

From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.

How to hide a div from code (c#)

Give the div "runat="server" and an id and you can reference it in your code behind.

<div runat="server" id="theDiv">

In code behind:

{
    theDiv.Visible = false;
}

In Designer.cs page:

 protected global::System.Web.UI.HtmlControls.HtmlGenericControl theDiv;

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

Get an object attribute

If you need to fetch an object's property dynamically, use the getattr() function: getattr(user, "fullName") - or to elaborate:

user = User()
property = "fullName"
name = getattr(user, property)

Otherwise just use user.fullName.

IIS Config Error - This configuration section cannot be used at this path

Heres what worked for me, had a similar problem on my new laptop which had windows 10.

  • Search for "Turn windows features on or off"
  • Check "Internet Information Services"
  • Check "World Wide Web Services"
  • Check "Application Development Features"
  • Enable all items under this

try again, now it should work.

How do I ignore all files in a folder with a Git repository in Sourcetree?

For Sourcetree users: If you want to ignore a specific folder, just select a file from this folder, right-click on it and do "Ignore...". You will have a pop-up menu where you can ignore "Ignore everything beneath: <YOUR UNWANTED FOLDER>"

First menu

Second menu

If you have the "Ignore" option greyed out, you have to select the "Stop Tracking" option. After that the file will be added to Staged files with a minus sign on red background icon and the file's icon in Unstaged files list will change to a question sign on a violet background. Now in Unstaged files list, the "Ignore" option is enabled again. Just do as described above.

How to negate 'isblank' function

If you're trying to just count how many of your cells in a range are not blank try this:

=COUNTA(range)

Example: (assume that it starts from A1 downwards):

---------    
Something 
---------
Something
---------

---------
Something
---------

---------
Something
---------

=COUNTA(A1:A6) returns 4 since there are two blank cells in there.

How do I convert an object to an array?

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

$array = json_decode(json_encode($response->response->docs), true);

What is the difference between compare() and compareTo()?

Important Answar
String name;
int roll;

public int compare(Object obj1,Object obj2) { // For Comparator interface
    return obj1.compareTo(obj1);
}

public int compareTo(Object obj1) { // For Comparable Interface
    return obj1.compareTo(obj);
}

Here in return obj1.compareTo(obj1) or return obj1.compareTo(obj) statement only take Object; primitive is not allowed. For Example

name.compareTo(obj1.getName()) // Correct Statement.

But

roll.compareTo(obj1.getRoll()) 
// Wrong Statement Compile Time Error Because roll 
// is not an Object Type, it is primitive type.

name is String Object so it worked. If you want to sort roll number of student than use below code.

public int compareTo(Object obj1) { // For Comparable Interface
    Student s = (Student) obj1;
    return rollno - s.getRollno();
}  

or

public int compare(Object obj1,Object obj2) { // For Comparator interface
    Student s1 = (Student) obj1;
    Student s2 = (Student) obj2;
    return s1.getRollno() - s2.getRollno();
}  

C++ Structure Initialization

This feature is called designated initializers. It is an addition to the C99 standard. However, this feature was left out of the C++11. According to The C++ Programming Language, 4th edition, Section 44.3.3.2 (C Features Not Adopted by C++):

A few additions to C99 (compared with C89) were deliberately not adopted in C++:

[1] Variable-length arrays (VLAs); use vector or some form of dynamic array

[2] Designated initializers; use constructors

The C99 grammar has the designated initializers [See ISO/IEC 9899:2011, N1570 Committee Draft - April 12, 2011]

6.7.9 Initialization

initializer:
    assignment-expression
    { initializer-list }
    { initializer-list , }
initializer-list:
    designation_opt initializer
    initializer-list , designationopt initializer
designation:
    designator-list =
designator-list:
    designator
    designator-list designator
designator:
    [ constant-expression ]
    . identifier

On the other hand, the C++11 does not have the designated initializers [See ISO/IEC 14882:2011, N3690 Committee Draft - May 15, 2013]

8.5 Initializers

initializer:
    brace-or-equal-initializer
    ( expression-list )
brace-or-equal-initializer:
    = initializer-clause
    braced-init-list
initializer-clause:
    assignment-expression
    braced-init-list
initializer-list:
    initializer-clause ...opt
    initializer-list , initializer-clause ...opt
braced-init-list:
    { initializer-list ,opt }
    { }

In order to achieve the same effect, use constructors or initializer lists:

Appending a vector to a vector

While saying "the compiler can reserve", why rely on it? And what about automatic detection of move semantics? And what about all that repeating of the container name with the begins and ends?

Wouldn't you want something, you know, simpler?

(Scroll down to main for the punchline)

#include <type_traits>
#include <vector>
#include <iterator>
#include <iostream>

template<typename C,typename=void> struct can_reserve: std::false_type {};

template<typename T, typename A>
struct can_reserve<std::vector<T,A>,void>:
    std::true_type
{};

template<int n> struct secret_enum { enum class type {}; };
template<int n>
using SecretEnum = typename secret_enum<n>::type;

template<bool b, int override_num=1>
using EnableFuncIf = typename std::enable_if< b, SecretEnum<override_num> >::type;
template<bool b, int override_num=1>
using DisableFuncIf = EnableFuncIf< !b, -override_num >;

template<typename C, EnableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t n ) {
  c.reserve(n);
}
template<typename C, DisableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t ) { } // do nothing

template<typename C,typename=void>
struct has_size_method:std::false_type {};
template<typename C>
struct has_size_method<C, typename std::enable_if<std::is_same<
  decltype( std::declval<C>().size() ),
  decltype( std::declval<C>().size() )
>::value>::type>:std::true_type {};

namespace adl_aux {
  using std::begin; using std::end;
  template<typename C>
  auto adl_begin(C&&c)->decltype( begin(std::forward<C>(c)) );
  template<typename C>
  auto adl_end(C&&c)->decltype( end(std::forward<C>(c)) );
}
template<typename C>
struct iterable_traits {
    typedef decltype( adl_aux::adl_begin(std::declval<C&>()) ) iterator;
    typedef decltype( adl_aux::adl_begin(std::declval<C const&>()) ) const_iterator;
};
template<typename C> using Iterator = typename iterable_traits<C>::iterator;
template<typename C> using ConstIterator = typename iterable_traits<C>::const_iterator;
template<typename I> using IteratorCategory = typename std::iterator_traits<I>::iterator_category;

template<typename C, EnableFuncIf< has_size_method<C>::value, 1>... >
std::size_t size_at_least( C&& c ) {
    return c.size();
}

template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 2>... >
std::size_t size_at_least( C&& c ) {
    using std::begin; using std::end;
  return end(c)-begin(c);
};
template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  !std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 3>... >
std::size_t size_at_least( C&& c ) {
  return 0;
};

template < typename It >
auto try_make_move_iterator(It i, std::true_type)
-> decltype(make_move_iterator(i))
{
    return make_move_iterator(i);
}
template < typename It >
It try_make_move_iterator(It i, ...)
{
    return i;
}


#include <iostream>
template<typename C1, typename C2>
C1&& append_containers( C1&& c1, C2&& c2 )
{
  using std::begin; using std::end;
  try_reserve( c1, size_at_least(c1) + size_at_least(c2) );

  using is_rvref = std::is_rvalue_reference<C2&&>;
  c1.insert( end(c1),
             try_make_move_iterator(begin(c2), is_rvref{}),
             try_make_move_iterator(end(c2), is_rvref{}) );

  return std::forward<C1>(c1);
}

struct append_infix_op {} append;
template<typename LHS>
struct append_on_right_op {
  LHS lhs;
  template<typename RHS>
  LHS&& operator=( RHS&& rhs ) {
    return append_containers( std::forward<LHS>(lhs), std::forward<RHS>(rhs) );
  }
};

template<typename LHS>
append_on_right_op<LHS> operator+( LHS&& lhs, append_infix_op ) {
  return { std::forward<LHS>(lhs) };
}
template<typename LHS,typename RHS>
typename std::remove_reference<LHS>::type operator+( append_on_right_op<LHS>&& lhs, RHS&& rhs ) {
  typename std::decay<LHS>::type retval = std::forward<LHS>(lhs.lhs);
  return append_containers( std::move(retval), std::forward<RHS>(rhs) );
}

template<typename C>
void print_container( C&& c ) {
  for( auto&& x:c )
    std::cout << x << ",";
  std::cout << "\n";
};

int main() {
  std::vector<int> a = {0,1,2};
  std::vector<int> b = {3,4,5};
  print_container(a);
  print_container(b);
  a +append= b;
  const int arr[] = {6,7,8};
  a +append= arr;
  print_container(a);
  print_container(b);
  std::vector<double> d = ( std::vector<double>{-3.14, -2, -1} +append= a );
  print_container(d);
  std::vector<double> c = std::move(d) +append+ a;
  print_container(c);
  print_container(d);
  std::vector<double> e = c +append+ std::move(a);
  print_container(e);
  print_container(a);
}

hehe.

Now with move-data-from-rhs, append-array-to-container, append forward_list-to-container, move-container-from-lhs, thanks to @DyP's help.

Note that the above does not compile in clang thanks to the EnableFunctionIf<>... technique. In clang this workaround works.

ASP.NET Core 1.0 on IIS error 502.5

I had the same problem.

To find out the exact source of it I switched on logging in web.config file:

<aspNetCore processPath="dotnet" arguments=".\MyWebService.dll" stdoutLogEnabled="**true**" stdoutLogFile=".\logs\stdout" />

and created logs subfolder in MyWebService root folder.

After restarting IIS and trying to execute API I got an error and it was missing of proper Core Runtime. After downloading an installing DotNetCore.1.0.5_1.1.2-WindowsHosting the error gone.

How to convert PDF files to images

I used PDFiumSharp and ImageSharp in a .NET Standard 2.1 class library.

/// <summary>
/// Saves a thumbnail (jpg) to the same folder as the PDF file, using dimensions 300x423,
/// which corresponds to the aspect ratio of 'A' paper sizes like A4 (ratio h/w=sqrt(2))
/// </summary>
/// <param name="pdfPath">Source path of the pdf file.</param>
/// <param name="thumbnailPath">Target path of the thumbnail file.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void SaveThumbnail(string pdfPath, string thumbnailPath = "", int width = 300, int height = 423)
{
    using var pdfDocument = new PdfDocument(pdfPath);
    var firstPage = pdfDocument.Pages[0];

    using var pageBitmap = new PDFiumBitmap(width, height, true);

    firstPage.Render(pageBitmap);

    var imageJpgPath = string.IsNullOrWhiteSpace(thumbnailPath)
        ? Path.ChangeExtension(pdfPath, "jpg")
        : thumbnailPath;
    var image = Image.Load(pageBitmap.AsBmpStream());

    // Set the background to white, otherwise it's black. https://github.com/SixLabors/ImageSharp/issues/355#issuecomment-333133991
    image.Mutate(x => x.BackgroundColor(Rgba32.White));

    image.Save(imageJpgPath, new JpegEncoder());
}

How to pass a JSON array as a parameter in URL

I would suggest to pass the JSON data in the body as a POST request.But if you still want to pass this as a parameter in URL,you will have to encode your URL like below just for example:-

for ex json is :->{"name":"ABC","id":"1"}

testurl:80/service?data=%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D

for more information on URL encoding refer below

https://en.wikipedia.org/wiki/Percent-encoding

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

How do you push a Git tag to a branch using a refspec?

For pushing a single tag: git push <reponame> <tagname>

For instance, git push production 1.0.0. Tags are not bound to branches, they are bound to commits.

When you want to have the tag's content in the master branch, do that locally on your machine. I would assume that you continued developing in your local master branch. Then just a git push origin master should suffice.

Adding null values to arraylist

You could create Util class:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;
        }

        return list.add(element);
    }
}

And then use it:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);

Angular 2 Routing run in new tab

Late to this one, but I just discovered an alternative way of doing it:

On your template,

<a (click)="navigateAssociates()">Associates</a> 

And on your component.ts, you can use serializeUrl to convert the route into a string, which can be used with window.open()

navigateAssociates() {
  const url = this.router.serializeUrl(
    this.router.createUrlTree(['/page1'])
  );

  window.open(url, '_blank');
}

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

At first you should check major version of compiled problematic .class file, in your case map/CareMonths. See this answer how to do it.

WAS7 uses Java 6 (as said Jacek), and Java 6 uses major version 50, so you have to compile your project with Java 6. How to set proper version of Java compiler depends on your IDE (e.g. Eclipse, IntelliJ) or build tool (e.g. Maven, Ant).

Extract time from moment js object

You can do something like this

var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');

ASP.NET file download from server

Further to Karl Anderson solution, you could put your parameters into session information and then clear them after response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));.

See MSDN page HttpSessionState.Add Method (String, Object) for more information on sessions.

Windows batch script to unhide files hidden by virus

this will unhide all files and folders on your computer

attrib -r -s -h /S /D

ASP.NET: Session.SessionID changes between requests

Another possibility that causes the SessionID to change between requests, even when Session_OnStart is defined and/or a Session has been initialized, is that the URL hostname contains an invalid character (such as an underscore). I believe this is IE specific (not verified), but if your URL is, say, http://server_name/app, then IE will block all cookies and your session information will not be accessible between requests.

In fact, each request will spin up a separate session on the server, so if your page contains multiple images, script tags, etc., then each of those GET requests will result in a different session on the server.

Further information: http://support.microsoft.com/kb/316112

Android Studio Google JAR file causing GC overhead limit exceeded error

This new issue is caused by the latest version of Android.

Go to your project root folder, open gradle.properties, and add the following options:

org.gradle.daemon=true

org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

org.gradle.parallel=true

org.gradle.configureondemand=true

Then add these changes in your build.gradle file:

dexOptions {
        incremental = true
        preDexLibraries = false
        javaMaxHeapSize "4g" // 2g should be also OK
}

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Instead of Windows PowerShell, find the item in the Start Menu called SharePoint 2013 Management Shell:

enter image description here

Regular expression for letters, numbers and - _

[A-Za-z0-9_.-]*

This will also match for empty strings, if you do not want that exchange the last * for an +

Where to place JavaScript in an HTML file?

I would say that it depends of fact what do you planed to achieve with Javascript code:

  • if you planned to insert external your JS script(s), then the best place is in head of the page
  • if you planed to use pages on smartphones, then bottom of page, just before tag.
  • but, if you planned to make combination HTML and JS (dynamically created and populated HTML table, for example) then you must put it where you need it there.

REST response code for invalid data

If the request could not be correctly parsed (including the request entity/body) the appropriate response is 400 Bad Request [1].

RFC 4918 states that 422 Unprocessable Entity is applicable when the request entity is syntactically well-formed, but semantically erroneous. So if the request entity is garbled (like a bad email format) use 400; but if it just doesn't make sense (like @example.com) use 422.

If the issue is that, as stated in the question, user name/email already exists, you could use 409 Conflict [2] with a description of the conflict, and a hint about how to fix it (in this case, "pick a different user name/email"). However in the spec as written, 403 Forbidden [3] can also be used in this case, arguments about HTTP Authorization notwithstanding.

412 Precondition Failed [4] is used when a precondition request header (e.g. If-Match) that was supplied by the client evaluates to false. That is, the client requested something and supplied preconditions, knowing full well that those preconditions might fail. 412 should never be sprung on the client out of the blue, and shouldn't be related to the request entity per se.

why is plotting with Matplotlib so slow?

For the first solution proposed by Joe Kington ( .copy_from_bbox & .draw_artist & canvas.blit), I had to capture the backgrounds after the fig.canvas.draw() line, otherwise the background had no effect and I got the same result as you mentioned. If you put it after the fig.show() it still does not work as proposed by Michael Browne.

So just put the background line after the canvas.draw():

[...]
fig.show()

# We need to draw the canvas before we start animating...
fig.canvas.draw()

# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]

How to scroll to bottom in a ScrollView on activity startup

Right after you append data to the view add this single line:

yourScrollview.fullScroll(ScrollView.FOCUS_DOWN);

How to prevent a click on a '#' link from jumping to top of page?

You can also return false after processing your jquery.

Eg.

$(".clickableAnchor").live(
    "click",
    function(){
        //your code
        return false; //<- prevents redirect to href address
    }
);

Git asks for username every time I push

  1. $ git config credential.helper store

  2. $ git push/push https://github.com/xxx.git

  3. Then enter your user name and password.

  4. Done

Javascript Debugging line by line using Google Chrome

...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...


For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:

enter image description here

When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.

More info:

Find all special characters in a column in SQL Server 2008

Negatives are your friend here:

SELECT Col1
FROM TABLE
WHERE Col1 like '%[^a-Z0-9]%'

Which says that you want any rows where Col1 consists of any number of characters, then one character not in the set a-Z0-9, and then any number of characters.

If you have a case sensitive collation, it's important that you use a range that includes both upper and lower case A, a, Z and z, which is what I've given (originally I had it the wrong way around. a comes before A. Z comes after z)


Or, to put it another way, you could have written your original WHERE as:

Col1 LIKE '[!@#$%]'

But, as you observed, you'd need to know all of the characters to include in the [].

How do you migrate an IIS 7 site to another server?

I can't comment up thread due to lack of rep. Another commenter stated they couldn't migrate from a lower version to a higher version of IIS. This is true if you don't merge some files, but if you do you can as I just migrated my IIS 7.5 site to IIS 8.0 using the answer posted by chews.

When the export is created (II7.5), there are two key files (administration.config and applicationHost.config) which have references to resources on the IIS7.5 server. For example, a DLL will be referred with a public key and version specific to 7.5. These are NOT the same on the IIS8 server. The feature configuration may differ as well (I ensured mine were identical). There are some new features in 8 which will never exist in 7.5.

If you are brave enough to merge the two files - it will work. I had to uninstall IIS once because I messed it up, but got it the second time.

I used a merge tool (Beyond Compare) and without something equivalent it would be a huge PITA - but was pretty easy with a good diff tool (five minutes).

To do the merge, the 8.0 files need to be diffed against the exported 7.5 files BEFORE an import is attempted. For the most part, the 8.0 files need to overwrite the server specific stuff in the exported 7.5 files, while leaving the site/app pool specific stuff.

I found that administration.config was almost identical, sans the version info of many entries. This one was easy.

The applicationHost.config has a lot more differences. Some entries are ordered differently, but otherwise identical, so you will have to pick through each difference and figure it out.

I put my 7.5 export files in the System32\inetsrv\config\Export folder prior to merging.

I merged FROM folder System32\inetsrv\config to folder System32\inetsrv\config\Export for both files I mentioned above. I pushed over everything in the FROM files except site specific tags/elements (e.g. applicationPools, customMetadata, sites, authentication). Of special note, there were also many site specific "location" tag blocks that I had to keep, but the new server had its own "location" tag block with server specific defaults that has to be kept.

Lastly, do note that if you use service accounts, these cached passwords are junk and will have to be re-entered for your app pools. None of my sites worked initially, but all that was required was re-entering the passwords for all my app pools and I was up and running.

If someone who can comment mention this post down thread - it will probably help someone else like me who has many sites on one server with complicated configurations.

Regards,

Stuart

Finding local maxima/minima with Numpy in a 1D numpy array

For curves with not too much noise, I recommend the following small code snippet:

from numpy import *

# example data with some peaks:
x = linspace(0,4,1e3)
data = .2*sin(10*x)+ exp(-abs(2-x)**2)

# that's the line, you need:
a = diff(sign(diff(data))).nonzero()[0] + 1 # local min+max
b = (diff(sign(diff(data))) > 0).nonzero()[0] + 1 # local min
c = (diff(sign(diff(data))) < 0).nonzero()[0] + 1 # local max


# graphical output...
from pylab import *
plot(x,data)
plot(x[b], data[b], "o", label="min")
plot(x[c], data[c], "o", label="max")
legend()
show()

The +1 is important, because diff reduces the original index number.

generate days from date range

Generate dates between two date fields

If you are aware with SQL CTE query, then this solution will helps you to solve your question

Here is example

We have dates in one table

Table Name: “testdate”

STARTDATE   ENDDATE
10/24/2012  10/24/2012
10/27/2012  10/29/2012
10/30/2012  10/30/2012

Require Result:

STARTDATE
10/24/2012
10/27/2012
10/28/2012
10/29/2012
10/30/2012

Solution:

WITH CTE AS
  (SELECT DISTINCT convert(varchar(10),StartTime, 101) AS StartTime,
                   datediff(dd,StartTime, endTime) AS diff
   FROM dbo.testdate
   UNION ALL SELECT StartTime,
                    diff - 1 AS diff
   FROM CTE
   WHERE diff<> 0)
SELECT DISTINCT DateAdd(dd,diff, StartTime) AS StartTime
FROM CTE

Explanation: CTE Recursive query explanation

  • First part of query:

    SELECT DISTINCT convert(varchar(10), StartTime, 101) AS StartTime, datediff(dd, StartTime, endTime) AS diff FROM dbo.testdate

    Explanation: firstcolumn is “startdate”, second column is difference of start and end date in days and it will be consider as “diff” column

  • Second part of query:

    UNION ALL SELECT StartTime, diff-1 AS diff FROM CTE WHERE diff<>0

    Explanation: Union all will inherit result of above query until result goes null, So “StartTime” result is inherit from generated CTE query, and from diff, decrease - 1, so its looks like 3, 2, and 1 until 0

For example

STARTDATE   DIFF
10/24/2012  0
10/27/2012  0
10/27/2012  1
10/27/2012  2
10/30/2012  0

Result Specification

STARTDATE       Specification
10/24/2012  --> From Record 1
10/27/2012  --> From Record 2
10/27/2012  --> From Record 2
10/27/2012  --> From Record 2
10/30/2012  --> From Record 3
  • 3rd Part of Query

    SELECT DISTINCT DateAdd(dd,diff, StartTime) AS StartTime FROM CTE

    It will add day “diff” in “startdate” so result should be as below

Result

STARTDATE
10/24/2012
10/27/2012
10/28/2012
10/29/2012
10/30/2012

qmake: could not find a Qt installation of ''

For my Qt 5.7, open QtCreator, go to Tools -> Options -> Build & Run -> Qt Versions gave me the location of qmake.

How to resolve TypeError: Cannot convert undefined or null to object

If you're using Laravel, my problem was in the name of my Route. Instead:

Route::put('/reason/update', 'REASONController@update');

I wrote:

Route::put('/reason/update', 'RESONController@update');

and when I fixed the controller name, the code worked!

How to return a boolean method in java?

You can also do this, for readability's sake

boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());

if(!passwordVerified ){
    txtaError.setEditable(true);
    txtaError.setText("*Password didn't match!");
    txtaError.setForeground(Color.red);
    txtaError.setEditable(false);
}else{
    addNewUser();
}
return passwordVerified;

Relational Database Design Patterns?

After many years of database development I can say there are some no goes and some question that you should answer before you begin:

questions:

  • Do you want use in the future another DBMS? If yes then does not use to special SQL stuff of the current DBMS. Remove logic in your application.

Does not use:

  • white spaces in table names and column names
  • Non Ascii characters in table and column names
  • binding to a specific lower case or upper case. And never use 2 tables or columns that differ only with lower case and upper case.
  • does not use SQL keywords for tables or columns names like "FROM", "BETWEEN", "DELETE", etc

recomendations:

  • Use NVARCHAR or equivalents for unicode support then you have no problems with codepages.
  • Give every column a unique name. This make it easer on join to select the column. It is very difficult if every table has a column "ID" or "Name" or "Description". Use XyzID and AbcID.
  • Use a resource bundle or equals for complex SQL expressions. It make it easer to switch to another DBMS.
  • Does not cast hard on any data type. Another DBMS can not have this data type. FOr example Oracle daes not have a SMALLINT only a number.

I hope this is a good starting point.

Subprocess changing directory

You want to use an absolute path to the executable, and use the cwd kwarg of Popen to set the working directory. See the docs.

If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.

Java: how do I check if a Date is within a certain range?

An easy way is to convert the dates into milliseconds after January 1, 1970 (use Date.getTime()) and then compare these values.

SQL Server 2008: how do I grant privileges to a username?

If you really want them to have ALL rights:

use YourDatabase
go
exec sp_addrolemember 'db_owner', 'UserName'
go

How to read an external local JSON file in JavaScript?

You cannot make a AJAX call to a local resource as the request is made using HTTP.

A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.

In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():

http://api.jquery.com/jQuery.getJSON/

Modal width (increase)

For responsive answer.

@media (min-width: 992px) {
  .modal-dialog {
    max-width: 80%;
  }
}

Getting JSONObject from JSONArray

JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
    JSONObject object = array.getJSONObject(n);
    // do some stuff....
}

What is the difference between JVM, JDK, JRE & OpenJDK?

JDK (Java Development Kit) :

  • contains tools needed to develop the Java programs.
  • You need JDK, if at all you want to write your own programs, and to compile them.
  • JDK is mainly targeted for java development.

JRE (Java Runtime Environment)

Java Runtime Environment contains JVM, class libraries, and other supporting files. JRE is targeted for execution of Java files.

JVM (Java Virtual Machine)

The JVM interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… Java Virtual Machine provides a platform-independent way of executing code.

Fatal error: Class 'PHPMailer' not found

I suggest you look into getting composer. https://getcomposer.org Composer makes getting third-party libraries a LOT easier and using a single autoloader for all of them. It also standardizes on where all your dependencies are located, along with some automatization capabilities.

Download https://getcomposer.org/composer.phar to C:\Inetpub\wwwroot\php

Delete your C:\Inetpub\wwwroot\php\PHPMailer\ directory.

Use composer.phar to get the phpmailer package using the command line to execute

cd C:\Inetpub\wwwroot\php
php composer.phar require phpmailer/phpmailer

After it is finished it will create a C:\Inetpub\wwwroot\php\vendor directory along with all of the phpmailer files and generate an autoloader.

Next in your main project configuration file you need to include the autoload file.

require_once 'C:\Inetpub\wwwroot\php\vendor\autoload.php';

The vendor\autoload.php will include the information for you to use $mail = new \PHPMailer;

Additional information on the PHPMailer package can be found at https://packagist.org/packages/phpmailer/phpmailer

How to create roles in ASP.NET Core and assign them to users?

I have created an action in the Accounts controller that calls a function to create the roles and assign the Admin role to the default user. (You should probably remove the default user in production):

    private async Task CreateRolesandUsers()
    {  
        bool x = await _roleManager.RoleExistsAsync("Admin");
        if (!x)
        {
            // first we create Admin rool    
            var role = new IdentityRole();
            role.Name = "Admin";
            await _roleManager.CreateAsync(role);

            //Here we create a Admin super user who will maintain the website                   

            var user = new ApplicationUser();
            user.UserName = "default";
            user.Email = "[email protected]";

            string userPWD = "somepassword";

            IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);

            //Add default User to Role Admin    
            if (chkUser.Succeeded)
            {
                var result1 = await _userManager.AddToRoleAsync(user, "Admin");
            }
        }

        // creating Creating Manager role     
        x = await _roleManager.RoleExistsAsync("Manager");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Manager";
            await _roleManager.CreateAsync(role);
        }

        // creating Creating Employee role     
        x = await _roleManager.RoleExistsAsync("Employee");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Employee";
            await _roleManager.CreateAsync(role);
        }
  }

After you could create a controller to manage roles for the users.

Return single column from a multi-dimensional array

array_map is a call back function, where you can play with the passed array. this should work.

$str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

I experienced a similar issue with android studio 2.2. Re-installing a new system image didnt resolve for me. Then found this solution on this link.

unchecking the Enable ADB Integration option and checking it back seem to resolve it for me. I hope this helps someone out there.

How to list active / open connections in Oracle?

select
  username,
  osuser,
  terminal,
  utl_inaddr.get_host_address(terminal) IP_ADDRESS
from
  v$session
where
  username is not null
order by
  username,
  osuser;

Pass Hidden parameters using response.sendRedirect()

TheNewIdiot's answer successfully explains the problem and the reason why you can't send attributes in request through a redirect. Possible solutions:

  1. Using forwarding. This will enable that request attributes could be passed to the view and you can use them in form of ServletRequest#getAttribute or by using Expression Language and JSTL. Short example (reusing TheNewIdiot's answer] code).

    Controller (your servlet)

    request.setAttribute("message", "Hello world");
    RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);
    

    View (your JSP)

    Using scriptlets:

    <%
        out.println(request.getAttribute("message"));
    %>
    

    This is just for information purposes. Scriptlets usage must be avoided: How to avoid Java code in JSP files?. Below there is the example using EL and JSTL.

    <c:out value="${message}" />
    
  2. If you can't use forwarding (because you don't like it or you don't feel it that way or because you must use a redirect) then an option would be saving a message as a session attribute, then redirect to your view, recover the session attribute in your view and remove it from session. Remember to always have your user session with only relevant data. Code example

    Controller

    //if request is not from HttpServletRequest, you should do a typecast before
    HttpSession session = request.getSession(false);
    //save message in session
    session.setAttribute("helloWorld", "Hello world");
    response.sendRedirect("/content/test.jsp");
    

    View

    Again, showing this using scriptlets and then EL + JSTL:

    <%
        out.println(session.getAttribute("message"));
        session.removeAttribute("message");
    %>
    
    <c:out value="${sessionScope.message}" />
    <c:remove var="message" scope="session" />