Programs & Examples On #T4mvc

T4MVC is an open source utility for Microsoft ASP.NET MVC. It allows replacing magic strings in Views, Controllers and Links to content with strong names/types.

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

Redirecting from HTTP to HTTPS with PHP

On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:

if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

Laravel - Forbidden You don't have permission to access / on this server

For my case was encountering this issue with Laravel 6.x and managed to sort it out by installing an SSL Certificate. Tried playing around with .htaccess but never worked. I'm using the default Laravel 6.x .htaccess file which has the following contents

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

How to check if a string contains text from an array of substrings in JavaScript?

building on T.J Crowder's answer

using escaped RegExp to test for "at least once" occurrence, of at least one of the substrings.

_x000D_
_x000D_
function buildSearch(substrings) {_x000D_
  return new RegExp(_x000D_
    substrings_x000D_
    .map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})_x000D_
    .join('{1,}|') + '{1,}'_x000D_
  );_x000D_
}_x000D_
_x000D_
_x000D_
var pattern = buildSearch(['hello','world']);_x000D_
_x000D_
console.log(pattern.test('hello there'));_x000D_
console.log(pattern.test('what a wonderful world'));_x000D_
console.log(pattern.test('my name is ...'));
_x000D_
_x000D_
_x000D_

Check if an object exists

You can also use get_object_or_404(), it will raise a Http404 if the object wasn't found:

user_pass = log_in(request.POST) #form class
if user_pass.is_valid():
    cleaned_info = user_pass.cleaned_data
    user_object = get_object_or_404(User, email=cleaned_info['username'])
    # User object found, you are good to go!
    ...

Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :

blob.getBytes

use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0)
blob.free();

Difference between jar and war in Java

You add web components to a J2EE application in a package called a web application archive (WAR), which is a JAR similar to the package used for Java class libraries. A WAR usually contains other resources besides web components, including:

  • Server-side utility classes (database beans, shopping carts, and so on).
  • Static web resources (HTML, image, and sound files, and so on)
  • Client-side classes (applets and utility classes)

A WAR has a specific hierarchical directory structure. The top-level directory of a WAR is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static web resources are stored.

(source)

So a .war is a .jar, but it contains web application components and is laid out according to a specific structure. A .war is designed to be deployed to a web application server such as Tomcat or Jetty or a Java EE server such as JBoss or Glassfish.

How to configure a HTTP proxy for svn

In TortoiseSVN you can configure the proxy server under Settings=> Network

DateTimePicker: pick both date and time

I'm afraid the DateTimePicker control doesn't have the ability to do those things. It's a pretty basic (and frustrating!) control. Your best option may be to find a third-party control that does what you want.

For the option of typing the date and time manually, you could build a custom component with a TextBox/DateTimePicker combination to accomplish this, and it might work reasonably well, if third-party controls are not an option.

Validating file types by regular expression

You can embed case insensitity into the regular expression like so:

\.(?i:)(?:jpg|gif|doc|pdf)$

Difference between ref and out parameters in .NET

They are subtly different.

An out parameter does not need to be initialized by the callee before being passed to the method. Therefore, any method with an out parameter

  • Cannot read the parameter before assigning a value to it
  • Must assign a value to it before returning

This is used for a method which needs to overwrite its argument regardless of its previous value.


A ref parameter must be initialized by the callee before passing it to the method. Therefore, any method with a ref parameter

  • Can inspect the value before assigning it
  • Can return the original value, untouched

This is used for a method which must (e.g.) inspect its value and validate it or normalize it.

how to use getSharedPreferences in android

//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;  
prefsEditor = myPrefs.edit();  
//strVersionName->Any value to be stored  
prefsEditor.putString("STOREDVALUE", strVersionName);  
prefsEditor.commit();

//Get Preferenece  
SharedPreferences myPrefs;    
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);  
String StoredValue=myPrefs.getString("STOREDVALUE", "");

Try this..

Automating running command on Linux from Windows using PuTTY

In case you are using Key based authentication, using saved Putty session seems to work great, for example to run a shell script on a remote server(In my case an ec2).Saved configuration will take care of authentication.

C:\Users> plink saved_putty_session_name path_to_shell_file/filename.sh

Please remember if you save your session with name like(user@hostname), this command would not work as it will be treated as part of the remote command.

PersistenceContext EntityManager injection NullPointerException

An entity manager can only be injected in classes running inside a transaction. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.

Since your TestService is not an EJB, the annotation @PersistenceContext is simply ignored. Not only that, in JavaEE 5, it's not possible to inject an EntityManager nor an EntityManagerFactory in a JAX-RS Service. You have to go with a JavaEE 6 server (JBoss 6, Glassfish 3, etc).

Here's an example of injecting an EntityManagerFactory:

package com.test.service;

import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;

@Path("/service")
public class TestService {

    @PersistenceUnit(unitName = "test")
    private EntityManagerFactory entityManagerFactory;

    @GET
    @Path("/get")
    @Produces("application/json")
    public List get() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            return entityManager.createQuery("from TestEntity").getResultList();
        } finally {
            entityManager.close();
        }
    }
}

The easiest way to go here is to declare your service as a EJB 3.1, assuming you're using a JavaEE 6 server.

Related question: Inject an EJB into JAX-RS (RESTful service)

make a phone call click on a button

Also good to check is telephony supported on device

private boolean isTelephonyEnabled(){
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
return tm != null && tm.getSimState()==TelephonyManager.SIM_STATE_READY
}

mat-form-field must contain a MatFormFieldControl

I had same issue

issue is simple

only you must import two modules to your project

MatFormFieldModule MatInputModule

Should I use <i> tag for icons instead of <span>?

Quentin's answer clearly states that i tag should not be used to define icons.

But, Holly suggested that span has no meaning in itself and voted in favor of i instead of span tag.

Few suggested to use img as it's semantic and contains alt tag. But, we should not also use img because even empty src sends a request to server. Read here

I think, the correct way would be,

<span class="icon-fb" role="img" aria-label="facebook"></span>

This solves the issue of no alt tag in span and makes it accessible to vision-impaired users. It's semantic and not misusing ( hacking ) any tag.

What exactly is LLVM?

The LLVM Compiler Infrastructure is particularly useful for performing optimizations and transformations on code. It also consists of a number of tools serving distinct usages. llvm-prof is a profiling tool that allows you to do profiling of execution in order to identify program hotspots. Opt is an optimization tool that offers various optimization passes (dead code elimination for instance).

Importantly LLVM provides you with the libraries, to write your own Passes. For instance if you require to add a range check on certain arguments that are passed into certain functions of a Program, writing a simple LLVM Pass would suffice.

For more information on writing your own Pass, check this http://llvm.org/docs/WritingAnLLVMPass.html

How can I export Excel files using JavaScript?

There is an interesting project on github called Excel Builder (.js) that offers a client-side way of downloading Excel xlsx files and includes options for formatting the Excel spreadsheet.
https://github.com/stephenliberty/excel-builder.js

You may encounter both browser and Excel compatibility issues using this library, but under the right conditions, it may be quite useful.

Another github project with less Excel options but less worries about Excel compatibility issues can be found here: ExcellentExport.js
https://github.com/jmaister/excellentexport

If you are using AngularJS, there is ng-csv:
a "Simple directive that turns arrays and objects into downloadable CSV files".

Which version of MVC am I using?

typeof(Controller).Assembly.GetName().Version

Gives the current version programmatically.

Find stored procedure by name

For SQL Server version 9.0 (2005), you can use the code below:

select * 
from 
syscomments c
inner join sys.procedures p on p.object_id = c.id
where 
p.name like '%usp_ConnectionsCount%';

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

EDIT: The new Design Support Library supports this and the previous method is no longer required.

This can now be achieved using the new Android Design Support Library.

You can see the Cheesesquare sample app by Chris Banes which demos all the new features.


Previous method:

Since there is no complete solution posted, here is the way I achieved the desired result.

First include a ScrimInsetsFrameLayout in your project.

/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* A layout that draws something in the insets passed to 
* {@link #fitSystemWindows(Rect)}, i.e. the area above UI chrome
* (status and navigation bars, overlay action bars).
*/
public class ScrimInsetsFrameLayout extends FrameLayout {
    private Drawable mInsetForeground;

    private Rect mInsets;
    private Rect mTempRect = new Rect();
    private OnInsetsCallback mOnInsetsCallback;

    public ScrimInsetsFrameLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ScrimInsetsFrameLayout(
        Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.ScrimInsetsView, defStyle, 0);
        if (a == null) {
            return;
        }
        mInsetForeground = a.getDrawable(
            R.styleable.ScrimInsetsView_insetForeground);
        a.recycle();

        setWillNotDraw(true);
    }

    @Override
    protected boolean fitSystemWindows(Rect insets) {
        mInsets = new Rect(insets);
        setWillNotDraw(mInsetForeground == null);
        ViewCompat.postInvalidateOnAnimation(this);
        if (mOnInsetsCallback != null) {
            mOnInsetsCallback.onInsetsChanged(insets);
        }
        return true; // consume insets
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        int width = getWidth();
        int height = getHeight();
        if (mInsets != null && mInsetForeground != null) {
            int sc = canvas.save();
            canvas.translate(getScrollX(), getScrollY());

            // Top
            mTempRect.set(0, 0, width, mInsets.top);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Bottom
            mTempRect.set(0, height - mInsets.bottom, width, height);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Left
            mTempRect.set(
                0, 
                mInsets.top, 
                mInsets.left, 
                height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Right
            mTempRect.set(
                width - mInsets.right, 
                mInsets.top, width, 
                height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            canvas.restoreToCount(sc);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(this);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(null);
        }
    }

    /**
     * Allows the calling container to specify a callback for custom 
     * processing when insets change (i.e. when {@link #fitSystemWindows(Rect)}
     * is called. This is useful for setting padding on UI elements 
     * based on UI chrome insets (e.g. a Google Map or a ListView). 
     * When using with ListView or GridView, remember to set
     * clipToPadding to false.
     */
    public void setOnInsetsCallback(OnInsetsCallback onInsetsCallback) {
        mOnInsetsCallback = onInsetsCallback;
    }

    public static interface OnInsetsCallback {
        public void onInsetsChanged(Rect insets);
    }
}

Then create a styleable so that the insetForeground can be set.

values/attrs.xml

<declare-styleable name="ScrimInsetsView">
    <attr name="insetForeground" format="reference|color" />
</declare-styleable>

Update your activity's xml file and make sure android:fitsSystemWindows is set to true on both the DrawerLayout as well as the ScrimInsetsFrameLayout.

layout/activity_main.xml

<android.support.v4.widget.DrawerLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <!-- The main content view -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- Your main content -->

    </LinearLayout>

    <!-- The navigation drawer -->
    <com.example.app.util.ScrimInsetsFrameLayout 
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/scrimInsetsFrameLayout"
        android:layout_width="320dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/white"
        android:elevation="10dp"
        android:fitsSystemWindows="true"
        app:insetForeground="#4000">

        <!-- Your drawer content -->

    </com.example.app.util.ScrimInsetsFrameLayout>

</android.support.v4.widget.DrawerLayout>

Inside the onCreate method of your activity set the status bar background color on the drawer layout.

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // ...

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mDrawerLayout.setStatusBarBackgroundColor(
        getResources().getColor(R.color.primary_dark));
}

Finally update your app's theme so that the DrawerLayout is behind the status bar.

values-v21/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

Result:

How can I define a composite primary key in SQL?

Just for clarification: a table can have at most one primary key. A primary key consists of one or more columns (from that table). If a primary key consists of two or more columns it is called a composite primary key. It is defined as follows:

CREATE TABLE voting (
  QuestionID NUMERIC,
  MemberID NUMERIC,
  PRIMARY KEY (QuestionID, MemberID)
);

The pair (QuestionID,MemberID) must then be unique for the table and neither value can be NULL. If you do a query like this:

SELECT * FROM voting WHERE QuestionID = 7

it will use the primary key's index. If however you do this:

SELECT * FROM voting WHERE MemberID = 7

it won't because to use a composite index requires using all the keys from the "left". If an index is on fields (A,B,C) and your criteria is on B and C then that index is of no use to you for that query. So choose from (QuestionID,MemberID) and (MemberID,QuestionID) whichever is most appropriate for how you will use the table.

If necessary, add an index on the other:

CREATE UNIQUE INDEX idx1 ON voting (MemberID, QuestionID);

What is the Java equivalent of PHP var_dump?

Your alternatives are to override the toString() method of your object to output its contents in a way that you like, or to use reflection to inspect the object (in a way similar to what debuggers do).

The advantage of using reflection is that you won't need to modify your individual objects to be "analysable", but there is added complexity and if you need nested object support you'll have to write that.

This code will list the fields and their values for an Object "o"

Field[] fields = o.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
    System.out.println(fields[i].getName() + " - " + fields[i].get(o));
}

Producer/Consumer threads using a Queue

Java 5+ has all the tools you need for this kind of thing. You will want to:

  1. Put all your Producers in one ExecutorService;
  2. Put all your Consumers in another ExecutorService;
  3. If necessary, communicate between the two using a BlockingQueue.

I say "if necessary" for (3) because from my experience it's an unnecessary step. All you do is submit new tasks to the consumer executor service. So:

final ExecutorService producers = Executors.newFixedThreadPool(100);
final ExecutorService consumers = Executors.newFixedThreadPool(100);
while (/* has more work */) {
  producers.submit(...);
}
producers.shutdown();
producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
consumers.shutdown();
consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

So the producers submit directly to consumers.

How can I install a CPAN module into a local directory?

I had a similar problem, where I couldn't even install local::lib

I created an installer that installed the module somewhere relative to the .pl files

The install goes like:

perl Makefile.PL PREFIX=./modulos
make
make install

Then, in the .pl file that requires the module, which is in ./

use lib qw(./modulos/share/perl/5.8.8/); # You may need to change this path
use module::name;

The rest of the files (makefile.pl, module.pm, etc) require no changes.

You can call the .pl file with just

perl file.pl

Can I get Unix's pthread.h to compile in Windows?

There are, as i recall, two distributions of the gnu toolchain for windows: mingw and cygwin.

I'd expect cygwin work - a lot of effort has been made to make that a "stadard" posix environment.

The mingw toolchain uses msvcrt.dll for its runtime and thus will probably expose msvcrt's "thread" api: _beginthread which is defined in <process.h>

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

I Understood your problem add this dependency in your pom.xml your problem will be solved,

https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38

Could not create the Java virtual machine

The problem got resolved when I edited the file /etc/bashrc with same contents as in /etc/profiles and in /etc/profiles.d/limits.sh and did a re-login.

Using jquery to get element's position relative to viewport

I found that the answer by cballou was no longer working in Firefox as of Jan. 2014. Specifically, if (self.pageYOffset) didn't trigger if the client had scrolled right, but not down - because 0 is a falsey number. This went undetected for a while because Firefox supported document.body.scrollLeft/Top, but this is no longer working for me (on Firefox 26.0).

Here's my modified solution:

var getPageScroll = function(document_el, window_el) {
  var xScroll = 0, yScroll = 0;
  if (window_el.pageYOffset !== undefined) {
    yScroll = window_el.pageYOffset;
    xScroll = window_el.pageXOffset;
  } else if (document_el.documentElement !== undefined && document_el.documentElement.scrollTop) {
    yScroll = document_el.documentElement.scrollTop;
    xScroll = document_el.documentElement.scrollLeft;
  } else if (document_el.body !== undefined) {// all other Explorers
    yScroll = document_el.body.scrollTop;
    xScroll = document_el.body.scrollLeft;
  }
  return [xScroll,yScroll];
};

Tested and working in FF26, Chrome 31, IE11. Almost certainly works on older versions of all of them.

Executing a stored procedure within a stored procedure

T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want.

CREATE PROCEDURE SP1 AS
   EXEC SP2
   PRINT 'Done'

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<form action="Delegate_update.php" method="post">
  Name
  <input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
  Username
  <input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
  Password
  <input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
  <input type="submit" name= "submit" value="Update">
</form>

look into this

Get img thumbnails from Vimeo?

function parseVideo(url) {
    // - Supported YouTube URL formats:
    //   - http://www.youtube.com/watch?v=My2FRPA3Gf8
    //   - http://youtu.be/My2FRPA3Gf8
    //   - https://youtube.googleapis.com/v/My2FRPA3Gf8
    // - Supported Vimeo URL formats:
    //   - http://vimeo.com/25451551
    //   - http://player.vimeo.com/video/25451551
    // - Also supports relative URLs:
    //   - //player.vimeo.com/video/25451551

    url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);

    if (RegExp.$3.indexOf('youtu') > -1) {
        var type = 'youtube';
    } else if (RegExp.$3.indexOf('vimeo') > -1) {
        var type = 'vimeo';
    }

    return {
        type: type,
        id: RegExp.$6
    };
}

function getVideoThumbnail(url, cb) {
    var videoObj = parseVideo(url);
    if (videoObj.type == 'youtube') {
        cb('//img.youtube.com/vi/' + videoObj.id + '/maxresdefault.jpg');
    } else if (videoObj.type == 'vimeo') {
        $.get('http://vimeo.com/api/v2/video/' + videoObj.id + '.json', function(data) {
            cb(data[0].thumbnail_large);
        });
    }
}

Passing data to components in vue.js

-------------Following is applicable only to Vue 1 --------------

Passing data can be done in multiple ways. The method depends on the type of use.


If you want to pass data from your html while you add a new component. That is done using props.

<my-component prop-name="value"></my-component>

This prop value will be available to your component only if you add the prop name prop-name to your props attribute.


When data is passed from a component to another component because of some dynamic or static event. That is done by using event dispatchers and broadcasters. So for example if you have a component structure like this:

<my-parent>
    <my-child-A></my-child-A>
    <my-child-B></my-child-B>
</my-parent>

And you want to send data from <my-child-A> to <my-child-B> then in <my-child-A> you will have to dispatch an event:

this.$dispatch('event_name', data);

This event will travel all the way up the parent chain. And from whichever parent you have a branch toward <my-child-B> you broadcast the event along with the data. So in the parent:

events:{
    'event_name' : function(data){
        this.$broadcast('event_name', data);
    },

Now this broadcast will travel down the child chain. And at whichever child you want to grab the event, in our case <my-child-B> we will add another event:

events: {
    'event_name' : function(data){
        // Your code. 
    },
},

The third way to pass data is through parameters in v-links. This method is used when components chains are completely destroyed or in cases when the URI changes. And i can see you already understand them.


Decide what type of data communication you want, and choose appropriately.

How to update all MySQL table rows at the same time?

The default null value for a field is "not null". So you must set it to "null" before you can set that field value for any record to null. Then you can:

UPDATE `myTable` SET `myField` = null

Codesign error: Provisioning profile cannot be found after deleting expired profile

To achieve Brad's solution entirely in Terminal, use these commands

  1. cd [Xcode project parent]
  2. vi [Xcode project name].xcodeproj/project.pbxproj
  3. /[offending provisioning profile] [Enter]
  4. dd - delete the entire line
  5. Press n until no more are found
  6. Ctrl+x to save and close

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

@SpringBootApplication
@MapperScan("com.developer.project.mapper")

public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

arranging div one below the other

Set the main div CSS to somthing like:

<style>
    .wrapper{
        display:flex;
        flex-direction: column;
    }
</style>

<div id="wrapper">
        <div id="inner1">This is inner div 1</div>
        <div id="inner2">This is inner div 2</div>
</div>

For more flexbox CSS refer: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

How to capture Curl output to a file?

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

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

How can I make a float top with CSS?

There is no float:top, only float:left and float:right

If you wish to display div underneath each other you would have to do:

<div style="float:left;clear:both"></div>
<div style="float:left;clear:both"></div>

Angular 2: How to write a for loop, not a foreach loop

If you want to use the object of ith term and input it to another component in each iteration then:

<table class="table table-striped table-hover">
  <tr>
    <th> Blogs </th>
  </tr>
  <tr *ngFor="let blogEl of blogs">
    <app-blog-item [blog]="blogEl"> </app-blog-item>
  </tr>
</table>

YouTube iframe embed - full screen

jut add allowfullscreen="true" to iframe

  <iframe src="URL here" allowfullscreen="true"> </iframe>

Using port number in Windows host file

-You can use any free address in the network 127.0.0.0/8 , in my case needed this for python flask and this is what I have done : add this line in the hosts file (you can find it is windows under : C:\Windows\System32\drivers\etc ) :

127.0.0.5 flask.dev
  • Make sure the port is the default port "80" in my case this is what in the python flask: app.run("127.0.0.5","80")

  • now run your code and browse flask.dev

Java Byte Array to String to Byte Array

Use the below code API to convert bytecode as string to Byte array.

 byte[] byteArray = DatatypeConverter.parseBase64Binary("JVBERi0xLjQKMyAwIG9iago8P...");

How to select multiple rows filled with constants?

SELECT * 
FROM DUAL 
CONNECT BY ROWNUM <= 9;

Write bytes to file

This example reads 6 bytes into a byte array and writes it to another byte array. It does an XOR operation with the bytes so that the result written to the file is the same as the original starting values. The file is always 6 bytes in size, since it writes at position 0.

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
        byte[] b1 = { 1, 2, 4, 8, 16, 32 };
        byte[] b2 = new byte[6];
        byte[] b3 = new byte[6];
        byte[] b4 = new byte[6];

        FileStream f1;
        f1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);

        // write the byte array into a new file
        f1.Write(b1, 0, 6);
        f1.Close();

        // read the byte array
        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        f1.Read(b2, 0, 6);
        f1.Close();

        // make changes to the byte array
        for (int i = 1; i < b2.Length; i++)
        {
            b2[i] = (byte)(b2[i] ^ (byte)10); //xor 10
        }

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);
        // write the new byte array into the file
        f1.Write(b2, 0, 6);
        f1.Close();

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);

        // read the byte array
        f1.Read(b3, 0, 6);
        f1.Close();

        // make changes to the byte array
        for (int i = 1; i < b3.Length; i++)
        {
            b4[i] = (byte)(b3[i] ^ (byte)10); //xor 10
        }

        f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);

        // b4 will have the same values as b1
        f1.Write(b4, 0, 6);
        f1.Close();
        }
    }
}

What are NR and FNR and what does "NR==FNR" imply?

Assuming you have Files a.txt and b.txt with

cat a.txt
a
b
c
d
1
3
5
cat b.txt
a
1
2
6
7

Keep in mind NR and FNR are awk built-in variables. NR - Gives the total number of records processed. (in this case both in a.txt and b.txt) FNR - Gives the total number of records for each input file (records in either a.txt or b.txt)

awk 'NR==FNR{a[$0];}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
a.txt 1 1 a
a.txt 2 2 b
a.txt 3 3 c
a.txt 4 4 d
a.txt 5 5 1
a.txt 6 6 3
a.txt 7 7 5
b.txt 8 1 a
b.txt 9 2 1

lets Add "next" to skip the first matched with NR==FNR

in b.txt and in a.txt

awk 'NR==FNR{a[$0];next}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 8 1 a
b.txt 9 2 1

in b.txt but not in a.txt

 awk 'NR==FNR{a[$0];next}{if(!($0 in a))print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 10 3 2
b.txt 11 4 6
b.txt 12 5 7

awk 'NR==FNR{a[$0];next}!($0 in a)' a.txt b.txt
2
6
7

Regular expression to extract URL from an HTML link

Yes, there are tons of them on regexlib. That only proves that RE's should not be used to do that. Use SGMLParser or BeautifulSoup or write a parser - but don't use RE's. The ones that seems to work are extremely compliated and still don't cover all cases.

git - pulling from specific branch

It's often clearer to separate the two actions git pull does. The first thing it does is update the local tracking branc that corresponds to the remote branch. This can be done with git fetch. The second is that it then merges in changes, which can of course be done with git merge, though other options such as git rebase are occasionally useful.

Pointer vs. Reference

A reference is similar to a pointer, except that you don’t need to use a prefix * to access the value referred to by the reference. Also, a reference cannot be made to refer to a different object after its initialization.

References are particularly useful for specifying function arguments.

for more information see "A Tour of C++" by "Bjarne Stroustrup" (2014) Pages 11-12

Round button with text and icon in flutter

Congrats to the previous answers... But I realised if the icons are in a row (say three icons as represented in the image above), you need to play around with columns and rows.

Here is the code

 Column(
        crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  FlatButton(
                      onPressed: () {},
                      child: Icon(
                        Icons.call,
                      )),
                  FlatButton(
                      onPressed: () {},
                      child: Icon(
                        Icons.message,
                      )),
                  FlatButton(
                      onPressed: () {},
                      child: Icon(
                        Icons.block,
                        color: Colors.red,
                      )),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Text(
                    '   Call',
                  ),
                  Text(
                    'Message',
                  ),
                  Text(
                    'Block',
                    style: TextStyle(letterSpacing: 2.0, color: Colors.red),
                  ),
                ],
              ),
            ],
          ),

Here is the result

Remove pandas rows with duplicate indices

Oh my. This is actually so simple!

grouped = df3.groupby(level=0)
df4 = grouped.last()
df4
                      A   B  rownum

2001-01-01 00:00:00   0   0       6
2001-01-01 01:00:00   1   1       7
2001-01-01 02:00:00   2   2       8
2001-01-01 03:00:00   3   3       3
2001-01-01 04:00:00   4   4       4
2001-01-01 05:00:00   5   5       5

Follow up edit 2013-10-29 In the case where I have a fairly complex MultiIndex, I think I prefer the groupby approach. Here's simple example for posterity:

import numpy as np
import pandas

# fake index
idx = pandas.MultiIndex.from_tuples([('a', letter) for letter in list('abcde')])

# random data + naming the index levels
df1 = pandas.DataFrame(np.random.normal(size=(5,2)), index=idx, columns=['colA', 'colB'])
df1.index.names = ['iA', 'iB']

# artificially append some duplicate data
df1 = df1.append(df1.select(lambda idx: idx[1] in ['c', 'e']))
df1
#           colA      colB
#iA iB                    
#a  a  -1.297535  0.691787
#   b  -1.688411  0.404430
#   c   0.275806 -0.078871
#   d  -0.509815 -0.220326
#   e  -0.066680  0.607233
#   c   0.275806 -0.078871  # <--- dup 1
#   e  -0.066680  0.607233  # <--- dup 2

and here's the important part

# group the data, using df1.index.names tells pandas to look at the entire index
groups = df1.groupby(level=df1.index.names)  
groups.last() # or .first()
#           colA      colB
#iA iB                    
#a  a  -1.297535  0.691787
#   b  -1.688411  0.404430
#   c   0.275806 -0.078871
#   d  -0.509815 -0.220326
#   e  -0.066680  0.607233

Could not load file or assembly '***.dll' or one of its dependencies

or one of its dependencies

That's the usual problem, you cannot see a missing unmanaged DLL with Fuslogvw.exe. Best thing to do is to run SysInternals' ProcMon utility. You'll see it searching for the DLL and not find it. Profile mode in Dependency Walker can show it too.

Stretch image to fit full container width bootstrap

This will do the same as many of the other answers, but will make sides flush with the window, so there is no scroll bars.

<div class="container-fluid">
  <div class="row">
    <div class="col" style="padding: 0;">
       <img src="example.jpg" class="img-responsive" alt="Example">  
    </div>
  </div>
</div>

How to edit default.aspx on SharePoint site without SharePoint Designer

You can always use Sharepoint Solution Generator to create a project and edit in VS2008.

You can find the Generator along with Sharepoint Developer tools.

how to use json file in html code

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>

<script>

    $(function() {


   var people = [];

   $.getJSON('people.json', function(data) {
       $.each(data.person, function(i, f) {
          var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
           "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
           $(tblRow).appendTo("#userdata tbody");
     });

   });

});
</script>
</head>

<body>

<div class="wrapper">
<div class="profile">
   <table id= "userdata" border="2">
  <thead>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email Address</th>
            <th>City</th>
        </thead>
      <tbody>

       </tbody>
   </table>

</div>
</div>

</body>
</html>

My JSON file:

{
   "person": [
       {
           "firstName": "Clark",
           "lastName": "Kent",
           "job": "Reporter",
           "roll": 20
       },
       {
           "firstName": "Bruce",
           "lastName": "Wayne",
           "job": "Playboy",
           "roll": 30
       },
       {
           "firstName": "Peter",
           "lastName": "Parker",
           "job": "Photographer",
           "roll": 40
       }
   ]
}

I succeeded in integrating a JSON file to HTML table after working a day on it!!!

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

How to cast the size_t to double or int C++

Assuming that the program cannot be redesigned to avoid the cast (ref. Keith Thomson's answer):

To cast from size_t to int you need to ensure that the size_t does not exceed the maximum value of the int. This can be done using std::numeric_limits:

int SizeTToInt(size_t data)
{
    if (data > std::numeric_limits<int>::max())
        throw std::exception("Invalid cast.");
    return std::static_cast<int>(data);
}

If you need to cast from size_t to double, and you need to ensure that you don't lose precision, I think you can use a narrow cast (ref. Stroustrup: The C++ Programming Language, Fourth Edition):

template<class Target, class Source>
Target NarrowCast(Source v)
{
    auto r = static_cast<Target>(v);
    if (static_cast<Source>(r) != v)
        throw RuntimeError("Narrow cast failed.");
    return r;
}

I tested using the narrow cast for size_t-to-double conversions by inspecting the limits of the maximum integers floating-point-representable integers (code uses googletest):

EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 2 })), size_t{ IntegerRepresentableBoundary() - 2 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 1 })), size_t{ IntegerRepresentableBoundary() - 1 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() })), size_t{ IntegerRepresentableBoundary() });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 1 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 2 })), size_t{ IntegerRepresentableBoundary() + 2 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 3 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 4 })), size_t{ IntegerRepresentableBoundary() + 4 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 5 }), std::exception);

where

constexpr size_t IntegerRepresentableBoundary()
{
    static_assert(std::numeric_limits<double>::radix == 2, "Method only valid for binary floating point format.");
    return size_t{2} << (std::numeric_limits<double>::digits - 1);
}

That is, if N is the number of digits in the mantissa, for doubles smaller than or equal to 2^N, integers can be exactly represented. For doubles between 2^N and 2^(N+1), every other integer can be exactly represented. For doubles between 2^(N+1) and 2^(N+2) every fourth integer can be exactly represented, and so on.

All combinations of a list of lists

Numpy can do it:

 >>> import numpy
 >>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
 >>> [list(x) for x in numpy.array(numpy.meshgrid(*a)).T.reshape(-1,len(a))]
[[ 1, 4, 7], [1, 5, 7], [1, 6, 7], ....]

How to select top n rows from a datatable/dataview in ASP.NET

myDataTable.AsEnumerable().Take(5).CopyToDataTable()

How to take character input in java

import java.util.Scanner;

class SwiCas {

    public static void main(String as[]) {   
        Scanner s= new Scanner(System.in);

        char a=s.next().charAt(0);//this line shows how to take character input in java

        switch(a) {    
            case 'a':
                System.out.println("Vowel....");   
                break;    
            case 'e':
                System.out.println("Vowel....");   
                break;   
            case 'i':
                System.out.println("Vowel....");   
                break;
            case 'o':
                System.out.println("Vowel....");    
                break;    
            case 'u':
                System.out.println("Vowel....");   
                break;    
            case 'A':
                System.out.println("Vowel....");    
                break;    
            case 'E':
                System.out.println("Vowel....");  
                break;    
            case 'I':
                System.out.println("Vowel....");    
                break;    
            case 'O':
                System.out.println("Vowel....");    
                break;   
            case 'U':
                System.out.println("Vowel....");    
                break;    
            default:    
                System.out.println("Consonants....");
        }
    }
}

JUnit 4 compare Sets

You can assert that the two Sets are equal to one another, which invokes the Set equals() method.

public class SimpleTest {

    private Set<String> setA;
    private Set<String> setB;

    @Before
    public void setUp() {
        setA = new HashSet<String>();
        setA.add("Testing...");
        setB = new HashSet<String>();
        setB.add("Testing...");
    }

    @Test
    public void testEqualSets() {
        assertEquals( setA, setB );
    }
}

This @Test will pass if the two Sets are the same size and contain the same elements.

How to get screen dimensions as pixels in Android

One way is:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();

It is deprecated, and you should try the following code instead. The first two lines of code gives you the DisplayMetrics objecs. This objects contains the fields like heightPixels, widthPixels.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
      
int height = metrics.heightPixels;
int width = metrics.widthPixels;

Api level 30 update

final WindowMetrics metrics = windowManager.getCurrentWindowMetrics();
 // Gets all excluding insets
 final WindowInsets windowInsets = metrics.getWindowInsets();
 Insets insets = windowInsets.getInsetsIgnoreVisibility(WindowInsets.Type.navigationBars()
         | WindowInsets.Type.displayCutout());

 int insetsWidth = insets.right + insets.left;
 int insetsHeight = insets.top + insets.bottom;

 // Legacy size that Display#getSize reports
 final Rect bounds = metrics.getBounds();
 final Size legacySize = new Size(bounds.width() - insetsWidth,
         bounds.height() - insetsHeight);

Angular - POST uploaded file

your http service file:

import { Injectable } from "@angular/core";
import { ActivatedRoute, Router } from '@angular/router';
import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import {Observable} from 'rxjs/Rx';
import { Constants } from './constants';
declare var $: any;

@Injectable()
export class HttpClient {
  requestUrl: string;
  responseData: any;
  handleError: any;

  constructor(private router: Router, 
  private http: Http, 
  private constants: Constants, 
  ) {
    this.http = http;
  }

  postWithFile (url: string, postData: any, files: File[]) {

    let headers = new Headers();
    let formData:FormData = new FormData();
    formData.append('files', files[0], files[0].name);
    // For multiple files
    // for (let i = 0; i < files.length; i++) {
    //     formData.append(`files[]`, files[i], files[i].name);
    // }

    if(postData !=="" && postData !== undefined && postData !==null){
      for (var property in postData) {
          if (postData.hasOwnProperty(property)) {
              formData.append(property, postData[property]);
          }
      }
    }
    var returnReponse = new Promise((resolve, reject) => {
      this.http.post(this.constants.root_dir + url, formData, {
        headers: headers
      }).subscribe(
          res => {
            this.responseData = res.json();
            resolve(this.responseData);
          },
          error => {
            this.router.navigate(['/login']);
            reject(error);
          }
      );
    });
    return returnReponse;
  }
}

call your function (Component file):

onChange(event) {
    let file = event.srcElement.files;
    let postData = {field1:"field1", field2:"field2"}; // Put your form data variable. This is only example.
    this._service.postWithFile(this.baseUrl + "add-update",postData,file).then(result => {
        console.log(result);
    });
}

your html code:

<input type="file" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="stock.documents" #documents="ngModel">

How to download Javadoc to read offline?

The updated latest version of "The Java language Specification" can be found via the following links. Java 7

Java 8

Better way to remove specific characters from a Perl string

Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.

You take that string, call it $place_older say. And then when you want to eliminate the text, you call quotemeta, and you use that value to substitute:

my $subs = quotemeta $place_holder;
s/$subs//g;

How to restore the dump into your running mongodb

Follow this path.

C:\Program Files\MongoDB\Server\4.2\bin

Run the cmd in bin folder and paste the below command

mongorestore --db <name-your-database-want-to-restore-as> <path-of-dumped-database>

For Example:

mongorestore --db testDb D:\Documents\Dump\myDb

Python regular expressions return true/false

You can use re.match() or re.search(). Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default). refer this

Insert null/empty value in sql datetime column by default

I was having the same issue this morning. It appears that for a DATE or DATETIME field, an empty value cannot be inserted. I got around this by first checking for an empty value (mydate = "") and if it was empty setting mydate = "NULL" before insert.

The DATE and DATETIME fields don't behave in the same way as VARCHAR fields.

Access XAMPP Localhost from Internet

you have to open a port of the service in you router then try you puplic ip out of your all network cause if you try it from your network , the puplic ip will always redirect you to your router but from the outside it will redirect to the server you have

How do I check if an element is hidden in jQuery?

This is some option to check that tag is visible or not

_x000D_
_x000D_
 // using a pure CSS selector  _x000D_
   if ($('p:visible')) {  _x000D_
      alert('Paragraphs are visible (checked using a CSS selector) !');  _x000D_
   };  _x000D_
  _x000D_
   // using jQuery's is() method  _x000D_
   if ($('p').is(':visible')) {  _x000D_
      alert('Paragraphs are visible (checked using is() method)!');  _x000D_
   };  _x000D_
  _x000D_
   // using jQuery's filter() method  _x000D_
   if ($('p').filter(':visible')) {  _x000D_
      alert('Paragraphs are visible (checked using filter() method)!');  _x000D_
   };  _x000D_
  _x000D_
   // you can use :hidden instead of :visible to reverse the logic and check if an element is hidden  _x000D_
   // if ($('p:hidden')) {  _x000D_
   //    do something  _x000D_
   // };  
_x000D_
_x000D_
_x000D_

How to remove all listeners in an element?

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);

If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

angular.js ng-repeat li items with html content

You can use NGBindHTML or NGbindHtmlUnsafe this will not escape the html content of your model.

http://jsfiddle.net/n9rQr/

<div ng-app ng-controller="MyCtrl">
    <ul>
    <li ng-repeat=" opt in opts"  ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
    </li>
    </ul>

    <p>{{opt}}</p>
</div>

This works, anyway you should be very careful when using unsanitized html content, you should really trust the source of the content.

Python: How exactly can you take a string, split it, reverse it and join it back together again?

I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-

def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
    if string[y]==" ":
        list_.append(string[x:y])
        x = y+1
    elif y==len(string)-1:
        list_.append(string[x:y+1])
return list_

def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
    reversed_list.append(element)
return reversed_list

def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with 
space as a separator'''
final_string = str()
for element in list_:
    final_string += str(element) + " "
return final_string

#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I 

Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!

What is "origin" in Git?

Git has the concept of "remotes", which are simply URLs to other copies of your repository. When you clone another repository, Git automatically creates a remote named "origin" and points to it.

You can see more information about the remote by typing git remote show origin.

vuetify center items into v-flex

<v-layout justify-center>
  <v-card-actions>
    <v-btn primary>
     <span>SignUp</span>
    </v-btn>`enter code here`
  </v-card-actions>
</v-layout>

How to append elements into a dictionary in Swift?

Given two dictionaries as below:

var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]

Here is how you can add all the items from dic2 to dic1:

dic2.forEach {
   dic1[$0.key] = $0.value
}

Event listener for when element becomes visible?

I had this same problem and created a jQuery plugin to solve it for our site.

https://github.com/shaunbowe/jquery.visibilityChanged

Here is how you would use it based on your example:

$('#contentDiv').visibilityChanged(function(element, visible) {
    alert("do something");
});

Dynamic variable names in Bash

As per BashFAQ/006, you can use read with here string syntax for assigning indirect variables:

function grep_search() {
  read "$1" <<<$(ls | tail -1);
}

Usage:

$ grep_search open_box
$ echo $open_box
stack-overflow.txt

Iterating C++ vector from the end to the beginning

As I don't want to introduce alien-like new C++ syntax, and I simply want to build up on existing primitives, the below snippets seems to work:

#include <vector>
#include <iostream>

int main (int argc,char *argv[])
{
    std::vector<int> arr{1,2,3,4,5};
    std::vector<int>::iterator it;

    // iterate forward
    for (it = arr.begin(); it != arr.end(); it++) {
        std::cout << *it << " ";
    }

    std::cout << "\n************\n";
 
    if (arr.size() > 0) {
        // iterate backward, simple Joe version
        it = arr.end() - 1;
        while (it != arr.begin()) {
            std::cout << *it << " ";
            it--;
        }
        std::cout << *it << " ";
    } 

    // iterate backwards, the C++ way
    std::vector<int>::reverse_iterator rit;
    for (rit = arr.rbegin(); rit != arr.rend(); rit++) {
        std::cout << *rit << " ";
    }

    return 0;
}

require is not defined? Node.js

Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.

See browserify or webpack if you wish to serve browser-specific modules from Node.

Mark error in form using Bootstrap

Bootstrap V3:

Once i was searching for laravel features then i got to know this amazing form validation. Later on, i amended glyphicon icon features. Now, it looks great.

<div class="col-md-12">
<div class="form-group has-error has-feedback">
    <input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
    <span class="glyphicon glyphicon-remove form-control-feedback"></span>       
    <span class="help-block"><p>The Email field is required.</p></span>                                        
</div>
</div>
<div class="clearfix"></div>

<div class="col-md-6">
<div class="form-group has-error has-feedback">
    <input id="account_holder_name" name="name" type="text" placeholder="Name" class="form-control ">
    <span class="glyphicon glyphicon-remove form-control-feedback"></span>                                            
    <span class="help-block"><p>The Name field is required.</p></span>                                        
</div>
</div>
<div class="col-md-6">
<div class="form-group has-error has-feedback">
 <input id="check_np" name="check_no" type="text" placeholder="Check no" class="form-control ">
 <span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Check No. field is required.</p></span>                                       
</div>
</div>

This is what it looks like: enter image description here

Once i completed it i thought i should implement it in Codeigniter as well. So here is the Codeigniter-3 validation with Bootstrap:

Controller

function addData()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|max_length[128]');
if($this->form_validation->run() == FALSE)
{
//validation fails. Load your view.
$this->loadViews('Load your view','pass your data to view if any');
}
else
{  
 //validation pass. Your code here.
}
}

View

<div class="col-md-12">
<?php 
 $email_error = (form_error('email') ? 'has-error has-feedback' : '');
 if(!empty($email_error)){
 $emailData = '<span class="help-block">'.form_error('email').'</span>';
 $emailClass = $email_error;
 $emailIcon = '<span class="glyphicon glyphicon-remove form-control-feedback"></span>';
}
else{
    $emailClass = $emailIcon = $emailData = '';
 } 
 ?>
<div class="form-group <?= $emailClass ?>">
<input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
<?= $emailIcon ?>
<?= $emailData ?>
</div>
</div>

Output: enter image description here

How to hide Soft Keyboard when activity starts

Ed_Cat_Search = (EditText) findViewById(R.id.editText_Searc_Categories);

Ed_Cat_Search.setInputType(InputType.TYPE_NULL);

Ed_Cat_Search.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        Ed_Cat_Search.setInputType(InputType.TYPE_CLASS_TEXT);
        Ed_Cat_Search.onTouchEvent(event); // call native handler
        return true; // consume touch even
    }
});

this one worked for me

Node Multer unexpected field

I solve this issues looking for the name that I passed on my request

I was sending on body:

{thumbbail: <myimg>}

and I was expect to:

upload.single('thumbnail')

so, I fix the name that a send on request

C# List of objects, how do I get the sum of a property

Another alternative:

myPlanetsList.Select(i => i.Moons).Sum();

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

Postfix is installed but how do I test it?

(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)

You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.

Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:

telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)

You should get a response like:

250 2.0.0 Ok: queued as 6E414C4643A

The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:

sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected]             [email protected]
[email protected]             [email protected]
@localdomain.local                [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the 
generic file)

Happy Trails

can't start MySql in Mac OS 10.6 Snow Leopard

my apple processor version10.6.3 is error and i can click system preference

Converting EditText to int? (Android)

I'm very sleepy and tired right now but wouldn't this work?:

EditText et = (EditText)findViewById(R.id.editText1);
String sTextFromET = et.getText().toString();
int nIntFromET = new Integer(sTextFromET).intValue();

OR

try
{
    int nIntFromET = Integer.parseInt(sTextFromET);
}
catch (NumberFormatException e)
{
    // handle the exception
}

Difference between except: and except Exception as e: in Python

There are differences with some exceptions, e.g. KeyboardInterrupt.

Reading PEP8:

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

What is the main difference between Inheritance and Polymorphism?

Inheritance is more a static thing (one class extends another) while polymorphism is a dynamic/ runtime thing (an object behaves according to its dynamic/ runtime type not to its static/ declaration type).

E.g.

// This assignment is possible because B extends A
A a = new B();
// polymorphic call/ access
a.foo();

-> Though the static/ declaration type of a is A, the actual dynamic/ runtime type is B and thus a.foo() will execute foo as defined in B not in A.

Can you write nested functions in JavaScript?

The following is nasty, but serves to demonstrate how you can treat functions like any other kind of object.

var foo = function () { alert('default function'); }

function pickAFunction(a_or_b) {
    var funcs = {
        a: function () {
            alert('a');
        },
        b: function () {
            alert('b');
        }
    };
    foo = funcs[a_or_b];
}

foo();
pickAFunction('a');
foo();
pickAFunction('b');
foo();

How do I exit from a function?

Yo can simply google for "exit sub in c#".

Also why would you check every text box if it is empty. You can place requiredfieldvalidator for these text boxes if this is an asp.net app and check if(Page.IsValid)

Or another solution is to get not of these conditions:

private void button1_Click(object sender, EventArgs e)
{
    if (!(textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == ""))
    {
        //do events
    }
}

And better use String.IsNullOrEmpty:

private void button1_Click(object sender, EventArgs e)
{
    if (!(String.IsNullOrEmpty(textBox1.Text)
    || String.IsNullOrEmpty(textBox2.Text)
    || String.IsNullOrEmpty(textBox3.Text)))
    {
        //do events
    }
}

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

Whenever you create or update package name Make sure your package name is exactly the same [Upper case and lower case matters]

Do below step.

1). Check applicationId in App level gradle file,

2). Check package_name in your google-services.json file,

3). Check package in your AndroidManifest file

and for full confirmation make sure that your working package directory name i.e.("com.example.app") is also the same.

EDIT [ Any one who is facing this issue in productFlavour scenario, go check out Droid Chris's Solution ]

How do I use a custom deleter with a std::unique_ptr member?

You can simply use std::bind with a your destroy function.

std::unique_ptr<Bar, std::function<void(Bar*)>> bar(create(), std::bind(&destroy,
    std::placeholders::_1));

But of course you can also use a lambda.

std::unique_ptr<Bar, std::function<void(Bar*)>> ptr(create(), [](Bar* b){ destroy(b);});

Java: print contents of text file to screen

Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text

Príliš žlutoucký kun
úpel dábelské ódy

and the file uses windows-1250 format. If you use FileReader you will get this result:

P??li? ?lu?ou?k? k??
?p?l ??belsk? ?dy

So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.

Example:

String encoding = "Cp1250";
File file = new File("foo.txt");

if (file.exists()) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
else {
    System.out.println("file doesn't exist");
}

In case you want to read the file character after character do not use BufferedReader.

try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
    int data = isr.read();
    while (data != -1) {
        System.out.print((char) data);
        data = isr.read();
    }
} catch (IOException e) {
    e.printStackTrace();
}

How to test if JSON object is empty in Java

If empty array:

.size() == 0

if empty object:

.length() == 0

what is the difference between ajax and jquery and which one is better?

Ajax is a technology / paradigm, whereas jquery is a library (which provides - besides other nice functionality - a convenient wrapper around ajax) - thus you can't compare them.

Get Table and Index storage size in sql server

with pages as (
    SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
            SUM (case 
                    when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
                    else lob_used_page_count + row_overflow_used_page_count
                 end) as pages
    FROM sys.dm_db_partition_stats
    group by object_id
), extra as (
    SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
    FROM sys.dm_db_partition_stats p, sys.internal_tables it
    WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
    group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
        pages * 8 as data_kb,
        (CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
        (CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id

Takes into account internal tables, such as those used for XML storage.

Edit: If you divide the data_kb and index_kb values by 1024.0, you will get the numbers you see in the GUI.

How can I specify the required Node.js version in package.json?

Just like said Ibam, engineStrict is now deprecated. But I've found this solution:

check-version.js:

import semver from 'semver';
import { engines } from './package';

const version = engines.node;
if (!semver.satisfies(process.version, version)) {
  console.log(`Required node version ${version} not satisfied with current version ${process.version}.`);
  process.exit(1);
}

package.json:

{
  "name": "my package",
  "engines": {
    "node": ">=50.9" // intentionally so big version number
  },
  "scripts": {
    "requirements-check": "babel-node check-version.js",
    "postinstall": "npm run requirements-check"
  }
}

Find out more here: https://medium.com/@adambisek/how-to-check-minimum-required-node-js-version-4a78a8855a0f#.3oslqmig4

.nvmrc

And one more thing. A dotfile '.nvmrc' can be used for requiring specific node version - https://github.com/creationix/nvm#nvmrc

But, it is only respected by npm scripts (and yarn scripts).

Counting the number of non-NaN elements in a numpy ndarray in Python

np.count_nonzero(~np.isnan(data))

~ inverts the boolean matrix returned from np.isnan.

np.count_nonzero counts values that is not 0\false. .sum should give the same result. But maybe more clearly to use count_nonzero

Testing speed:

In [23]: data = np.random.random((10000,10000))

In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan

In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop

In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop

In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop

data.size - np.count_nonzero(np.isnan(data)) seems to barely be the fastest here. other data might give different relative speed results.

How do I reverse a commit in git?

You can do git push --force but be aware that you are rewriting history and anyone using the repo will have issue with this.

If you want to prevent this problem, don't use reset, but instead use git revert

Running a script inside a docker container using shell script

Assuming that your docker container is up and running, you can run commands as:

docker exec mycontainer /bin/sh -c "cmd1;cmd2;...;cmdn"

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

Calculating moving average

EDIT: took great joy in adding the side parameter, for a moving average (or sum, or ...) of e.g. the past 7 days of a Date vector.


For people just wanting to calculate this themselves, it's nothing more than:

# x = vector with numeric data
# w = window length
y <- numeric(length = length(x))

for (i in seq_len(length(x))) {
  ind <- c((i - floor(w / 2)):(i + floor(w / 2)))
  ind <- ind[ind %in% seq_len(length(x))]
  y[i] <- mean(x[ind])
}

y

But it gets fun to make it independent of mean(), so you can calculate any 'moving' function!

# our working horse:
moving_fn <- function(x, w, fun, ...) {
  # x = vector with numeric data
  # w = window length
  # fun = function to apply
  # side = side to take, (c)entre, (l)eft or (r)ight
  # ... = parameters passed on to 'fun'
  y <- numeric(length(x))
  for (i in seq_len(length(x))) {
    if (side %in% c("c", "centre", "center")) {
      ind <- c((i - floor(w / 2)):(i + floor(w / 2)))
    } else if (side %in% c("l", "left")) {
      ind <- c((i - floor(w) + 1):i)
    } else if (side %in% c("r", "right")) {
      ind <- c(i:(i + floor(w) - 1))
    } else {
      stop("'side' must be one of 'centre', 'left', 'right'", call. = FALSE)
    }
    ind <- ind[ind %in% seq_len(length(x))]
    y[i] <- fun(x[ind], ...)
  }
  y
}

# and now any variation you can think of!
moving_average <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = mean, side = side, na.rm = na.rm)
}

moving_sum <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = sum, side = side, na.rm = na.rm)
}

moving_maximum <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = max, side = side, na.rm = na.rm)
}

moving_median <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = median, side = side, na.rm = na.rm)
}

moving_Q1 <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = quantile, side = side, na.rm = na.rm, 0.25)
}

moving_Q3 <- function(x, w = 5, side = "centre", na.rm = FALSE) {
  moving_fn(x = x, w = w, fun = quantile, side = side, na.rm = na.rm, 0.75)
}

How to set the font style to bold, italic and underlined in an Android TextView?

Just one line of code in xml

        android:textStyle="italic"

Concatenating null strings in Java

The second line is transformed to the following code:

s = (new StringBuilder()).append((String)null).append("hello").toString();

The append methods can handle null arguments.

How do I remove  from the beginning of a file?

If you need to be able to remove the BOM from UTF-8 encoded files, you first need to get hold of an editor that is aware of them.

I personally use E Text Editor.

In the bottom right, there are options for character encoding, including the BOM tag. Load your file, deselect Byte Order Marker if it is selected, resave, and it should be done.

Alt text http://oth4.com/encoding.png

E is not free, but there is a free trial, and it is an excellent editor (limited TextMate compatibility).

Notification bar icon turns white in Android 5 Lollipop

Post android Lollipop release android has changed the guidelines for displaying notification icons in the Notification bar. The official documentation says "Update or remove assets that involve color. The system ignores all non-alpha channels in action icons and in the main notification icon. You should assume that these icons will be alpha-only. The system draws notification icons in white and action icons in dark gray.” Now what that means in lay man terms is "Convert all parts of the image that you don’t want to show to transparent pixels. All colors and non transparent pixels are displayed in white"

You can see how to do this in detail with screenshots here https://blog.clevertap.com/fixing-notification-icon-for-android-lollipop-and-above/

Hope that helps

Generating Request/Response XML from a WSDL

Parasoft is a tool which can do this. I've done this very thing using this tool in my past work place. You can generate a request in Parasoft SOATest and get a response in Parasoft Virtualize. It does cost though. However Parasoft Virtualize now has a free community edition from which you can generate response messages from a WSDL. You can download from parasoft community edition

Switch statement for greater-than/less-than

When I looked at the solutions in the other answers I saw some things that I know are bad for performance. I was going to put them in a comment but I thought it was better to benchmark it and share the results. You can test it yourself. Below are my results (ymmv) normalized after the fastest operation in each browser (multiply the 1.0 time with the normalized value to get the absolute time in ms).

                    Chrome  Firefox Opera   MSIE    Safari  Node
-------------------------------------------------------------------
1.0 time               37ms    73ms    68ms   184ms    73ms    21ms
if-immediate            1.0     1.0     1.0     2.6     1.0     1.0
if-indirect             1.2     1.8     3.3     3.8     2.6     1.0
switch-immediate        2.0     1.1     2.0     1.0     2.8     1.3
switch-range           38.1    10.6     2.6     7.3    20.9    10.4
switch-range2          31.9     8.3     2.0     4.5     9.5     6.9
switch-indirect-array  35.2     9.6     4.2     5.5    10.7     8.6
array-linear-switch     3.6     4.1     4.5    10.0     4.7     2.7
array-binary-switch     7.8     6.7     9.5    16.0    15.0     4.9

Test where performed on Windows 7 32bit with the folowing versions: Chrome 21.0.1180.89m, Firefox 15.0, Opera 12.02, MSIE 9.0.8112, Safari 5.1.7. Node was run on a Linux 64bit box because the timer resolution on Node.js for Windows was 10ms instead of 1ms.

if-immediate

This is the fastest in all tested environments, except in ... drumroll MSIE! (surprise, surprise). This is the recommended way to implement it.

if (val < 1000) { /*do something */ } else
if (val < 2000) { /*do something */ } else
...
if (val < 30000) { /*do something */ } else

if-indirect

This is a variant of switch-indirect-array but with if-statements instead and performs much faster than switch-indirect-array in almost all tested environments.

values=[
   1000,  2000, ... 30000
];
if (val < values[0]) { /* do something */ } else
if (val < values[1]) { /* do something */ } else
...
if (val < values[29]) { /* do something */ } else

switch-immediate

This is pretty fast in all tested environments, and actually the fastest in MSIE. It works when you can do a calculation to get an index.

switch (Math.floor(val/1000)) {
  case 0: /* do something */ break;
  case 1: /* do something */ break;
  ...
  case 29: /* do something */ break;
}

switch-range

This is about 6 to 40 times slower than the fastest in all tested environments except for Opera where it takes about one and a half times as long. It is slow because the engine has to compare the value twice for each case. Surprisingly it takes Chrome almost 40 times longer to complete this compared to the fastest operation in Chrome, while MSIE only takes 6 times as long. But the actual time difference was only 74ms in favor to MSIE at 1337ms(!).

switch (true) {
  case (0 <= val &&  val < 1000): /* do something */ break;
  case (1000 <= val &&  val < 2000): /* do something */ break;
  ...
  case (29000 <= val &&  val < 30000): /* do something */ break;
}

switch-range2

This is a variant of switch-range but with only one compare per case and therefore faster, but still very slow except in Opera. The order of the case statement is important since the engine will test each case in source code order ECMAScript262:5 12.11

switch (true) {
  case (val < 1000): /* do something */ break;
  case (val < 2000): /* do something */ break;
  ...
  case (val < 30000): /* do something */ break;
}

switch-indirect-array

In this variant the ranges is stored in an array. This is slow in all tested environments and very slow in Chrome.

values=[1000,  2000 ... 29000, 30000];

switch(true) {
  case (val < values[0]): /* do something */ break;
  case (val < values[1]): /* do something */ break;
  ...
  case (val < values[29]): /* do something */ break;
}

array-linear-search

This is a combination of a linear search of values in an array, and the switch statement with fixed values. The reason one might want to use this is when the values isn't known until runtime. It is slow in every tested environment, and takes almost 10 times as long in MSIE.

values=[1000,  2000 ... 29000, 30000];

for (sidx=0, slen=values.length; sidx < slen; ++sidx) {
  if (val < values[sidx]) break;
}

switch (sidx) {
  case 0: /* do something */ break;
  case 1: /* do something */ break;
  ...
  case 29: /* do something */ break;
}

array-binary-switch

This is a variant of array-linear-switch but with a binary search. Unfortunately it is slower than the linear search. I don't know if it is my implementation or if the linear search is more optimized. It could also be that the keyspace is to small.

values=[0, 1000,  2000 ... 29000, 30000];

while(range) {
  range = Math.floor( (smax - smin) / 2 );
  sidx = smin + range;
  if ( val < values[sidx] ) { smax = sidx; } else { smin = sidx; }
}

switch (sidx) {
  case 0: /* do something */ break;
  ...
  case 29: /* do something */ break;
}

Conclusion

If performance is important, use if-statements or switch with immediate values.

Add a column to a table, if it does not already exist

You can use a similar construct by using the sys.columns table io sys.objects.

IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[dbo].[Person]') 
         AND name = 'ColumnName'
)

What is the difference between Sessions and Cookies in PHP?

A session is a chunk of data maintained at the server that maintains state between HTTP requests. HTTP is fundamentally a stateless protocol; sessions are used to give it statefulness.

A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.

How do I upgrade to Python 3.6 with conda?

Creating a new environment will install python 3.6:

$ conda create --name 3point6 python=3.6
Fetching package metadata .......
Solving package specifications: ..........

Package plan for installation in environment /Users/dstansby/miniconda3/envs/3point6:

The following NEW packages will be INSTALLED:

    openssl:    1.0.2j-0     
    pip:        9.0.1-py36_1 
    python:     3.6.0-0      
    readline:   6.2-2        
    setuptools: 27.2.0-py36_0
    sqlite:     3.13.0-0     
    tk:         8.5.18-0     
    wheel:      0.29.0-py36_0
    xz:         5.2.2-1      
    zlib:       1.2.8-3 

Comparing two files in linux terminal

If you prefer the diff output style from git diff, you can use it with the --no-index flag to compare files not in a git repository:

git diff --no-index a.txt b.txt

Using a couple of files with around 200k file name strings in each, I benchmarked (with the built-in timecommand) this approach vs some of the other answers here:

git diff --no-index a.txt b.txt
# ~1.2s

comm -23 <(sort a.txt) <(sort b.txt)
# ~0.2s

diff a.txt b.txt
# ~2.6s

sdiff a.txt b.txt
# ~2.7s

vimdiff a.txt b.txt
# ~3.2s

comm seems to be the fastest by far, while git diff --no-index appears to be the fastest approach for diff-style output.


Update 2018-03-25 You can actually omit the --no-index flag unless you are inside a git repository and want to compare untracked files within that repository. From the man pages:

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

ReactJS map through Object

Use Object.entries() function.

Object.entries(object) return:

[
    [key, value],
    [key, value],
    ...
]

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

{Object.entries(subjects).map(([key, subject], i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">key: {i} Name: {subject.name}</span>
    </li>
))}

Responsive css background images

If you want the entire image to show irrespective of the aspect ratio, then try this:

background-image:url('../images/bg.png');
background-repeat:no-repeat;
background-size:100% 100%;
background-position:center;

This will show the entire image no matter what the screen size.

sending mail from Batch file

You can also use a Power Shell script:

$smtp = new-object Net.Mail.SmtpClient("mail.example.com")

if( $Env:SmtpUseCredentials -eq "true" ) {
    $credentials = new-object Net.NetworkCredential("username","password")
    $smtp.Credentials = $credentials
}
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "[email protected]"
$objMailMessage.To.Add("[email protected]")
$objMailMessage.Subject = "eMail subject Notification"
$objMailMessage.Body = "Hello world!"

$smtp.send($objMailMessage)

How can I find the location of origin/master in git, and how do I change it?

I thought my laptop was the origin…

That’s kind of nonsensical: origin refers to the default remote repository – the one you usually fetch/pull other people’s changes from.

How can I:

  1. git remote -v will show you what origin is; origin/master is your “bookmark” for the last known state of the master branch of the origin repository, and your own master is a tracking branch for origin/master. This is all as it should be.

  2. You don’t. At least it makes no sense for a repository to be the default remote repository for itself.

  3. It isn’t. It’s merely telling you that you have made so-and-so many commits locally which aren’t in the remote repository (according to the last known state of that repository).

How do I resolve this "ORA-01109: database not open" error?

I got a same problem. Below is how I solved the problem. I am working on an oracle database 12c pluggable database(pdb) on a windows 10.

-- using sqlplus to login as sysdba from a terminal; Below is an example:

sqlplus sys/@orclpdb as sysdba

-- First check your database status;

SQL> select name, open_mode from v$pdbs;

-- It shows the database is mounted in my case. If yours is not mounted, you should mount the database first.

-- Next open the database for read/write

SQL> ALTER PLUGGABLE DATABASE OPEN; (or ALTER PLUGGABLE DATABASE YOURDATABASENAME OPEN;)

-- Check the status again.

SQL> select name, open_mode from v$pdbs;

-- Now your dababase should be open for read/write and you should be able to create schemas, etc.

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

You should return only one column and one row in the where query where you assign the returned value to a variable. Example:

select * from table1 where Date in (select * from Dates) -- Wrong
select * from table1 where Date in (select Column1,Column2 from Dates) -- Wrong
select * from table1 where Date in (select Column1 from Dates) -- OK

CocoaPods Errors on Project Build

You can try the following. It fixed for me.

  1. install gem install cocoapods-deintegrate
  2. install gem install cocoapods-clean
  3. goto pod deintegrate
  4. pod clean
  5. pod install

The plugins will be remove from cocoapods for your project and will install freshly.

How to display a date as iso 8601 format with PHP

Procedural style :

echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00

Object oriented style :

$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00

Hybrid 1 :

echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00

Hybrid 2 :

echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00

Notes :

1) You could also use 'Y-m-d\TH:i:sP' as an alternative to 'c' for your format.

2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :

echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00

3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :

echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

Even though that this question was already answered I feel that there are missing examples in the answer that was answered.

Therefore I'll bring here what I wrote in a blog post "Android Log Levels"

Verbose

Is the lowest level of logging. If you want to go nuts with logging then you go with this level. I never understood when to use Verbose and when to use Debug. The difference sounded to me very arbitrary. I finally understood it once I was pointed to the source code of Android¹ “Verbose should never be compiled into an application except during development.” Now it is clear to me, whenever you are developing and want to add deletable logs that help you during the development it is useful to have the verbose level this will help you delete all these logs before you go into production.

Debug

Is for debugging purposes. This is the lowest level that should be in production. Information that is here is to help during development. Most times you’ll disable this log in production so that less information will be sent and only enable this log if you have a problem. I like to log in debug all the information that the app sends/receives from the server (take care not to log passwords!!!). This is very helpful to understand if the bug lies in the server or the app. I also make logs of entering and exiting of important functions.

Info

For informational messages that highlight the progress of the application. For example, when initialising of the app is finished. Add info when the user moves between activities and fragments. Log each API call but just little information like the URL , status and the response time.

Warning

When there is a potentially harmful situation.

This log is in my experience a tricky level. When do you have a potential harmful situation? In general or that it is OK or that it is an error. I personally don’t use this level much. Examples of when I use it are usually when stuff happens several times. For example, a user has a wrong password more than 3 times. This could be because he entered the password wrongly 3 times, it could also be because there is a problem with a character that isn’t being accepted in our system. Same goes with network connection problems.

Error

Error events. The application can still continue to run after the error. This can be for example when I get a null pointer where I’m not supposed to get one. There was an error parsing the response of the server. Got an error from the server.

WTF (What a Terrible Failure)

Fatal is for severe error events that will lead the application to exit. In Android the fatal is in reality the Error level, the difference is that it also adds the fullstack.

Is it possible to have empty RequestParam values use the defaultValue?

You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
    if(i == null) {
        i = 10;
    }
    // ...
}

I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:

http://example.com/test

sed one-liner to convert all uppercase to lowercase?

You also can do this very easily with awk, if you're willing to consider a different tool:

echo "UPPER" | awk '{print tolower($0)}'

Get the time of a datetime using T-SQL?

Just to add that from SQL Server 2008, there is a TIME datatype so from then on you can do:

SELECT CONVERT(TIME, GETDATE())

Might be useful for those that use SQL 2008+ and find this question.

Dropdownlist width in IE

this is the best way to do this:

select:focus{
    min-width:165px;
    width:auto;
    z-index:9999999999;
    position:absolute;
}

it's exactly the same like BalusC solution. Only this is easier. ;)

Unable to call the built in mb_internal_encoding method?

For OpenSUse (zypper package manager):

zypper install php5-mbstring

and:

zyper install php7-mbstring

In the other hand, you can search them through YaST Software manager.

Note that, you must restart apache http server:

systemctl restart apache2.service

Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

How To Remove Outline Border From Input Button

To avoid the problem caused when you change the outline property on a focus, is tho give a visual effect when the user Tab on the input button or click on it.

In this case is a submit type, but you can apply to a type="button" too.

_x000D_
_x000D_
input[type="submit"]:focus {_x000D_
    outline: none !important;_x000D_
    background-color: rgb(208, 192, 74);_x000D_
}
_x000D_
_x000D_
_x000D_

How and where to use ::ng-deep?

Make sure not to miss the explanation of :host-context which is directly above ::ng-deep in the angular guide : https://angular.io/guide/component-styles. I missed it up until now and wish I'd seen it sooner.

::ng-deep is often necessary when you didn't write the component and don't have access to its source, but :host-context can be a very useful option when you do.

For example I have a black <h1> header inside a component I designed, and I want the ability to change it to white when it's displayed on a dark themed background.

If I didn't have access to the source I may have to do this in the css for the parent:

.theme-dark widget-box ::ng-deep h1 { color: white; }

But instead with :host-context you can do this inside the component.

 h1 
 {
     color: black;       // default color

     :host-context(.theme-dark) &
     {
         color: white;   // color for dark-theme
     }

     // OR set an attribute 'outside' with [attr.theme]="'dark'"

     :host-context([theme='dark']) &
     {
         color: white;   // color for dark-theme
     }
 }

This will look anywhere in the component chain for .theme-dark and apply the css to the h1 if found. This is a good alternative to relying too much on ::ng-deep which while often necessary is somewhat of an anti-pattern.

In this case the & is replaced by the h1 (that's how sass/scss works) so you can define your 'normal' and themed/alternative css right next to each other which is very handy.

Be careful to get the correct number of :. For ::ng-deep there are two and for :host-context only one.

How do I restart nginx only after the configuration test was successful on Ubuntu?

Actually, as far as I know, nginx would show an empty message and it wouldn't actually restart if the configuration is bad.

The only way to screw it up is by doing an nginx stop and then start again. It would succeed to stop, but fail to start.

Insert data using Entity Framework model

[HttpPost] // it use when you write logic on button click event

public ActionResult DemoInsert(EmployeeModel emp)
{
    Employee emptbl = new Employee();    // make object of table
    emptbl.EmpName = emp.EmpName;
    emptbl.EmpAddress = emp.EmpAddress;  // add if any field you want insert
    dbc.Employees.Add(emptbl);           // pass the table object 
    dbc.SaveChanges();

    return View();
}

Python element-wise tuple operations like sum

Here is another handy solution if you are already using numpy. It is compact and the addition operation can be replaced by any numpy expression.

import numpy as np
tuple(np.array(a) + b)

Importing a GitHub project into Eclipse

unanswered core problem persists:

My working directory is now c:\users\projectname.git So then I try to import the project using the eclipse "import" option. When I try to import selecting the option "Use the new projects wizard" the source code is not imported, if I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project. When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?

Yes it should.

It's a bug. Reported here.

Here is a workaround:

  • Import as general project

  • Notice the imported data is no valid Eclipse project (no build path available)

  • Open the .project xml file in the project folder in Eclipse. If you can't see this file, see How can I get Eclipse to show .* files?.

  • Go to source tab

  • Search for <natures></natures> and change it to <natures><nature>org.eclipse.jdt.core.javanature</nature></natures> and save the file

    (idea comes from here)

  • Right click the src folder, go to Build Path... and click Use as Source Folder

After that, you should be able to run & debug the project, and also use team actions via right-click in the package explorer.

If you still have troubles running the project (something like "main class not found"), make sure the <buildSpec> inside the .project file is set (as described here):

<buildSpec>
    <buildCommand>
        <name>org.eclipse.jdt.core.javabuilder</name>
        <arguments>
        </arguments>
    </buildCommand>
</buildSpec>

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

If you keep on allocating & keeping references to object, you will fill up any amount of memory you have.

One option is to do a transparent file close & open when they switch tabs (you only keep a pointer to the file, and when the user switches tab, you close & clean all the objects... it'll make the file change slower... but...), and maybe keep only 3 or 4 files on memory.

Other thing you should do is, when the user opens a file, load it, and intercept any OutOfMemoryError, then (as it is not possible to open the file) close that file, clean its objects and warn the user that he should close unused files.

Your idea of dynamically extending virtual memory doesn't solve the issue, for the machine is limited on resources, so you should be carefull & handle memory issues (or at least, be carefull with them).

A couple of hints i've seen with memory leaks is:

--> Keep on mind that if you put something into a collection and afterwards forget about it, you still have a strong reference to it, so nullify the collection, clean it or do something with it... if not you will find a memory leak difficult to find.

--> Maybe, using collections with weak references (weakhashmap...) can help with memory issues, but you must be carefull with it, for you might find that the object you look for has been collected.

--> Another idea i've found is to develope a persistent collection that stored on database objects least used and transparently loaded. This would probably be the best approach...

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Use CSS :before and content property to print the breakpoint state in the <span id="breakpoint-js"> so the JavaScript just have to read this data to turn it as a variable to use within your function.

(run the snippet to see the example)

NOTE: I added a few line of CSS to use the <span> as a red flag in the upper corner of my browser. Just make sure to switch it back to display:none; before pushing your stuff public.

_x000D_
_x000D_
// initialize it with jquery when DOM is ready_x000D_
$(document).on('ready', function() {_x000D_
    getBootstrapBreakpoint();_x000D_
});_x000D_
_x000D_
// get bootstrap grid breakpoints_x000D_
var theBreakpoint = 'xs'; // bootstrap336 default = mobile first_x000D_
function getBootstrapBreakpoint(){_x000D_
   theBreakpoint = window.getComputedStyle(document.querySelector('#breakpoint-js'),':before').getPropertyValue('content').replace(/['"]+/g, '');_x000D_
   console.log('bootstrap grid breakpoint = ' + theBreakpoint);_x000D_
}
_x000D_
#breakpoint-js {_x000D_
  /* display: none; //comment this while developping. Switch back to display:NONE before commit */_x000D_
  /* optional red flag layout */_x000D_
  position: fixed;_x000D_
  z-index: 999;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  color: white;_x000D_
  padding: 5px 10px;_x000D_
  background-color: red;_x000D_
  opacity: .7;_x000D_
  /* end of optional red flag layout */_x000D_
}_x000D_
#breakpoint-js:before {_x000D_
  content: 'xs'; /* default = mobile first */_x000D_
}_x000D_
@media screen and (min-width: 768px) {_x000D_
  #breakpoint-js:before {_x000D_
    content: 'sm';_x000D_
  }_x000D_
}_x000D_
@media screen and (min-width: 992px) {_x000D_
  #breakpoint-js:before {_x000D_
    content: 'md';_x000D_
  }_x000D_
}_x000D_
@media screen and (min-width: 1200px) {_x000D_
  #breakpoint-js:before {_x000D_
    content: 'lg';_x000D_
  }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
  <span id="breakpoint-js"></span>_x000D_
  <div class="page-header">_x000D_
    <h1>Bootstrap grid examples</h1>_x000D_
    <p class="lead">Basic grid layouts to get you familiar with building within the Bootstrap grid system.</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

python - find index position in list based of partial string

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)

PHP XML how to output nice format

// ##### IN SUMMARY #####

$xmlFilepath = 'test.xml';
echoFormattedXML($xmlFilepath);

/*
 * echo xml in source format
 */
function echoFormattedXML($xmlFilepath) {
    header('Content-Type: text/xml'); // to show source, not execute the xml
    echo formatXML($xmlFilepath); // format the xml to make it readable
} // echoFormattedXML

/*
 * format xml so it can be easily read but will use more disk space
 */
function formatXML($xmlFilepath) {
    $loadxml = simplexml_load_file($xmlFilepath);

    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($loadxml->asXML());
    $formatxml = new SimpleXMLElement($dom->saveXML());
    //$formatxml->saveXML("testF.xml"); // save as file

    return $formatxml->saveXML();
} // formatXML

What is boilerplate code?

Joshua Bloch has a talk about API design that covers how bad ones make boilerplate code necessary. (Minute 46 for reference to boilerplate, listening to this today)

How to escape double quotes in JSON

It's showing the backslash because you're also escaping the backslash.

Aside from double quotes, you must also escape backslashes if you want to include one in your JSON quoted string. However if you intend to use a backslash in an escape sequence, obviously you shouldn't escape it.

Not receiving Google OAuth refresh token

    #!/usr/bin/env perl

    use strict;
    use warnings;
    use 5.010_000;
    use utf8;
    binmode STDOUT, ":encoding(utf8)";

    use Text::CSV_XS;
    use FindBin;
    use lib $FindBin::Bin . '/../lib';
    use Net::Google::Spreadsheets::V4;

    use Net::Google::DataAPI::Auth::OAuth2;

    use lib 'lib';
    use Term::Prompt;
    use Net::Google::DataAPI::Auth::OAuth2;
    use Net::Google::Spreadsheets;
    use Data::Printer ;


    my $oauth2 = Net::Google::DataAPI::Auth::OAuth2->new(
         client_id => $ENV{CLIENT_ID},
         client_secret => $ENV{CLIENT_SECRET},
         scope => ['https://www.googleapis.com/auth/spreadsheets'],
    );
    my $url = $oauth2->authorize_url();
    # system("open '$url'");
    print "go to the following url with your browser \n" ;
    print "$url\n" ;
    my $code = prompt('x', 'paste code: ', '', '');
    my $objToken = $oauth2->get_access_token($code);

    my $refresh_token = $objToken->refresh_token() ;

    print "my refresh token is : \n" ;
    # debug p($refresh_token ) ;
    p ( $objToken ) ;


    my $gs = Net::Google::Spreadsheets::V4->new(
            client_id      => $ENV{CLIENT_ID}
         , client_secret  => $ENV{CLIENT_SECRET}
         , refresh_token  => $refresh_token
         , spreadsheet_id => '1hGNULaWpYwtnMDDPPkZT73zLGDUgv5blwJtK7hAiVIU'
    );

    my($content, $res);

    my $title = 'My foobar sheet';

    my $sheet = $gs->get_sheet(title => $title);

    # create a sheet if does not exit
    unless ($sheet) {
         ($content, $res) = $gs->request(
              POST => ':batchUpdate',
              {
                    requests => [
                         {
                              addSheet => {
                                    properties => {
                                         title => $title,
                                         index => 0,
                                    },
                              },
                         },
                    ],
              },
         );

         $sheet = $content->{replies}[0]{addSheet};
    }

    my $sheet_prop = $sheet->{properties};

    # clear all cells
    $gs->clear_sheet(sheet_id => $sheet_prop->{sheetId});

    # import data
    my @requests = ();
    my $idx = 0;

    my @rows = (
         [qw(name age favorite)], # header
         [qw(tarou 31 curry)],
         [qw(jirou 18 gyoza)],
         [qw(saburou 27 ramen)],
    );

    for my $row (@rows) {
         push @requests, {
              pasteData => {
                    coordinate => {
                         sheetId     => $sheet_prop->{sheetId},
                         rowIndex    => $idx++,
                         columnIndex => 0,
                    },
                    data => $gs->to_csv(@$row),
                    type => 'PASTE_NORMAL',
                    delimiter => ',',
              },
         };
    }

    # format a header row
    push @requests, {
         repeatCell => {
              range => {
                    sheetId       => $sheet_prop->{sheetId},
                    startRowIndex => 0,
                    endRowIndex   => 1,
              },
              cell => {
                    userEnteredFormat => {
                         backgroundColor => {
                              red   => 0.0,
                              green => 0.0,
                              blue  => 0.0,
                         },
                         horizontalAlignment => 'CENTER',
                         textFormat => {
                              foregroundColor => {
                                    red   => 1.0,
                                    green => 1.0,
                                    blue  => 1.0
                              },
                              bold => \1,
                         },
                    },
              },
              fields => 'userEnteredFormat(backgroundColor,textFormat,horizontalAlignment)',
         },
    };

    ($content, $res) = $gs->request(
         POST => ':batchUpdate',
         {
              requests => \@requests,
         },
    );

    exit;

    #Google Sheets API, v4

    # Scopes
    # https://www.googleapis.com/auth/drive   View and manage the files in your Google D# # i# rive
    # https://www.googleapis.com/auth/drive.file View and manage Google Drive files and folders that you have opened or created with this app
    # https://www.googleapis.com/auth/drive.readonly   View the files in your Google Drive
    # https://www.googleapis.com/auth/spreadsheets  View and manage your spreadsheets in Google Drive
    # https://www.googleapis.com/auth/spreadsheets.readonly  View your Google Spreadsheets

Found conflicts between different versions of the same dependent assembly that could not be resolved

If you made any changes to packages -- reopen the sln. This worked for me!

Move seaborn plot legend to a different position?

Building on @user308827's answer: you can use legend=False in factorplot and specify the legend through matplotlib:

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                   data=titanic, kind="bar",
                   size=6, palette="muted",
                   legend=False)
g.despine(left=True)
plt.legend(loc='upper left')
g.set_ylabels("survival probability")

How do I do multiple CASE WHEN conditions using SQL Server 2008?

There are two formats of case expression. You can do CASE with many WHEN as;

CASE  WHEN Col1 = 1 OR Col3 = 1  THEN 1 
      WHEN Col1 = 2 THEN 2
      ...
      ELSE 0 END as Qty

Or a Simple CASE expression

CASE Col1 WHEN 1 THEN 11 WHEN 2 THEN 21 ELSE 13 END

Or CASE within CASE as;

CASE  WHEN Col1 < 2 THEN  
                    CASE Col2 WHEN 'X' THEN 10 ELSE 11 END
      WHEN Col1 = 2 THEN 2
      ...
      ELSE 0 END as Qty

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

The SQL Server Maximums are disclosed http://msdn.microsoft.com/en-us/library/ms143432.aspx (this is the 2008 version)

A SQL Query can be a varchar(max) but is shown as limited to 65,536 * Network Packet size, but even then what is most likely to trip you up is the 2100 parameters per query. If SQL chooses to parameterize the literal values in the in clause, I would think you would hit that limit first, but I havn't tested it.

Edit : Test it, even under forced parameteriztion it survived - I knocked up a quick test and had it executing with 30k items within the In clause. (SQL Server 2005)

At 100k items, it took some time then dropped with:

Msg 8623, Level 16, State 1, Line 1 The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.

So 30k is possible, but just because you can do it - does not mean you should :)

Edit : Continued due to additional question.

50k worked, but 60k dropped out, so somewhere in there on my test rig btw.

In terms of how to do that join of the values without using a large in clause, personally I would create a temp table, insert the values into that temp table, index it and then use it in a join, giving it the best opportunities to optimse the joins. (Generating the index on the temp table will create stats for it, which will help the optimiser as a general rule, although 1000 GUIDs will not exactly find stats too useful.)

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

Evaluate empty or null JSTL c tags

You can use

    ${var == null}

alternatively.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

If you were using DropDownListFor like this:

@Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)

where MySelectList in the model was a property of type SelectList, this error could be thrown if the property was null.

Avoid this by simple initializing it in constructor, like this:

public MyModel()
{
    MySelectList = new SelectList(new List<string>()); // empty list of anything...
}

I know it's not the OP's case, but this might help someone like me which had the same error due to this.

What is private bytes, virtual bytes, working set?

You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.

A previous reply to this question has given a great explanation of what the various types are.

You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.

http://www.softwareverify.com/cpp/memory/index.html

Disclaimer: I designed Memory Validator.

Procedure or function !!! has too many arguments specified

Yet another cause of this error is when you are calling the stored procedure from code, and the parameter type in code does not match the type on the stored procedure.

Comparing results with today's date?

OK, lets do this properly. Select dates matching today, using indexes if available, with all the different date/time types present.

The principle here is the same in each case. We grab rows where the date column is on or after the most recent midnight (today's date with time 00:00:00), and before the next midnight (tomorrow's date with time 00:00:00, but excluding anything with that exact value).

For pure date types, we can do a simple comparison with today's date.

To keep things nice and fast, we're explicitly avoiding doing any manipulation on the dates stored in the DB (the LHS of the where clause in all the examples below). This would potentially trigger a full table scan as the date would have to be computed for every comparison. (This behaviour appears to vary by DBMS, YMMV).

MS SQL Server: (SQL Fiddle | db<>fiddle)

First, using DATE

select * from dates 
where dte = CAST(CURRENT_TIMESTAMP AS DATE)
;

Now with DATETIME:

select * from datetimes 
where dtm >= CAST(CURRENT_TIMESTAMP AS DATE)
and dtm < DATEADD(DD, 1, CAST(CURRENT_TIMESTAMP AS DATE))
;

Lastly with DATETIME2:

select * from datetimes2
where dtm2 >= CAST(CURRENT_TIMESTAMP AS DATE)
and dtm2 < DATEADD(DD, 1, CAST(CURRENT_TIMESTAMP AS DATE))
;

MySQL: (SQL Fiddle | db<>fiddle)

Using DATE:

select * from dates 
where dte = cast(now() as date)
;

Using DATETIME:

select * from datetimes 
where dtm >= cast((now()) as date)
and dtm < cast((now() + interval 1 day) as date)
;

PostgreSQL: (SQL Fiddle | db<>fiddle)

Using DATE:

select * from dates 
where dte = current_date
;

Using TIMESTAMP WITHOUT TIME ZONE:

select * from timestamps
where ts >= 'today'
and ts < 'tomorrow'
;

Oracle: (SQL Fiddle)

Using DATE:

select to_char(dte, 'YYYY-MM-DD HH24:MI:SS') dte
from dates 
where dte >= trunc(current_date)
and dte < trunc(current_date) + 1
;

Using TIMESTAMP:

select to_char(ts, 'YYYY-MM-DD HH24:MI:SS') ts
from timestamps
where ts >= trunc(current_date)
and ts < trunc(current_date) + 1
;

SQLite: (SQL Fiddle)

Using date strings:

select * from dates 
where dte = (select date('now'))
;

Using date and time strings:

select dtm from datetimes
where dtm >= datetime(date('now'))
and dtm < datetime(date('now', '+1 day'))
;

Using unix timestamps:

select datetime(dtm, 'unixepoch', 'localtime') from datetimes
where dtm >= strftime('%s', date('now'))
and dtm < strftime('%s', date('now', '+1 day'))
;

Backup of SQL Fiddle code

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

This will get you the name of the day:

SELECT DATENAME(weekday, GETDATE())

How can I copy a Python string?

Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]

GDB: Listing all mapped memory regions for a crashed process

If you have the program and the core file, you can do the following steps.

1) Run the gdb on the program along with core file

 $gdb ./test core

2) type info files and see what different segments are there in the core file.

    (gdb)info files

A sample output:

    (gdb)info files 

    Symbols from "/home/emntech/debugging/test".
    Local core dump file:
`/home/emntech/debugging/core', file type elf32-i386.
  0x0055f000 - 0x0055f000 is load1
  0x0057b000 - 0x0057c000 is load2
  0x0057c000 - 0x0057d000 is load3
  0x00746000 - 0x00747000 is load4
  0x00c86000 - 0x00c86000 is load5
  0x00de0000 - 0x00de0000 is load6
  0x00de1000 - 0x00de3000 is load7
  0x00de3000 - 0x00de4000 is load8
  0x00de4000 - 0x00de7000 is load9
  0x08048000 - 0x08048000 is load10
  0x08049000 - 0x0804a000 is load11
  0x0804a000 - 0x0804b000 is load12
  0xb77b9000 - 0xb77ba000 is load13
  0xb77cc000 - 0xb77ce000 is load14
  0xbf91d000 - 0xbf93f000 is load15

In my case I have 15 segments. Each segment has start of the address and end of the address. Choose any segment to search data for. For example lets select load11 and search for a pattern. Load11 has start address 0x08049000 and ends at 0x804a000.

3) Search for a pattern in the segment.

(gdb) find /w 0x08049000 0x0804a000 0x8048034
 0x804903c
 0x8049040
 2 patterns found

If you don't have executable file you need to use a program which prints data of all segments of a core file. Then you can search for a particular data at an address. I don't find any program as such, you can use the program at the following link which prints data of all segments of a core or an executable file.

 http://emntech.com/programs/printseg.c

Sorting int array in descending order

Guava has a method Ints.asList() for creating a List<Integer> backed by an int[] array. You can use this with Collections.sort to apply the Comparator to the underlying array.

List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());

Note that the latter is a live list backed by the actual array, so it should be pretty efficient.

Android Camera Preview Stretched

My requirements are the camera preview need to be fullscreen and keep the aspect ratio. Hesam and Yoosuf's solution was great but I do see a high zoom problem for some reason.

The idea is the same, have the preview container center in parent and increase the width or height depend on the aspect ratios until it can cover the entire screen.

One thing to note is the preview size is in landscape because we set the display orientation.

camera.setDisplayOrientation(90);

The container that we will add the SurfaceView view to:

<RelativeLayout
    android:id="@+id/camera_preview_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"/>

Add the preview to it's container with center in parent in your activity.

this.cameraPreview = new CameraPreview(this, camera);
cameraPreviewContainer.removeAllViews();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
cameraPreviewContainer.addView(cameraPreview, 0, params);

Inside the CameraPreview class:

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.

    if (holder.getSurface() == null) {
        // preview surface does not exist
        return;
    }

    stopPreview();

    // set preview size and make any resize, rotate or
    // reformatting changes here
    try {
        Camera.Size nativePictureSize = CameraUtils.getNativeCameraPictureSize(camera);
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(optimalSize.width, optimalSize.height);
        parameters.setPictureSize(nativePictureSize.width, nativePictureSize.height);
        camera.setParameters(parameters);
        camera.setDisplayOrientation(90);
        camera.setPreviewDisplay(holder);
        camera.startPreview();

    } catch (Exception e){
        Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

    if (supportedPreviewSizes != null && optimalSize == null) {
        optimalSize = CameraUtils.getOptimalSize(supportedPreviewSizes, width, height);
        Log.i(TAG, "optimal size: " + optimalSize.width + "w, " + optimalSize.height + "h");
    }

    float previewRatio =  (float) optimalSize.height / (float) optimalSize.width;
    // previewRatio is height/width because camera preview size are in landscape.
    float measuredSizeRatio = (float) width / (float) height;

    if (previewRatio >= measuredSizeRatio) {
        measuredHeight = height;
        measuredWidth = (int) ((float)height * previewRatio);
    } else {
        measuredWidth = width;
        measuredHeight = (int) ((float)width / previewRatio);
    }
    Log.i(TAG, "Preview size: " + width + "w, " + height + "h");
    Log.i(TAG, "Preview size calculated: " + measuredWidth + "w, " + measuredHeight + "h");

    setMeasuredDimension(measuredWidth, measuredHeight);
}

Beamer: How to show images as step-by-step images

\includegraphics<1>{A}%
\includegraphics<2>{B}%
\includegraphics<3>{C}%

The % is important. This will keep all the images fixed.

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

Java 8 Stream and operation on arrays

There are new methods added to java.util.Arrays to convert an array into a Java 8 stream which can then be used for summing etc.

int sum =  Arrays.stream(myIntArray)
                 .sum();

Multiplying two arrays is a little more difficult because I can't think of a way to get the value AND the index at the same time as a Stream operation. This means you probably have to stream over the indexes of the array.

//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...

int[] result = new int[a.length];

IntStream.range(0, a.length)
         .forEach(i -> result[i] = a[i] * b[i]);

EDIT

Commenter @Holger points out you can use the map method instead of forEach like this:

int[] result = IntStream.range(0, a.length).map(i -> a[i] * b[i]).toArray();

What is the SQL command to return the field names of a table?

You can use the provided system views to do this:

eg

select * from INFORMATION_SCHEMA.COLUMNS
where table_name = '[table name]'

alternatively, you can use the system proc sp_help

eg

sp_help '[table name]'

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Submit form with Enter key without submit button?

@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;.

How to describe table in SQL Server 2008?

May be this can help:

Use MyTest
Go
select * from information_schema.COLUMNS where TABLE_NAME='employee'

{ where: MyTest= DatabaseName Employee= TableName } --Optional conditions

Shell command to sum integers, one per line?

Bit of awk should do it?

awk '{s+=$1} END {print s}' mydatafile

Note: some versions of awk have some odd behaviours if you are going to be adding anything exceeding 2^31 (2147483647). See comments for more background. One suggestion is to use printf rather than print:

awk '{s+=$1} END {printf "%.0f", s}' mydatafile

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

-Wall and -Wextra sets the stage in GCC and the subsequent -Wno-unused-variable may not take effect. For example, if you have:

CFLAGS += -std=c99 -pedantic -pedantic-errors -Werror -g0 -Os \ -fno-strict-overflow -fno-strict-aliasing \ -Wall -Wextra \ -pthread \ -Wno-unused-label \ -Wno-unused-function \ -Wno-unused-parameter \ -Wno-unused-variable \ $(INC)

then GCC sees the instruction -Wall -Wextra and seems to ignore -Wno-unused-variable

This can instead look like this below and you get the desired effect of not being stopped in your compile on the unused variable:

CFLAGS += -std=c99 -pedantic -pedantic-errors -Werror -g0 -Os \ -fno-strict-overflow -fno-strict-aliasing \ -pthread \ -Wno-unused-label \ -Wno-unused-function \ $(INC)

There is a good reason it is called a "warning" vs an "error". Failing the compile just because you code is not complete (say you are stubbing the algorithm out) can be defeating.

How can I set a custom date time format in Oracle SQL Developer?

For anyone still having an issue with this; I happened to find this page from Google...

Put it in like this (NLS Parameters)... it sticks for me in SQLDeveloper v3.0.04:

DD-MON-YY HH12:MI:SS AM or for 24-Hour, DD-MON-YY HH24:MI:SS 

What is a View in Oracle?

If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.
See materialized views

How to get directory size in PHP

Object Oriented Approach :

/**
 * Returns a directory size
 *
 * @param string $directory
 *
 * @return int $size directory size in bytes
 *
 */
function dir_size($directory)
{
    $size = 0;
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file)
    {
        $size += $file->getSize();
    }
    return $size;
}

Fast and Furious Approach :

function dir_size2($dir)
{
    $line = exec('du -sh ' . $dir);
    $line = trim(str_replace($dir, '', $line));
    return $line;
}

I want to execute shell commands from Maven's pom.xml

Here's what's been working for me:

<plugin>
  <artifactId>exec-maven-plugin</artifactId>
  <groupId>org.codehaus.mojo</groupId>
  <executions>
    <execution><!-- Run our version calculation script -->
      <id>Version Calculation</id>
      <phase>generate-sources</phase>
      <goals>
        <goal>exec</goal>
      </goals>
      <configuration>
        <executable>${basedir}/scripts/calculate-version.sh</executable>
      </configuration>
    </execution>
  </executions>
</plugin>

Find files in a folder using Java

Appache commons IO various

FilenameUtils.wildcardMatch

See Apache javadoc here. It matches the wildcard with the filename. So you can use this method for your comparisons.

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

To me it feels like you have missing header files for popen, which is a C system library.

Check if you have installed xcode successful with the command line tools and have accepted the license.

See this thread for more information: How to install Xcode Command Line Tools

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"

Is it possible to get element from HashMap by its position?

If you want to maintain the order in which you added the elements to the map, use LinkedHashMap as opposed to just HashMap.

Here is an approach that will allow you to get a value by its index in the map:

public Object getElementByIndex(LinkedHashMap map,int index){
    return map.get( (map.keySet().toArray())[ index ] );
}

GridView - Show headers on empty data source

I was using asp sqlDataSource. It worked for me when I set the CancelSelectOnNullParameter to false as below:

<asp:SqlDataSource ID="SqlData1" runat="server" ConnectionString="" SelectCommand="myStoredProcedure" SelectCommandType="StoredProcedure" CancelSelectOnNullParameter="False"> </asp:SqlDataSource>

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

I am using this method to avoid the popup blocker in my React code. it will work in all other javascript codes also.

When you are making an async call on click event, just open a blank window first and then write the URL in that later when an async call will complete.

const popupWindow = window.open("", "_blank");
popupWindow.document.write("<div>Loading, Plesae wait...</div>")

on async call's success, write the following

popupWindow.document.write(resonse.url)

shuffling/permutating a DataFrame in pandas

You can use sklearn.utils.shuffle() (requires sklearn 0.16.1 or higher to support Pandas data frames):

# Generate data
import pandas as pd
df = pd.DataFrame({'A':range(5), 'B':range(5)})
print('df: {0}'.format(df))

# Shuffle Pandas data frame
import sklearn.utils
df = sklearn.utils.shuffle(df)
print('\n\ndf: {0}'.format(df))

outputs:

df:    A  B
0  0  0
1  1  1
2  2  2
3  3  3
4  4  4


df:    A  B
1  1  1
0  0  0
3  3  3
4  4  4
2  2  2

Then you can use df.reset_index() to reset the index column, if needs to be:

df = df.reset_index(drop=True)
print('\n\ndf: {0}'.format(df)

outputs:

df:    A  B
0  1  1
1  0  0
2  4  4
3  2  2
4  3  3

Is it possible to change the radio button icon in an android radio button group

In case you want to do it programmatically,

checkBoxOrRadioButton.setButtonDrawable(null);
checkBoxOrRadioButton.setBackgroundResource(R.drawable.resource_name);

Printing a char with printf

This is supposed to print the ASCII value of the character, as %d is the escape sequence for an integer. So the value given as argument of printf is taken as integer when printed.

char ch = 'a';
printf("%d", ch);

Same holds for printf("%d", '\0');, where the NULL character is interpreted as the 0 integer.

Finally, sizeof('\n') is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.

It all depends on the interpretation you give to the bytes.

How to pick an image from gallery (SD Card) for my app?

You have to start the gallery intent for a result.

Intent i = new Intent(Intent.ACTION_PICK,
               android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, ACTIVITY_SELECT_IMAGE); 

Then in onActivityForResult, call intent.getData() to get the Uri of the Image. Then you need to get the Image from the ContentProvider.

Cleaning `Inf` values from an R dataframe

Another solution:

    dat <- data.frame(a = rep(c(1,Inf), 1e6), b = rep(c(Inf,2), 1e6), 
                      c = rep(c('a','b'),1e6),d = rep(c(1,Inf), 1e6),  
                      e = rep(c(Inf,2), 1e6))
    system.time(dat[dat==Inf] <- NA)

#   user  system elapsed
#  0.316   0.024   0.340

How do you UrlEncode without using System.Web?

Here's an example of sending a POST request that properly encodes parameters using application/x-www-form-urlencoded content type:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "param1", "value1" },
        { "param2", "value2" },
    };
    var result = client.UploadValues("http://foo.com", values);
}

Batch: Remove file extension

If your variable is an argument, you can simply use %~dpn (for paths) or %~n (for names only) followed by the argument number, so you don't have to worry for varying extension lengths.

For instance %~dpn0 will return the path of the batch file without its extension, %~dpn1 will be %1 without extension, etc.

Whereas %~n0 will return the name of the batch file without its extension, %~n1 will be %1 without path and extension, etc.

How can I output leading zeros in Ruby?

Use the % operator with a string:

irb(main):001:0> "%03d" % 5
=> "005"

The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:

irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"

Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C function printf, but similar formating functions are available in perl, ruby, python, java, php, etc.

Only read selected columns

You do it like this:

df = read.table("file.txt", nrows=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
colClasses = as.list(apply(df, 2, class))
needCols = c("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
colClasses[!names(colClasses) %in% needCols] = list(NULL)
df = read.table("file.txt", header=TRUE, colClasses=colClasses, sep="\t", stringsAsFactors=FALSE)

Best way to get value from Collection by index

use for each loop...

ArrayList<Character> al = new ArrayList<>();    
String input="hello";

for (int i = 0; i < input.length(); i++){
    al.add(input.charAt(i));
}

for (Character ch : al) {               
    System.Out.println(ch);             
}

How can I add an image file into json object?

You will need to read the bytes from that File into a byte[] and put that object into your JSONObject.

You should also have a look at the following posts :

Hope this helps.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

I ran into a similar error when creating a custom view class, that was because somehow one of the outlet got hooked up twice in the XIB file(I think I initially control dragged the control directly to the code, but latter control dragged again from the File's owner). I opened the XIB file and remove one of them, after that everything worked fine. Hopefully this helps.

Can you test google analytics on a localhost address?

After spending about two hours trying to come up with a solution I realized that I had adblockers blocking the call to GA. Once I turned them off I was good to go.

How to suppress "unused parameter" warnings in C?

I usually write a macro like this:

#define UNUSED(x) (void)(x)

You can use this macro for all your unused parameters. (Note that this works on any compiler.)

For example:

void f(int x) {
    UNUSED(x);
    ...
}

How to make a simple image upload using Javascript/HTML

<li class="list-group-item active"><h5>Feaured Image</h5></li>
            <li class="list-group-item">
                <div class="input-group mb-3">
                    <div class="custom-file ">
                        <input type="file"  class="custom-file-input" name="thumbnail" id="thumbnail">
                        <label class="custom-file-label" for="thumbnail">Choose file</label>
                    </div>
                </div>
                <div class="img-thumbnail  text-center">
                    <img src="@if(isset($product)) {{asset('storage/'.$product->thumbnail)}} @else {{asset('images/no-thumbnail.jpeg')}} @endif" id="imgthumbnail" class="img-fluid" alt="">
                </div>
            </li>
<script>
$(function(){
$('#thumbnail').on('change', function() {
    var file = $(this).get(0).files;
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.addEventListener("load", function(e) {
    var image = e.target.result;
$("#imgthumbnail").attr('src', image);
});
});
}
</script>

Char Comparison in C

In C the char type has a numeric value so the > operator will work just fine for example

#include <stdio.h>
main() {

    char a='z';

    char b='h';

    if ( a > b ) {
        printf("%c greater than %c\n",a,b);
    }
}

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

MVC Calling a view from a different controller

To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.

public class CommentsController : Controller
{
    public ActionResult Index()
    { 
        return View("../Articles/Index", model );
    }
}

and

public class ArticlesController : Controller
{
    public ActionResult Index()
    { 
        return View();
    }
}

Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.