Programs & Examples On #Tabactivity

This tag is related to android TabActivity. It is an activity that contains and runs multiple embedded activities or views.

android : Error converting byte to dex

In my case the problem was because of capital letters in some packages.

Android TabLayout Android Design

I've just managed to setup new TabLayout, so here are the quick steps to do this (????)?*:???

  1. Add dependencies inside your build.gradle file:

    dependencies {
        compile 'com.android.support:design:23.1.1'
    }
    
  2. Add TabLayout inside your layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
    
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"/>
    
        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    </LinearLayout>
    
  3. Setup your Activity like this:

    import android.os.Bundle;
    import android.support.design.widget.TabLayout;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    
    public class TabLayoutActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_pull_to_refresh);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
            ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    
            if (toolbar != null) {
                setSupportActionBar(toolbar);
            }
    
            viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
            tabLayout.setupWithViewPager(viewPager);
        }
    
        public class SectionPagerAdapter extends FragmentPagerAdapter {
    
            public SectionPagerAdapter(FragmentManager fm) {
                super(fm);
            }
    
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        return new FirstTabFragment();
                    case 1:
                    default:
                        return new SecondTabFragment();
                }
            }
    
            @Override
            public int getCount() {
                return 2;
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "First Tab";
                    case 1:
                    default:
                        return "Second Tab";
                }
            }
        }
    
    }
    

Using intents to pass data between activities

Main Activity

public class MainActivity extends Activity {

    EditText user, password;
    Button login;

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

        user = (EditText) findViewById(R.id.username_edit);
        password = (EditText) findViewById(R.id.edit_password);
        login = (Button) findViewById(R.id.btnSubmit);
        login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Second.class);

                String uservalue = user.getText().toString();
                String name_value = password.getText().toString();
                String password_value = password.getText().toString();

                intent.putExtra("username", uservalue);
                intent.putExtra("password", password_value);
                startActivity(intent);
            }
        });
    }
}

Second Activity in which you want to receive Data

public class Second extends Activity{

    EditText name, pass;
    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);

        name = (EditText) findViewById(R.id.editText1);
        pass = (EditText) findViewById(R.id.editText2);

        String value = getIntent().getStringExtra("username");
        String pass_val = getIntent().getStringExtra("password");
        name.setText(value);
        pass.setText(pass_val);
    }
}

java.lang.RuntimeException: Unable to start activity ComponentInfo

I had the same issue, I cleaned and rebuilt the project and it worked.

How to return a result (startActivityForResult) from a TabHost Activity?

Oh, god! After spending several hours and downloading the Android sources, I have finally come to a solution.

If you look at the Activity class, you will see, that finish() method only sends back the result if there is a mParent property set to null. Otherwise the result is lost.

public void finish() {
    if (mParent == null) {
        int resultCode;
        Intent resultData;
        synchronized (this) {
            resultCode = mResultCode;
            resultData = mResultData;
        }
        if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
        try {
            if (ActivityManagerNative.getDefault()
                .finishActivity(mToken, resultCode, resultData)) {
                mFinished = true;
            }
        } catch (RemoteException e) {
            // Empty
        }
    } else {
        mParent.finishFromChild(this);
    }
}

So my solution is to set result to the parent activity if present, like that:

Intent data = new Intent();
 [...]
if (getParent() == null) {
    setResult(Activity.RESULT_OK, data);
} else {
    getParent().setResult(Activity.RESULT_OK, data);
}
finish();

I hope that will be helpful if someone looks for this problem workaround again.

Android: How to detect double-tap?

Improvised dhruvi code

public abstract class DoubleClickListener implements View.OnClickListener {

private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds

long lastClickTime = 0;
boolean tap = true;

@Override
public void onClick(View v) {
    long clickTime = System.currentTimeMillis();
    if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
        onDoubleClick(v);
        tap = false;
    } else
        tap = true;

    v.postDelayed(new Runnable() {
        @Override
        public void run() {
            if(tap)
                onSingleClick();
        }
    },DOUBLE_CLICK_TIME_DELTA);

    lastClickTime = clickTime;
}

public abstract void onDoubleClick(View v);

public abstract void onSingleClick();
}

Error : ORA-01704: string literal too long

What are you using when operate with CLOB?

In all events you can do it with PL/SQL

DECLARE
  str varchar2(32767);
BEGIN
  str := 'Very-very-...-very-very-very-very-very-very long string value';
  update t1 set col1 = str;
END;
/

Proof link on SQLFiddle

understanding private setters

A private setter is useful if you have a read only property and don't want to explicitly declare the backing variable.

So:

public int MyProperty
{
    get; private set;
}

is the same as:

private int myProperty;
public int MyProperty
{
    get { return myProperty; }
}

For non auto implemented properties it gives you a consistent way of setting the property from within your class so that if you need validation etc. you only have it one place.

To answer your final question the MSDN has this to say on private setters:

However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, it is recommended to make the objects immutable by declaring the set accessor as private.

From the MSDN page on Auto Implemented properties

How to reset or change the passphrase for a GitHub SSH key?

  1. Log in to your github account.
  2. Go to the "Settings" page (the "wrench and screwdriver" icon in the top right corner of the page).
  3. Go to "SSH keys" page.
  4. Generate a new SSH key (probably studying the links provided by github on that page).
  5. Add your new key using the "Add SSH key" link.
  6. Verify your new key works.
  7. Make gitub forget your old key by using the "Delete" link next to it in the list of known keys.

How To Run PHP From Windows Command Line in WAMPServer

I remember one time when I stumbled upon this issue a few years ago, it's because windows don't have readline, therefore no interactive shell, to use php interactive mode without readline support, you can do this instead:

C:\>php -a 
Interactive mode enabled 

<?php 
echo "Hello, world!"; 
?> 
^Z 
Hello, world!

After entering interactive mode, type using opening (<?php) and closing (?>) php tag, and end with control Z (^Z) which denotes the end of file.

I also recall that I found the solution from php's site user comment: http://www.php.net/manual/en/features.commandline.interactive.php#105729

Timeout on a function call

I have a different proposal which is a pure function (with the same API as the threading suggestion) and seems to work fine (based on suggestions on this thread)

def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
    import signal

    class TimeoutError(Exception):
        pass

    def handler(signum, frame):
        raise TimeoutError()

    # set the timeout handler
    signal.signal(signal.SIGALRM, handler) 
    signal.alarm(timeout_duration)
    try:
        result = func(*args, **kwargs)
    except TimeoutError as exc:
        result = default
    finally:
        signal.alarm(0)

    return result

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

how to install python distutils

you can use sudo apt-get install python3-distutils by root permission.

i believe it worked here

Could not reserve enough space for object heap to start JVM

It looks like the machine you're trying to run this on has only 256 MB memory.

Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.

Try starting your Java program with a smaller heap size, for example:

java -Xms16m ...

Radio buttons and label to display in same line

I'm assuming the problem is that they are wrapping onto separate lines when the window is too narrow. As others have pointed out, by default the label and input should be "display:inline;", so unless you have other style rules that are changing this, they should render on the same line if there is room.

Without changing the markup, there will be no way to fix this using only CSS.

The simplest way to fix it would be to wrap the radio button and label in a block element, such as a p or a div, and then prevent that from wrapping by using white-space:nowrap. For example:

<div style="white-space:nowrap;">
  <label for="one">First Item</label>
  <input type="radio" id="one" name="first_item" value="1" />
</div>

SQL Server AS statement aliased column within WHERE statement

I am not sure why you cannot use "lat" but, if you must you can rename the columns in a derived table.

select latitude from (SELECT lat AS latitude FROM poi_table) p where latitude < 500

How do you use window.postMessage across domains?

Probably you try to send your data from mydomain.com to www.mydomain.com or reverse, NOTE you missed "www". http://mydomain.com and http://www.mydomain.com are different domains to javascript.

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

Just ran into this problem myself. OSx Lion hides scrollbars while not in use to make it seem more "slick", but at the same time the issue you addressed comes up: people sometimes cannot see whether a div has a scroll feature or not.

The fix: In your css include -

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

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

_x000D_
_x000D_
/* always show scrollbars */_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
  -webkit-appearance: none;_x000D_
  width: 7px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
  border-radius: 4px;_x000D_
  background-color: rgba(0, 0, 0, .5);_x000D_
  box-shadow: 0 0 1px rgba(255, 255, 255, .5);_x000D_
}_x000D_
_x000D_
_x000D_
/* css for demo */_x000D_
_x000D_
#container {_x000D_
  height: 4em;_x000D_
  /* shorter than the child */_x000D_
  overflow-y: scroll;_x000D_
  /* clip height to 4em and scroll to show the rest */_x000D_
}_x000D_
_x000D_
#child {_x000D_
  height: 12em;_x000D_
  /* taller than the parent to force scrolling */_x000D_
}_x000D_
_x000D_
_x000D_
/* === ignore stuff below, it's just to help with the visual. === */_x000D_
_x000D_
#container {_x000D_
  background-color: #ffc;_x000D_
}_x000D_
_x000D_
#child {_x000D_
  margin: 30px;_x000D_
  background-color: #eee;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="child">Example</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

customize the apperance as needed. Source

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;

javascript - pass selected value from popup window to parent window input box

(parent window)

<html> 
<script language="javascript"> 
function openWindow() { 
  window.open("target.html","_blank","height=200,width=400, status=yes,toolbar=no,menubar=no,location=no"); 
} 
</script> 
<body> 
<form name=frm> 
<input id=text1 type=text> 
<input type=button onclick="javascript:openWindow()" value="Open window.."> 
</form> 
</body> 
</html>

(child window)

<html> 
<script language="javascript"> 
function changeParent() { 
  window.opener.document.getElementById('text1').value="Value changed..";
  window.close();
} 
</script> 
<body> 
<form> 
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value.."> 
</form> 
</body> 
</html>

http://www.codehappiness.com/post/access-parent-window-from-child-window-or-access-child-window-from-parent-window-using-javascript.aspx

How to write a multidimensional array to a text file?

There exist special libraries to do just that. (Plus wrappers for python)

hope this helps

Removing pip's cache?

On my mac I had to remove the cache directory ~/Library/Caches/pip/

How to secure the ASP.NET_SessionId cookie?

To add the ; secure suffix to the Set-Cookie http header I simply used the <httpCookies> element in the web.config:

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>

IMHO much more handy than writing code as in the article of Anubhav Goyal.

See: http://msdn.microsoft.com/en-us/library/ms228262(v=vs.100).aspx

Jquery Smooth Scroll To DIV - Using ID value from Link

Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :

<div id="searchbycharacter">
    <a class="searchbychar" href="#" data-target="numeric">0-9 |</a> 
    <a class="searchbychar" href="#" data-target="A"> A |</a> 
    <a class="searchbychar" href="#" data-target="B"> B |</a> 
    <a class="searchbychar" href="#" data-target="C"> C |</a> 
    ... Untill Z
</div>

As for the jquery :

$(document).on('click','.searchbychar', function(event) {
    event.preventDefault();
    var target = "#" + this.getAttribute('data-target');
    $('html, body').animate({
        scrollTop: $(target).offset().top
    }, 2000);
});

How to sort an array in descending order in Ruby

Simple Solution from ascending to descending and vice versa is:

STRINGS

str = ['ravi', 'aravind', 'joker', 'poker']
asc_string = str.sort # => ["aravind", "joker", "poker", "ravi"]
asc_string.reverse # => ["ravi", "poker", "joker", "aravind"]

DIGITS

digit = [234,45,1,5,78,45,34,9]
asc_digit = digit.sort # => [1, 5, 9, 34, 45, 45, 78, 234]
asc_digit.reverse # => [234, 78, 45, 45, 34, 9, 5, 1]

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I solved this problem by removing --deploy-mode cluster from spark-submit code. By default , spark submit takes client mode which has following advantage :

1. It opens up Netty HTTP server and distributes all jars to the worker nodes.
2. Driver program runs on master node , which means dedicated resources to driver process.

While in cluster mode :

 1.  It runs on worker node.
 2. All the jars need to be placed in a common folder of the cluster so that it is accessible to all the worker nodes or in folder of each worker node.

Here it's not able to access hive metastore due to unavailability of hive jar to any of the nodes in cluster. enter image description here

Case insensitive searching in Oracle

you can do something like that:

where regexp_like(name, 'string$', 'i');

Read XML Attribute using XmlDocument

You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.

Then the code would be something similar to

string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;

Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.

cURL equivalent in Node.js?

The http module that you use to run servers is also used to make remote requests.

Here's the example in their docs:

var http = require("http");

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

Android: Storing username and password?

Most Android and iPhone apps I have seen use an initial screen or dialog box to ask for credentials. I think it is cumbersome for the user to have to re-enter their name/password often, so storing that info makes sense from a usability perspective.

The advice from the (Android dev guide) is:

In general, we recommend minimizing the frequency of asking for user credentials -- to make phishing attacks more conspicuous, and less likely to be successful. Instead use an authorization token and refresh it.

Where possible, username and password should not be stored on the device. Instead, perform initial authentication using the username and password supplied by the user, and then use a short-lived, service-specific authorization token.

Using the AccountManger is the best option for storing credentials. The SampleSyncAdapter provides an example of how to use it.

If this is not an option to you for some reason, you can fall back to persisting credentials using the Preferences mechanism. Other applications won't be able to access your preferences, so the user's information is not easily exposed.

Float a div right, without impacting on design

If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:

position:absolute;
right:0;
top:0;

If you want it to float at the right of a particular parent section, you can add position: relative to that section.

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

MySQL: can't access root account

There is a section in the MySQL manual on how to reset the root password which will solve your problem.

How to get table cells evenly spaced?

Take the width of the table and divide it by the number of cell ().

PerformanceTable {width:500px;}    
PerformanceTable.td {width:100px;}

If the table dynamically widens or shrinks you could dynamically increase the cell size with a little javascript.

Changing the CommandTimeout in SQL Management studio

Changing Command Execute Timeout in Management Studio:

Click on Tools -> Options

Select Query Execution from tree on left side and enter command timeout in "Execute Timeout" control.

Changing Command Timeout in Server:

In the object browser tree right click on the server which give you timeout and select "Properties" from context menu.

Now in "Server Properties -....." dialog click on "Connections" page in "Select a Page" list (on left side). On the right side you will get property

Remote query timeout (in seconds, 0 = no timeout):
[up/down control]

you can set the value in up/down control.

How to lose margin/padding in UITextView?

On iOS 5 UIEdgeInsetsMake(-8,-8,-8,-8); seems to work great.

How to merge rows in a column into one cell in excel?

If you prefer to do this without VBA, you can try the following:

  1. Have your data in cells A1:A999 (or such)
  2. Set cell B1 to "=A1"
  3. Set cell B2 to "=B1&A2"
  4. Copy cell B2 all the way down to B999 (e.g. by copying B2, selecting cells B3:B99 and pasting)

Cell B999 will now contain the concatenated text string you are looking for.

How do I open a second window from the first window in WPF?

You can use this code:

private void OnClickNavigate(object sender, RoutedEventArgs e)
{
    NavigatedWindow navigatesWindow = new NavigatedWindow();
    navigatesWindow.ShowDialog();
}

How to use protractor to check if an element is visible?

I had a similar issue, in that I only wanted return elements that were visible in a page object. I found that I'm able to use the css :not. In the case of this issue, this should do you...

expect($('i.icon-spinner:not(.ng-hide)').isDisplayed()).toBeTruthy();

In the context of a page object, you can get ONLY those elements that are visible in this way as well. Eg. given a page with multiple items, where only some are visible, you can use:

this.visibileIcons = $$('i.icon:not(.ng-hide)'); 

This will return you all visible i.icons

could not access the package manager. is the system running while installing android application

In my case it was just that the emulator took 9 minutes to start. Wait until you see the lock icon on the emulator LCD. Or use actual tablet or phone.

Git pushing to remote branch

git push --set-upstream origin <branch_name>_test

--set-upstream sets the association between your local branch and the remote. You only have to do it the first time. On subsequent pushes you can just do:

git push

If you don't have origin set yet, use:

git remote add origin <repository_url> then retry the above command.

Android - How to get application name? (Not package name)

If you know Package name then Use following snippet

ApplicationInfo ai;
try {
    ai = pm.getApplicationInfo(packageName, 0);
} catch (final NameNotFoundException e) {
    ai = null;
}
final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

"Get" request with appending headers transform to "Options" request. So Cors policy problems occur. You have to implement "Options" request to your server.

Finding the length of an integer in C

The number of digits of an integer x is equal to 1 + log10(x). So you can do this:

#include <math.h>
#include <stdio.h>

int main()
{
    int x;
    scanf("%d", &x);
    printf("x has %d digits\n", 1 + (int)log10(x));
}

Or you can run a loop to count the digits yourself: do integer division by 10 until the number is 0:

int numDigits = 0;
do
{
    ++numDigits;
    x = x / 10;
} while ( x );

You have to be a bit careful to return 1 if the integer is 0 in the first solution and you might also want to treat negative integers (work with -x if x < 0).

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

How to edit an Android app?

First you have to download file x-plore and installed it.. After that open it and find the thoes you want to edit.. After that just rename the file Xyz.apk to xyz.zip After that open that file and you can see some folders.. then just go and edit the app..

How do I access the $scope variable in browser's console using AngularJS?

This requires jQuery to be installed as well, but works perfectly for a dev environment. It looks through each element to get the instances of the scopes then returns them labelled with there controller names. Its also removing any property start with a $ which is what angularjs generally uses for its configuration.

let controllers = (extensive = false) => {
            let result = {};
            $('*').each((i, e) => {
                let scope = angular.element(e).scope();
                if(Object.prototype.toString.call(scope) === '[object Object]' && e.hasAttribute('ng-controller')) {
                    let slimScope = {};
                    for(let key in scope) {
                        if(key.indexOf('$') !== 0 && key !== 'constructor' || extensive) {
                            slimScope[key] = scope[key];
                        }
                    }
                    result[$(e).attr('ng-controller')] = slimScope;
                }
            });

            return result;
        }

How to check if a map contains a key in Go?

    var d map[string]string
    value, ok := d["key"]
    if ok {
        fmt.Println("Key Present ", value)
    } else {
        fmt.Println(" Key Not Present ")
    }

How to load a controller from another controller in codeigniter?

Create a helper using the code I created belows and name it controller_helper.php.

Autoload your helper in the autoload.php file under config.

From your method call controller('name') to load the controller.

Note that name is the filename of the controller.

This method will append '_controller' to your controller 'name'. To call a method in the controller just run $this->name_controller->method(); after you load the controller as described above.

<?php

if(!function_exists('controller'))
{
    function controller($name)
    {
        $filename = realpath(__dir__ . '/../controllers/'.$name.'.php');

        if(file_exists($filename))
        {
            require_once $filename;

            $class = ucfirst($name);

            if(class_exists($class))
            {
                $ci =& get_instance();

                if(!isset($ci->{$name.'_controller'}))
                {
                    $ci->{$name.'_controller'} = new $class();
                }
            }
        }
    }
}
?>

Connecting an input stream to an outputstream

Use org.apache.commons.io.IOUtils

InputStream inStream = new ...
OutputStream outStream = new ...
IOUtils.copy(inStream, outStream);

or copyLarge for size >2GB

Select a Column in SQL not in Group By

You can join the table on itself to get the PK:

Select cpe1.PK, cpe2.MaxDate, cpe1.fmgcms_cpeclaimid 
from Filteredfmgcms_claimpaymentestimate cpe1
INNER JOIN
(
    select MAX(createdon) As MaxDate, fmgcms_cpeclaimid 
    from Filteredfmgcms_claimpaymentestimate
    group by fmgcms_cpeclaimid
) cpe2
    on cpe1.fmgcms_cpeclaimid = cpe2.fmgcms_cpeclaimid
    and cpe1.createdon = cpe2.MaxDate
where cpe1.createdon < 'reportstartdate'

Get fragment (value after hash '#') from a URL in php

I found this trick if you insist want the value with PHP. split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP

How to add an element to Array and shift indexes?

Try this

public static int [] insertArry (int inputArray[], int index, int value){
    for(int i=0; i< inputArray.length-1; i++) {

        if (i == index){

            for (int j = inputArray.length-1; j >= index; j-- ){
                inputArray[j]= inputArray[j-1];
            }

            inputArray[index]=value;
        }

    }
    return inputArray;
}

Catch checked change event of a checkbox

The click will affect a label if we have one attached to the input checkbox?

I think that is better to use the .change() function

<input type="checkbox" id="something" />

$("#something").change( function(){
  alert("state changed");
});

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

You can use as below:

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

iOS how to set app icon and launch images

Update: Unless you love resizing icons one by one, check out Schmoudi's answer. It's just a lot easier.

Icon sizes

enter image description here

Above image from Designing for iOS 9. They are the same for iOS 10.

How to Set the App Icon

Click Assets.xcassets in the Project navigator and then choose AppIcon.

enter image description here

This will give you an empty app icon set.

enter image description here

Now just drag the right sized image (in .png format) from Finder onto every blank in the app set. The app icon should be all set up now.

How to create the right sized images

The image at the very top tells the pixels sizes for for each point size that is required in iOS 9. However, even if I don't get this answer updated for future versions of iOS, you can still figure out the correct pixel sizes using the method below.

Look at how many points (pt) each blank on the empty image set is. If the image is 1x then the pixels are the same as the points. For 2x double the points and 3x triple the points. So, for example, in the first blank above (29pt 2x) you would need a 58x58 pixel image.

You can start with a 1024x1024 pixel image and then downsize it to the correct sizes. You can do it yourself or there are also websites and scripts for getting the right sizes. Do a search for "ios app icon generator" or something similar.

I don't think the names matter as long as you get the dimensions right, but the general naming convention is as follows:

Icon-29.png      // 29x29 pixels
[email protected]   // 58x58 pixels
[email protected]   // 87x87 pixels

Launch Image

Although you can use an image for the launch screen, consider using a launch screen storyboard file. This will conveniently resize for every size and orientation. Check out this SO answer or the following documentation for help with this.

Useful documentation

The Xcode images in this post were created with Xcode 7.

How to permanently remove few commits from remote branch

Just note to use the last_working_commit_id, when reverting a non-working commit

git reset --hard <last_working_commit_id>

So we must not reset to the commit_id that we don't want.

Then sure, we must push to remote branch:

git push --force

Codeigniter: does $this->db->last_query(); execute a query?

For me save_queries option was turned off so,

$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;

Ref: Can't get result from $this->db->last_query(); codeigniter

Difference between Static methods and Instance methods

Instance method vs Static method

  1. Instance method can access the instance methods and instance variables directly.

  2. Instance method can access static variables and static methods directly.

  3. Static methods can access the static variables and static methods directly.

  4. Static methods can’t access instance methods and instance variables directly. They must use reference to object. And static method can’t use this keyword as there is no instance for ‘this’ to refer to.

SQL how to increase or decrease one for a int column in one command

@dotjoe It is cheaper to update and check @@rowcount, do an insert after then fact.

Exceptions are expensive && updates are more frequent

Suggestion: If you want to be uber performant in your DAL, make the front end pass in a unique ID for the row to be updated, if null insert.

The DALs should be CRUD, and not need to worry about being stateless.

If you make it stateless, With good indexes, you will not see a diff with the following SQL vs 1 statement. IF (select top 1 * form x where PK=@ID) Insert else update

Get Application Name/ Label via ADB Shell or Terminal

just enter the following command on command prompt after launching the app:

adb shell dumpsys window windows | find "mCurrentFocus"

if executing the command on linux terminal replace find by grep

Python assigning multiple variables to same value? list behavior

Cough cough

>>> a,b,c = (1,2,3)
>>> a
1
>>> b
2
>>> c
3
>>> a,b,c = ({'test':'a'},{'test':'b'},{'test':'c'})
>>> a
{'test': 'a'}
>>> b
{'test': 'b'}
>>> c
{'test': 'c'}
>>> 

Insert NULL value into INT column

If the column has the NOT NULL constraint then it won't be possible; but otherwise this is fine:

INSERT INTO MyTable(MyIntColumn) VALUES(NULL);

Why do we always prefer using parameters in SQL statements?

Old post but wanted to ensure newcomers are aware of Stored procedures.

My 10¢ worth here is that if you are able to write your SQL statement as a stored procedure, that in my view is the optimum approach. I ALWAYS use stored procs and never loop through records in my main code. For Example: SQL Table > SQL Stored Procedures > IIS/Dot.NET > Class.

When you use stored procedures, you can restrict the user to EXECUTE permission only, thus reducing security risks.

Your stored procedure is inherently paramerised, and you can specify input and output parameters.

The stored procedure (if it returns data via SELECT statement) can be accessed and read in the exact same way as you would a regular SELECT statement in your code.

It also runs faster as it is compiled on the SQL Server.

Did I also mention you can do multiple steps, e.g. update a table, check values on another DB server, and then once finally finished, return data to the client, all on the same server, and no interaction with the client. So this is MUCH faster than coding this logic in your code.

How to split a large text file into smaller files with equal number of lines?

you can also use awk

awk -vc=1 'NR%200000==0{++c}{print $0 > c".txt"}' largefile

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Call a Class From another class

Suposse you have

Class1

public class Class1 {
    //Your class code above
}

Class2

public class Class2 {
}

and then you can use Class2 in different ways.

Class Field

public class Class1{
    private Class2 class2 = new Class2();
}

Method field

public class Class1 {
    public void loginAs(String username, String password)
    {
         Class2 class2 = new Class2();
         class2.invokeSomeMethod();
         //your actual code
    }
}

Static methods from Class2 Imagine this is your class2.

public class Class2 {
     public static void doSomething(){
     }
}

from class1 you can use doSomething from Class2 whenever you want

public class Class1 {
    public void loginAs(String username, String password)
    {
         Class2.doSomething();
         //your actual code
    }
}

How can I execute Shell script in Jenkinsfile?

Previous answers are correct but here is one more way of doing this and some tips:

Option #1 Go to you Jenkins job and search for "add build step" and then just copy and paste your script there

Option #2 Go to Jenkins and do the same again "add build step" but this time put the fully qualified path for your script in there example : ./usr/somewhere/helloWorld.sh

enter image description here enter image description here

things to watch for /tips:

  • Environment variables, if your job is running at the same time then you need to worry about concurrency issues. One job may be setting the value of environment variables and the next may use the value or take some action based on that incorrectly.
  • Make sure all paths are fully qualified
  • Think about logging /var/log or somewhere so you would also have something to go to on the server (optional)
  • thing about space issue and permissions, running out of space and permission issues are very common in linux environment
  • Alerting and make sure your script/job fails the jenkin jobs when your script fails

'\r': command not found - .bashrc / .bash_profile

For the Emacs users out there:

  1. Open the file
  2. M-x set-buffer-file-coding-system
  3. Select "unix"

This will update the new characters in the file to be unix style. More info on "Newline Representation" in Emacs can be found here:

http://ergoemacs.org/emacs/emacs_line_ending_char.html

Note: The above steps could be made into an Emacs script if one preferred to execute this from the command line.

Can I create a One-Time-Use Function in a Script or Stored Procedure?

You can create temp stored procedures like:

create procedure #mytemp as
begin
   select getdate() into #mytemptable;
end

in an SQL script, but not functions. You could have the proc store it's result in a temp table though, then use that information later in the script ..

shared global variables in C

In the header file write it with extern. And at the global scope of one of the c files declare it without extern.

setHintTextColor() in EditText

You could call editText.invalidate() after you reset the hint color. That could resolve your issue. Actually the SDK update the color in the same way.

AngularJS multiple filter with custom filter function

In view file (HTML or EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

and In Controller

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}

Check if a string contains a string in C++

If you don't want to use standard library functions, below is one solution.

#include <iostream>
#include <string>

bool CheckSubstring(std::string firstString, std::string secondString){
    if(secondString.size() > firstString.size())
        return false;

    for (int i = 0; i < firstString.size(); i++){
        int j = 0;
        // If the first characters match
        if(firstString[i] == secondString[j]){
            int k = i;
            while (firstString[i] == secondString[j] && j < secondString.size()){
                j++;
                i++;
            }
            if (j == secondString.size())
                return true;
            else // Re-initialize i to its original value
                i = k;
        }
    }
    return false;
}

int main(){
    std::string firstString, secondString;

    std::cout << "Enter first string:";
    std::getline(std::cin, firstString);

    std::cout << "Enter second string:";
    std::getline(std::cin, secondString);

    if(CheckSubstring(firstString, secondString))
        std::cout << "Second string is a substring of the frist string.\n";
    else
        std::cout << "Second string is not a substring of the first string.\n";

    return 0;
}

Django: List field in model?

It's quite an old topic, but since it is returned when searching for "django list field" I'll share the custom django list field code I modified to work with Python 3 and Django 2. It supports the admin interface now and not uses eval (which is a huge security breach in Prashant Gaur's code).

from django.db import models
from typing import Iterable

class ListField(models.TextField):
    """
    A custom Django field to represent lists as comma separated strings
    """

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs['token'] = self.token
        return name, path, args, kwargs

    def to_python(self, value):

        class SubList(list):
            def __init__(self, token, *args):
                self.token = token
                super().__init__(*args)

            def __str__(self):
                return self.token.join(self)

        if isinstance(value, list):
            return value
        if value is None:
            return SubList(self.token)
        return SubList(self.token, value.split(self.token))

    def from_db_value(self, value, expression, connection):
        return self.to_python(value)

    def get_prep_value(self, value):
        if not value:
            return
        assert(isinstance(value, Iterable))
        return self.token.join(value)

    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return self.get_prep_value(value)

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

How do I clear a C++ array?

std::fill(a.begin(),a.end(),0);

Generating Request/Response XML from a WSDL

I use SOAPUI 5.3.0, it has an option for creating requests/responses (also using WSDL), you can even create a mock service which will respond when you send request. Procedure is as follows:

  1. Right click on your project and select New Mock Service option which will create mock service.
  2. Right click on mock service and select New Mock Operation option which will create response which you can use as template.

EDIT #1:

Check out the SoapUI link for the latest version. There is a Pro version as well as the free open source version.

What programming language does facebook use?

Facebook uses the LAMP stack, so if you want to get a career with them you're going to want to focus on that. In addition they often have C++ and/or Java listed in their requirements as well.

One of the postings includes the following requirements:

  • Expertise with C++ and/or Java
  • Knowledge of Perl or PHP or Python
  • Knowledge of relational databases and SQL, preferably MySQL and Oracle

Another:

  • Expertise in PHP, JavaScript, and CSS.

Another:

  • Knowledge of Perl or PHP or Python
  • Knowledge of relational databases and
  • SQL, preferably MySQL Knowledge of
  • web technologies: XHTML, JavaScript Experience with C, C++ a plus

Source

http://www.facebook.com/careers/#!/careers/department.php?dept=engineering

Also, do any other social networking sites use the same language?

Some other companys that use PHP/LAMP Stack:

How do you move a file?

Check out section 5.14.2. Moving files and folders (or check out "move" in the Index of the help) of the TortoiseSVN help. You do a move via right-dragging. It also mentions that you need to commit from the parent folder to make it "one" revision. This works for doing the change in a working copy.

(Note that the SVN items in the following image will only show up if the destination folder has already been added to the repository.)

tortoise move menu

You can also do the move via the Repo Browser (section 5.23. The Repository Browser of the help).

How to get an enum value from a string value in Java?

public static MyEnum getFromValue(String value) {
    MyEnum resp = null;
    MyEnum nodes[] = values();
    for(int i = 0; i < nodes.length; i++) {
        if(nodes[i].value.equals(value)) {
            resp = nodes[i];
            break;
        }
    }
    return resp;
}

Generate random int value from 3 to 6

Here is the simple and single line of code

For this use the SQL Inbuild RAND() function.

Here is the formula to generate random number between two number (RETURN INT Range)

Here a is your First Number (Min) and b is the Second Number (Max) in Range

SELECT FLOOR(RAND()*(b-a)+a)

Note: You can use CAST or CONVERT function as well to get INT range number.

( CAST(RAND()*(25-10)+10 AS INT) )

Example:

SELECT FLOOR(RAND()*(25-10)+10);

Here is the formula to generate random number between two number (RETURN DECIMAL Range)

SELECT RAND()*(b-a)+a;

Example:

SELECT RAND()*(25-10)+10;

More details check this: https://www.techonthenet.com/sql_server/functions/rand.php

Create SQL identity as primary key?

If you're using T-SQL, the only thing wrong with your code is that you used braces {} instead of parentheses ().

PS: Both IDENTITY and PRIMARY KEY imply NOT NULL, so you can omit that if you wish.

SQL to Entity Framework Count Group-By

with EF 6.2 it worked for me

  var query = context.People
               .GroupBy(p => new {p.name})
               .Select(g => new { name = g.Key.name, count = g.Count() });

How can I retrieve the remote git address of a repo?

The long boring solution, which is not involved with CLI, you can manually navigate to:

your local repo folder ? .git folder (hidden) ? config file

then choose your text editor to open it and look for url located under the [remote "origin"] section.

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

Add line break within tooltips

This css will help you.

    .tooltip {
      word-break: break-all;
    }

or if you want in one line

    .tooltip-inner {
      max-width: 100%;
    }

How to specify names of columns for x and y when joining in dplyr?

This feature has been added in dplyr v0.3. You can now pass a named character vector to the by argument in left_join (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:

left_join(test_data, kantrowitz, by = c("first_name" = "name"))

How to quickly check if folder is empty (.NET)?

I don't know about the performance statistics on this one, but have you tried using the Directory.GetFiles() static method ?

It returns a string array containing filenames (not FileInfos) and you can check the length of the array in the same way as above.

Get a pixel from HTML Canvas?

Note that getImageData returns a snapshot. Implications are:

  • Changes will not take effect until subsequent putImageData
  • getImageData and putImageData calls are relatively slow

Print empty line?

You can just do

print()

to get an empty line.

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Sticky footer with fixed height:

HTML scheme:

<body>
   <div id="wrap">
   </div>
   <div id="footer">
   </div>
</body>

CSS:

html, body {
    height: 100%;
}
#wrap {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -60px;
}
#footer {
    height: 60px;
}

Best way to check for "empty or null value"

If database having large number of records then null check can take more time you can use null check in different ways like : 1) where columnname is null 2) where not exists() 3) WHERE (case when columnname is null then true end)

how to remove pagination in datatable

if you want to remove pagination and but want ordering of dataTable then add this script at the end of your page!

_x000D_
_x000D_
<script>_x000D_
$(document).ready(function() {        _x000D_
    $('#table_id').DataTable({_x000D_
        "paging":   false,_x000D_
       "info":     false_x000D_
    } );_x000D_
      _x000D_
  } );_x000D_
</script>
_x000D_
_x000D_
_x000D_

Seconds CountDown Timer

You need a public class for Form1 to initialize.

See this code:

namespace TimerApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private int counter = 60;
        private void button1_Click(object sender, EventArgs e)
        {
            //Insert your code from before
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //Again insert your code
        }
    }
}

I've tried this and it all worked fine

If you need anymore help feel free to comment :)

accepting HTTPS connections with self-signed certificates

The following main steps are required to achieve a secured connection from Certification Authorities which are not considered as trusted by the android platform.

As requested by many users, I've mirrored the most important parts from my blog article here:

  1. Grab all required certificates (root and any intermediate CA’s)
  2. Create a keystore with keytool and the BouncyCastle provider and import the certs
  3. Load the keystore in your android app and use it for the secured connections (I recommend to use the Apache HttpClient instead of the standard java.net.ssl.HttpsURLConnection (easier to understand, more performant)

Grab the certs

You have to obtain all certificates that build a chain from the endpoint certificate the whole way up to the Root CA. This means, any (if present) Intermediate CA certs and also the Root CA cert. You don’t need to obtain the endpoint certificate.

Create the keystore

Download the BouncyCastle Provider and store it to a known location. Also ensure that you can invoke the keytool command (usually located under the bin folder of your JRE installation).

Now import the obtained certs (don’t import the endpoint cert) into a BouncyCastle formatted keystore.

I didn’t test it, but I think the order of importing the certificates is important. This means, import the lowermost Intermediate CA certificate first and then all the way up to the Root CA certificate.

With the following command a new keystore (if not already present) with the password mysecret will be created and the Intermediate CA certificate will be imported. I also defined the BouncyCastle provider, where it can be found on my file system and the keystore format. Execute this command for each certificate in the chain.

keytool -importcert -v -trustcacerts -file "path_to_cert/interm_ca.cer" -alias IntermediateCA -keystore "res/raw/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "path_to_bouncycastle/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret

Verify if the certificates were imported correctly into the keystore:

keytool -list -keystore "res/raw/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "path_to_bouncycastle/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret

Should output the whole chain:

RootCA, 22.10.2010, trustedCertEntry, Thumbprint (MD5): 24:77:D9:A8:91:D1:3B:FA:88:2D:C2:FF:F8:CD:33:93
IntermediateCA, 22.10.2010, trustedCertEntry, Thumbprint (MD5): 98:0F:C3:F8:39:F7:D8:05:07:02:0D:E3:14:5B:29:43

Now you can copy the keystore as a raw resource in your android app under res/raw/

Use the keystore in your app

First of all we have to create a custom Apache HttpClient that uses our keystore for HTTPS connections:

import org.apache.http.*

public class MyHttpClient extends DefaultHttpClient {

    final Context context;

    public MyHttpClient(Context context) {
        this.context = context;
    }

    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        // Register for port 443 our SSLSocketFactory with our keystore
        // to the ConnectionManager
        registry.register(new Scheme("https", newSslSocketFactory(), 443));
        return new SingleClientConnManager(getParams(), registry);
    }

    private SSLSocketFactory newSslSocketFactory() {
        try {
            // Get an instance of the Bouncy Castle KeyStore format
            KeyStore trusted = KeyStore.getInstance("BKS");
            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
            try {
                // Initialize the keystore with the provided trusted certificates
                // Also provide the password of the keystore
                trusted.load(in, "mysecret".toCharArray());
            } finally {
                in.close();
            }
            // Pass the keystore to the SSLSocketFactory. The factory is responsible
            // for the verification of the server certificate.
            SSLSocketFactory sf = new SSLSocketFactory(trusted);
            // Hostname verification from certificate
            // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
            sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            return sf;
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}

We have created our custom HttpClient, now we can use it for secure connections. For example when we make a GET call to a REST resource:

// Instantiate the custom HttpClient
DefaultHttpClient client = new MyHttpClient(getApplicationContext());
HttpGet get = new HttpGet("https://www.mydomain.ch/rest/contacts/23");
// Execute the GET call and obtain the response
HttpResponse getResponse = client.execute(get);
HttpEntity responseEntity = getResponse.getEntity();

That's it ;)

Erase the current printed console line

i iterates through char array words. j keeps track of word length. "\b \b" erases word while backing over line.

#include<stdio.h>

int main()
{
    int i = 0, j = 0;

    char words[] = "Hello Bye";

    while(words[i]!='\0')
    {
        if(words[i] != ' ') {
            printf("%c", words[i]);
        fflush(stdout);
        }
        else {
            //system("ping -n 1 127.0.0.1>NUL");  //For Microsoft OS
            system("sleep 0.25");
            while(j-->0) {
                printf("\b \b");
            }
        }

        i++;
        j++;
    }

printf("\n");                   
return 0;
}

How to get the sizes of the tables of a MySQL database?

There is an easy way to get many informations using Workbench:

  • Right-click the schema name and click "Schema inspector".

  • In the resulting window you have a number of tabs. The first tab "Info" shows a rough estimate of the database size in MB.

  • The second tab, "Tables", shows Data length and other details for each table.

Hive Alter table change Column Name

In the comments @libjack mentioned a point which is really important. I would like to illustrate more into it. First, we can check what are the columns of our table by describe <table_name>; command. enter image description here

there is a double-column called _c1 and such columns are created by the hive itself when we moving data from one table to another. To address these columns we need to write it inside backticks

`_c1`

Finally, the ALTER command will be,

ALTER TABLE <table_namr> CHANGE `<system_genarated_column_name>` <new_column_name> <data_type>;

Bootstrap 4 Center Vertical and Horizontal Alignment

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
    <div class="col-12 border border-info">_x000D_
          <div class="d-flex justify-content-center align-items-center" style="height: 100px">_x000D_
              <a href="#" class="btn btn-dark">Transfer</a>_x000D_
              <a href="#" class="btn btn-dark mr-2 ml-2">Replenish</a>_x000D_
              <a href="#" class="btn btn-dark mr-3">Account Details</a>_x000D_
          </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Displaying a webcam feed using OpenCV and Python

change import cv to import cv2.cv as cv See also the post here.

TypeError: Router.use() requires middleware function but got a Object

If your are using express above 2.x, you have to declare app.router like below code. Please try to replace your code

app.use('/', routes);

with

app.use(app.router);
routes.initialize(app);

Please click here to get more details about app.router

Note:

app.router is depreciated in express 3.0+. If you are using express 3.0+, refer to Anirudh's answer below.

How to get the query string by javascript?

I have use this method

function getString()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
}
return vars;
}
var buisnessArea = getString();

Modulo operation with negative numbers

C99 requires that when a/b is representable:

(a/b) * b + a%b shall equal a

This makes sense, logically. Right?

Let's see what this leads to:


Example A. 5/(-3) is -1

=> (-1) * (-3) + 5%(-3) = 5

This can only happen if 5%(-3) is 2.


Example B. (-5)/3 is -1

=> (-1) * 3 + (-5)%3 = -5

This can only happen if (-5)%3 is -2

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

What does "implements" do on a class?

An interface defines a simple contract of methods all implementing classes must implement. When a class implements an interface, it must provide implementations for all its methods.

I guess the poster assumes a certain level of knowledge about the language.

Bootstrap NavBar with left, center or right aligned items

<div class="d-flex justify-content-start">hello</div>    
<div class="d-flex justify-content-end">hello</div>
<div class="d-flex justify-content-center">hello</div>
<div class="d-flex justify-content-between">hello</div>
<div class="d-flex justify-content-around">hello</div>

Put the fields that you want to center, right or left according above division.

How to clear input buffer in C?

A portable way to clear up to the end of a line that you've already tried to read partially is:

int c;

while ( (c = getchar()) != '\n' && c != EOF ) { }

This reads and discards characters until it gets \n which signals the end of the file. It also checks against EOF in case the input stream gets closed before the end of the line. The type of c must be int (or larger) in order to be able to hold the value EOF.

There is no portable way to find out if there are any more lines after the current line (if there aren't, then getchar will block for input).

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

What worked with me, in the Storyboard, go to the Navigation Controller, select the navigation bar, click on the Attributes Inspector, then change the style from default to black. That's it!

Get random boolean in Java

Why not use the Random class, which has a method nextBoolean:

import java.util.Random;

/** Generate 10 random booleans. */
public final class MyProgram {

  public static final void main(String... args){

    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      boolean randomBool = randomGenerator.nextBoolean();
      System.out.println("Generated : " + randomBool);
    }
  }
}

What is the intended use-case for git stash?

I know StackOverflow is not the place for opinion based answers, but I actually have a good opinion on when to shelve changes with a stash.

You don't want to commit you experimental changes

When you make changes in your workspace/working tree, if you need to perform any branch based operations like a merge, push, fetch or pull, you must be at a clean commit point. So if you have workspace changes you need to commit them. But what if you don't want to commit them? What if they are experimental? Something you don't want part of your commit history? Something you don't want others to see when you push to GitHub?

You don't want to lose local changes with a hard reset

In that case, you can do a hard reset. But if you do a hard reset you will lose all of your local working tree changes because everything gets overwritten to where it was at the time of the last commit and you'll lose all of your changes.

So, as for the answer of 'when should you stash', the answer is when you need to get back to a clean commit point with a synchronized working tree/index/commit, but you don't want to lose your local changes in the process. Just shelve your changes in a stash and you're good.

And once you've done your stash and then merged or pulled or pushed, you can just stash pop or apply and you're back to where you started from.

Git stash and GitHub

GitHub is constantly adding new features, but as of right now, there is now way to save a stash there. Again, the idea of a stash is that it's local and private. Nobody else can peek into your stash without physical access to your workstation. Kinda the same way git reflog is private with the git log is public. It probably wouldn't be private if it was pushed up to GitHub.

One trick might be to do a diff of your workspace, check the diff into your git repository, commit and then push. Then you can do a pull from home, get the diff and then unwind it. But that's a pretty messy way to achieve those results.

git diff > git-dif-file.diff

pop the stash

ERROR: Sonar server 'http://localhost:9000' can not be reached

When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.

How to fit a smooth curve to my data in R?

The other answers are all good approaches. However, there are a few other options in R that haven't been mentioned, including lowess and approx, which may give better fits or faster performance.

The advantages are more easily demonstrated with an alternate dataset:

sigmoid <- function(x)
{
  y<-1/(1+exp(-.15*(x-100)))
  return(y)
}

dat<-data.frame(x=rnorm(5000)*30+100)
dat$y<-as.numeric(as.logical(round(sigmoid(dat$x)+rnorm(5000)*.3,0)))

Here is the data overlaid with the sigmoid curve that generated it:

Data

This sort of data is common when looking at a binary behavior among a population. For example, this might be a plot of whether or not a customer purchased something (a binary 1/0 on the y-axis) versus the amount of time they spent on the site (x-axis).

A large number of points are used to better demonstrate the performance differences of these functions.

Smooth, spline, and smooth.spline all produce gibberish on a dataset like this with any set of parameters I have tried, perhaps due to their tendency to map to every point, which does not work for noisy data.

The loess, lowess, and approx functions all produce usable results, although just barely for approx. This is the code for each using lightly optimized parameters:

loessFit <- loess(y~x, dat, span = 0.6)
loessFit <- data.frame(x=loessFit$x,y=loessFit$fitted)
loessFit <- loessFit[order(loessFit$x),]

approxFit <- approx(dat,n = 15)

lowessFit <-data.frame(lowess(dat,f = .6,iter=1))

And the results:

plot(dat,col='gray')
curve(sigmoid,0,200,add=TRUE,col='blue',)
lines(lowessFit,col='red')
lines(loessFit,col='green')
lines(approxFit,col='purple')
legend(150,.6,
       legend=c("Sigmoid","Loess","Lowess",'Approx'),
       lty=c(1,1),
       lwd=c(2.5,2.5),col=c("blue","green","red","purple"))

Fits

As you can see, lowess produces a near perfect fit to the original generating curve. Loess is close, but experiences a strange deviation at both tails.

Although your dataset will be very different, I have found that other datasets perform similarly, with both loess and lowess capable of producing good results. The differences become more significant when you look at benchmarks:

> microbenchmark::microbenchmark(loess(y~x, dat, span = 0.6),approx(dat,n = 20),lowess(dat,f = .6,iter=1),times=20)
Unit: milliseconds
                           expr        min         lq       mean     median        uq        max neval cld
  loess(y ~ x, dat, span = 0.6) 153.034810 154.450750 156.794257 156.004357 159.23183 163.117746    20   c
            approx(dat, n = 20)   1.297685   1.346773   1.689133   1.441823   1.86018   4.281735    20 a  
 lowess(dat, f = 0.6, iter = 1)   9.637583  10.085613  11.270911  11.350722  12.33046  12.495343    20  b 

Loess is extremely slow, taking 100x as long as approx. Lowess produces better results than approx, while still running fairly quickly (15x faster than loess).

Loess also becomes increasingly bogged down as the number of points increases, becoming unusable around 50,000.

EDIT: Additional research shows that loess gives better fits for certain datasets. If you are dealing with a small dataset or performance is not a consideration, try both functions and compare the results.

How do I drag and drop files into an application?

In Windows Forms, set the control's AllowDrop property, then listen for DragEnter event and DragDrop event.

When the DragEnter event fires, set the argument's AllowedEffect to something other than none (e.g. e.Effect = DragDropEffects.Move).

When the DragDrop event fires, you'll get a list of strings. Each string is the full path to the file being dropped.

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

From the Intel Instructions

"The SDK Manager will download the installer to the "extras" directory, under the main SDK directory. Even though the SDK manager says "Installed" it actually means that the Intel HAXM executable was downloaded. You will still need to run the installer from the "extras" directory to finish installation.

Extract the installer inside the "extras" directory and follow the installation instructions for your platform."

Best way to get whole number part of a Decimal number

   Public Function getWholeNumber(number As Decimal) As Integer
    Dim round = Math.Round(number, 0)
    If round > number Then
        Return round - 1
    Else
        Return round
    End If
End Function

How do you use bcrypt for hashing passwords in PHP?

Version 5.5 of PHP will have built-in support for BCrypt, the functions password_hash() and password_verify(). Actually these are just wrappers around the function crypt(), and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.

The easiest way to use this functions will be:

$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

This code will hash the password with BCrypt (algorithm 2y), generates a random salt from the OS random source, and uses the default cost parameter (at the moment this is 10). The second line checks, if the user entered password matches an already stored hash-value.

Should you want to change the cost parameter, you can do it like this, increasing the cost parameter by 1, doubles the needed time to calculate the hash value:

$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));

In contrast to the "cost" parameter, it is best to omit the "salt" parameter, because the function already does its best to create a cryptographically safe salt.

For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash() function. For PHP versions before 5.3.7 there is no support for crypt() with 2y, the unicode safe BCrypt algorithm. One could replace it instead with 2a, which is the best alternative for earlier PHP versions.

Is it possible to decompile an Android .apk file?

Sometimes you get broken code, when using dex2jar/apktool, most notably in loops. To avoid this, use jadx, which decompiles dalvik bytecode into java source code, without creating a .jar/.class file first as dex2jar does (apktool uses dex2jar I think). It is also open-source and in active development. It even has a GUI, for GUI-fanatics. Try it!

How to change color in markdown cells ipython/jupyter notebook?

<span style='color:blue '> your message/text </span>

So here it is a perfect html css style entry inside a notebook ipynb file.

Of course you can choose your favourite color here and then your text.

How to fire a button click event from JavaScript in ASP.NET

var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();

That solution works for me, but remember it wont work if your asp button has

Visible="False"

To hide button that should be triggered with that script you should hide it with <div hidden></div>

Get User Selected Range

Selection is its own object within VBA. It functions much like a Range object.

Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

In android how to set navigation drawer header image and name programmatically in class file?

In Kotlin

    val hView = nav_view.getHeaderView(0)
    val textViewName = hView.findViewById(R.id.textViewName) as TextView
    val textViewEmail = hView.findViewById(R.id.textViewEmail) as TextView
    val imgvw = hView.findViewById(R.id.imageView) as ImageView
    imgvw.setImageResource(R.drawable.ic_menu_gallery)

iPhone/iOS JSON parsing tutorial

As of iOS 5.0 Apple provides the NSJSONSerialization class "to convert JSON to Foundation objects and convert Foundation objects to JSON". No external frameworks to incorporate and according to benchmarks its performance is quite good, significantly better than SBJSON.

Open Bootstrap Modal from code-behind

Maybe this answer is so late, but it's useful.
to do it,we have 3 steps:
1- Create a modal structure in HTML.
2- Create a button to call a function in java script, to open modal and set display:none in CSS .
3- Call this button by function in code behind .
you can see these steps in below snippet :

HTML modal:

<div class="modal fade" id="myModal">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">
                                Registration done Successfully</h4>
                        </div>
                        <div class="modal-body">
                            <asp:Label ID="lblMessage" runat="server" />
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">
                                Close</button>
                            <button type="button" class="btn btn-primary">
                                Save changes</button>
                        </div>
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <!-- /.modal -->  

Hidden Button:

<button type="button" style="display: none;" id="btnShowPopup" class="btn btn-primary btn-lg"
                data-toggle="modal" data-target="#myModal">
                Launch demo modal
            </button>    

Script Code:

<script type="text/javascript">
        function ShowPopup() {
            $("#btnShowPopup").click();
        }
    </script>  

code behind:

protected void Page_Load(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup();", true);
    this.lblMessage.Text = "Your Registration is done successfully. Our team will contact you shotly";
}  

this solution is one of any solutions that I used it .

What does an exclamation mark mean in the Swift language?

To put it simply, exclamation marks mean an optional is being unwrapped. An optional is a variable that can have a value or not -- so you can check if the variable is empty, using an if let statement as shown here, and then force unwrap it. If you force unwrap an optional that is empty though, your program will crash, so be careful! Optionals are declared by putting a question mark at the end of an explicit assignment to a variable, for example I could write:

var optionalExample: String?

This variable has no value. If I were to unwrap it, the program would crash and Xcode would tell you you tried to unwrap an optional with a value of nil.

Hope that helped.

WPF TabItem Header Styling

While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.

The Code:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MealNinja"
        mc:Ignorable="d"
        Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
    <Window.Effect>
        <DropShadowEffect Opacity="0.5"/>
    </Window.Effect>
    <Grid Background="#FF423C3C">
        <TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
            <TabControl.Resources>
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
                                        <ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                    <Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
                                </Grid>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="FontWeight" Value="Bold" />
                                        <Setter TargetName="ContentSite" Property="Width" Value="30" />
                                        <Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter Property="FontWeight" Value="Bold" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <ContentPresenter Content="{TemplateBinding Content}">
                                    <ContentPresenter.LayoutTransform>
                                        <RotateTransform Angle="270" />
                                    </ContentPresenter.LayoutTransform>
                                </ContentPresenter>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="Background" Value="#FF6E6C67" />
                    <Setter Property="Height" Value="90" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="FontFamily" Value="DokChampa" />
                    <Setter Property="FontSize" Value="16" />
                    <Setter Property="VerticalAlignment" Value="Top" />
                    <Setter Property="HorizontalAlignment" Value="Right" />
                    <Setter Property="UseLayoutRounding" Value="False" />
                </Style>
                <Style x:Key="tabGrids">
                    <Setter Property="Grid.Background" Value="#FFE5E5E5" />
                    <Setter Property="Grid.Margin" Value="6,10,10,10" />
                </Style>
            </TabControl.Resources>
            <TabItem Header="Planner">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 2">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section III">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 04">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Tools">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Screenshot:

enter image description here

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

Read Post Data submitted to ASP.Net Form

NameValueCollection nvclc = Request.Form;
string   uName= nvclc ["txtUserName"];
string   pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);

How to clear gradle cache?

Take care with gradle daemon, you have to stop it before clear and re-run gradle.

Stop first daemon:

./gradlew --stop

Clean cache using:

rm -rf ~/.gradle/caches/

Run again you compilation

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

How to make div follow scrolling smoothly with jQuery?

That code doesn't work very well i fixed it a little bit

var el = $('.caja-pago');
var elpos_original = el.offset().top;

 $(window).scroll(function(){
     var elpos = el.offset().top;
     var windowpos = $(window).scrollTop();
     var finaldestination = windowpos;
     if(windowpos<elpos_original) {
         finaldestination = elpos_original;
         el.stop().animate({'top':400},500);
     } else {
         el.stop().animate({'top':windowpos+10},500);
     }
 });

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.

COUNT(*) - Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null

COUNT(1) - Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE matches.

COUNT(PK) - The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.

From this you can see the first count is the slowest and the last count is the fastest in Oracle.

how to get last insert id after insert query in codeigniter active record

From the documentation:

$this->db->insert_id()

The insert ID number when performing database inserts.

Therefore, you could use something like this:

$lastid = $this->db->insert_id();

Quick way to retrieve user information Active Directory

Well, if you know where your user lives in the AD hierarchy (e.g. quite possibly in the "Users" container, if it's a small network), you could also bind to the user account directly, instead of searching for it.

DirectoryEntry deUser = new DirectoryEntry("LDAP://cn=John Doe,cn=Users,dc=yourdomain,dc=com");

if (deUser != null)
{
  ... do something with your user
}

And if you're on .NET 3.5 already, you could even use the vastly expanded System.DirectorySrevices.AccountManagement namespace with strongly typed classes for each of the most common AD objects:

// bind to your domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://dc=yourdomain,dc=com");

// find the user by identity (or many other ways)
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "cn=John Doe");

There's loads of information out there on System.DirectoryServices.AccountManagement - check out this excellent article on MSDN by Joe Kaplan and Ethan Wilansky on the topic.

Bootstrap button drop-down inside responsive table not visible because of scroll

my 2¢ quick global fix:

// drop down in responsive table

(function () {
  $('.table-responsive').on('shown.bs.dropdown', function (e) {
    var $table = $(this),
        $menu = $(e.target).find('.dropdown-menu'),
        tableOffsetHeight = $table.offset().top + $table.height(),
        menuOffsetHeight = $menu.offset().top + $menu.outerHeight(true);

    if (menuOffsetHeight > tableOffsetHeight)
      $table.css("padding-bottom", menuOffsetHeight - tableOffsetHeight);
  });

  $('.table-responsive').on('hide.bs.dropdown', function () {
    $(this).css("padding-bottom", 0);
  })
})();

Explications: When a dropdown-menu inside a '.table-responsive' is shown, it calculate the height of the table and expand it (with padding) to match the height required to display the menu. The menu can be any size.

In my case, this is not the table that has the '.table-responsive' class, it's a wrapping div:

<div class="table-responsive" style="overflow:auto;">
    <table class="table table-hover table-bordered table-condensed server-sort">

So the $table var in the script is actually a div! (just to be clear... or not) :)

Note: I wrap it in a function so my IDE can collapse function ;) but it's not mandatory!

MVC4 input field placeholder

This works:

@Html.TextBox("name", null,  new { placeholder = "Text" })

Collection that allows only unique items in .NET?

You may look into something kind of Unique List as follows

public class UniqueList<T>
{
    public List<T> List
    {
        get;
        private set;
    }
    List<T> _internalList;

    public static UniqueList<T> NewList
    {
        get
        {
            return new UniqueList<T>();
        }
    }

    private UniqueList()
    {            
        _internalList = new List<T>();
        List = new List<T>();
    }

    public void Add(T value)
    {
        List.Clear();
        _internalList.Add(value);
        List.AddRange(_internalList.Distinct());
        //return List;
    }

    public void Add(params T[] values)
    {
        List.Clear();
        _internalList.AddRange(values);
        List.AddRange(_internalList.Distinct());
       // return List;
    }

    public bool Has(T value)
    {
        return List.Contains(value);
    }
}

and you can use it like follows

var uniquelist = UniqueList<string>.NewList;
uniquelist.Add("abc","def","ghi","jkl","mno");
uniquelist.Add("abc","jkl");
var _myList = uniquelist.List;

will only return "abc","def","ghi","jkl","mno" always even when duplicates are added to it

Using Default Arguments in a Function

In PHP 8 we can use named arguments for this problem.

So we could solve the problem described by the original poster of this question:

What if I want to use the default argument for $x and set a different argument for $y?

With:

foo(blah: "blah", y: "test");

Reference: https://wiki.php.net/rfc/named_params (in particular the "Skipping defaults" section)

Determining image file size + dimensions via Javascript?

Getting the Original Dimensions of the Image

If you need to get the original image dimensions (not in the browser context), clientWidth and clientHeight properties do not work since they return incorrect values if the image is stretched/shrunk via css.

To get original image dimensions, use naturalHeight and naturalWidth properties.

var img = document.getElementById('imageId'); 

var width = img.naturalWidth;
var height = img.naturalHeight;

p.s. This does not answer the original question as the accepted answer does the job. This, instead, serves like addition to it.

Remove header and footer from window.print()

@page { margin: 0; } works fine in Chrome and Firefox. I haven't found a way to fix IE through css. But you can go into Page Setup in IE on your own machine at and set the margins to 0. Press alt and then the file menu in the top left corner and you'll find Page Setup. This only works for the one machine at a time...

get next and previous day with PHP

always make sure to have set your default timezone

date_default_timezone_set('Europe/Berlin');

create DateTime instance, holding the current datetime

$datetime = new DateTime();

create one day interval

$interval = new DateInterval('P1D');

modify the DateTime instance

$datetime->sub($interval);

display the result, or print_r($datetime); for more insight

echo $datetime->format('Y-m-d');

TIP:

If you don't want to change the default timezone, use the DateTimeZone class instead.

$myTimezone = new DateTimeZone('Europe/Berlin');
$datetime->setTimezone($myTimezone); 

or just include it inside the constructor in this form new DateTime("now", $myTimezone);

Setting background colour of Android layout element

4 possible ways, use one you need.

1. Kotlin

val ll = findViewById<LinearLayout>(R.id.your_layout_id)
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white))

2. Data Binding

<LinearLayout
    android:background="@{@color/white}"

OR more useful statement-

<LinearLayout
    android:background="@{model.colorResId}"

3. XML

<LinearLayout
    android:background="#FFFFFF"

<LinearLayout
    android:background="@color/white"

4. Java

LinearLayout ll = (LinearLayout) findViewById(R.id.your_layout_id);
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white));

Ifelse statement in R with multiple conditions

another solution using dplyr is:

df <- ## your data ##
df <- df %>%
        mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))

Countdown timer in React

Basic idea showing counting down using Date.now() instead of subtracting one which will drift over time.

_x000D_
_x000D_
class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      time: {
        hours: 0,
        minutes: 0,
        seconds: 0,
        milliseconds: 0,
      },
      duration: 2 * 60 * 1000,
      timer: null
    };
    this.startTimer = this.start.bind(this);
  }

  msToTime(duration) {
    let milliseconds = parseInt((duration % 1000));
    let seconds = Math.floor((duration / 1000) % 60);
    let minutes = Math.floor((duration / (1000 * 60)) % 60);
    let hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

    hours = hours.toString().padStart(2, '0');
    minutes = minutes.toString().padStart(2, '0');
    seconds = seconds.toString().padStart(2, '0');
    milliseconds = milliseconds.toString().padStart(3, '0');

    return {
      hours,
      minutes,
      seconds,
      milliseconds
    };
  }

  componentDidMount() {}

  start() {
    if (!this.state.timer) {
      this.state.startTime = Date.now();
      this.timer = window.setInterval(() => this.run(), 10);
    }
  }

  run() {
    const diff = Date.now() - this.state.startTime;
    
    // If you want to count up
    // this.setState(() => ({
    //  time: this.msToTime(diff)
    // }));
    
    // count down
    let remaining = this.state.duration - diff;
    if (remaining < 0) {
      remaining = 0;
    }
    this.setState(() => ({
      time: this.msToTime(remaining)
    }));
    if (remaining === 0) {
      window.clearTimeout(this.timer);
      this.timer = null;
    }
  }

  render() {
    return ( <
      div >
      <
      button onClick = {
        this.startTimer
      } > Start < /button> {
        this.state.time.hours
      }: {
        this.state.time.minutes
      }: {
        this.state.time.seconds
      }. {
        this.state.time.milliseconds
      }:
      <
      /div>
    );
  }
}

ReactDOM.render( < Example / > , document.getElementById('View'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>
_x000D_
_x000D_
_x000D_

getElementsByClassName not working

There are several issues:

  1. Class names (and IDs) are not allowed to start with a digit.
  2. You have to pass a class to getElementsByClassName().
  3. You have to iterate of the result set.

Example (untested):

<script type="text/javascript">
function hideTd(className){
    var elements = document.getElementsByClassName(className);
    for(var i = 0, length = elements.length; i < length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
  <tr>
    <td class="td">not empty</td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
</table>
</body>

Note that getElementsByClassName() is not available up to and including IE8.

Update:

Alternatively you can give the table an ID and use:

var elements = document.getElementById('tableID').getElementsByTagName('td');

to get all td elements.

To hide the parent row, use the parentNode property of the element:

elements[i].parentNode.style.display = "none";

Make flex items take content width, not width of parent container

In addtion to align-self you can also consider auto margin which will do almost the same thing

_x000D_
_x000D_
.container {_x000D_
  background: red;_x000D_
  height: 200px;_x000D_
  flex-direction: column;_x000D_
  padding: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
a {_x000D_
  margin-right:auto;_x000D_
  padding: 10px 40px;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
  <a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get array keys in Javascript?

If you are doing any kind of array/collection manipulation or inspection I highly recommend using Underscore.js. It's small, well-tested and will save you days/weeks/years of javascript headache. Here is its keys function:

Keys

Retrieve all the names of the object's properties.

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

Eventviewer eventid for lock and unlock

The event IDs to look for in pre-Vista Windows are 528, 538, and 680. 528 usually stands for successful unlock of workstation.

The codes for newer Windows versions differ, see below answers for more infos.

How do I fix the indentation of an entire file in Vi?

1G=G. That should indent all the lines in the file. 1G takes you the first line, = will start the auto-indent and the final G will take you the last line in the file.

How to remove all duplicate items from a list

Use set():

woduplicates = set(lseparatedOrblist)

Returns a set without duplicates. If you, for some reason, need a list back:

woduplicates = list(set(lseperatedOrblist))

This will, however, have a different order than your original list.

How to dynamically change the color of the selected menu item of a web page?

I use PHP to find the URL and match the page name (without the extension of .php, also I can add multiple pages that all have the same word in common like contact, contactform, etc. All will have that class added) and add a class with PHP to change the color, etc. For that you would have to save your pages with file extension .php.

Here is a demo. Change your links and pages as required. The CSS class for all the links is .tab and for the active link there is also another class of .currentpage (as is the PHP function) so that is where you will overwrite your CSS rules. You could name them whatever you like.

<?php # Using REQUEST_URI
    $currentpage = $_SERVER['REQUEST_URI'];?>
    <div class="nav">
        <div class="tab
             <?php
                 if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
                     echo " currentpage";
             ?>"><a href="index.php">Home</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/services/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="services.php">Services</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/about/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="about.php">About</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/contact/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="contact.php">Contact</a>
         </div>
     </div> <!--nav-->

Google Maps Android API v2 Authorization failure

I followed the same step provided in the Google Doc but i was getting the same error. Later i realized that i was signing my app with my app.keystore and the SHA key that i was using to generate the API key was the debug one.

So i simply removed the signingConfig signingConfig.generic from by build.gradle file and my map started to work fine.

Hope this helps someone.

Manifest Merger failed with multiple errors in Android Studio

As a newbie to Android Studio, in my case, I had moved an existing project from Eclipse to Android Studio and found that there was a duplicate definition of an activity within my Manifest.xml that hadn't been picked up by Eclipse was shown as a Gradle error.

I found this by going to the Gradle Console (bottom right of the screen).

How to Batch Rename Files in a macOS Terminal?

you can install rename command by using brew. just do brew install rename and use it.

What are the proper permissions for an upload folder with PHP/Apache?

I will add that if you are using SELinux that you need to make sure the type context is tmp_t You can accomplish this by using the chcon utility

chcon -t tmp_t uploads

How to Handle Button Click Events in jQuery?

$('#btnSubmit').click(function(){
    alert("button");
});

or

//Use this code if button is appended in the DOM
$(document).on('click','#btnSubmit',function(){
    alert("button");
});

See documentation for more information:
https://api.jquery.com/click/

How to debug external class library projects in visual studio?

I was having a similar issue as my breakpoints in project(B) were not being hit. My solution was to rebuild project(B) then debug project(A) as the dlls needed to be updated.

Visual studio should allow you to debug into an external library.

importing a CSV into phpmyadmin

In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :

enter image description here

Get a list of all the files in a directory (recursive)

The following works for me in Gradle / Groovy for build.gradle for an Android project, without having to import groovy.io.FileType (NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):

FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
    println "Proguard file located and processed: " + it
}

How to combine paths in Java?

The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing, such as the concat() method.

How do you copy and paste into Git Bash

Use Shift + Insert like in linux bash

Edit: It works even in putty.

Timestamp Difference In Hours for PostgreSQL

Get fields where a timestamp is greater than date in postgresql:

SELECT * from yourtable 
WHERE your_timestamp_field > to_date('05 Dec 2000', 'DD Mon YYYY');

Subtract minutes from timestamp in postgresql:

SELECT * from yourtable 
WHERE your_timestamp_field > current_timestamp - interval '5 minutes'

Subtract hours from timestamp in postgresql:

SELECT * from yourtable 
WHERE your_timestamp_field > current_timestamp - interval '5 hours'

How to use setprecision in C++

#include <iostream>
#include <iomanip>
 
int main(void) 
{
    float value;
    cin >> value;
    cout << setprecision(4) << value;
    return 0;
}

IndexError: too many indices for array

I think the problem is given in the error message, although it is not very easy to spot:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None).

This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function.

I highly recommend in your for loop inserting:

print(data)

This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Loading custom functions in PowerShell

You have to dot source them:

. .\build_funtions.ps1
. .\build_builddefs.ps1

Note the extra .

This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

How to read a list of files from a folder using PHP?

<html>
<head>
<title>Names</title>
</head>
<body style="background-color:powderblue;">

<form method='post' action='alex.php'>
 <input type='text' name='name'>
<input type='submit' value='name'>
</form>
Enter Name:
<?php

  if($_POST)
  {
  $Name = $_POST['name'];
  $count = 0;
  $fh=fopen("alex.txt",'a+') or die("failed to create");
  while(!feof($fh))
  {
    $line = chop(fgets($fh));
    if($line==$Name && $line!="")
    $count=1;
  }
  if($count==0 && $Name!="")
  {
    fwrite($fh, "\r\n$Name"); 
 }
  else if($count!=0 && $line!="") 
  { 
    echo '<font color="red">'.$Name.', the name you entered is already in the list.</font><br><br>';
  }
  $count=0;
  fseek($fh, 0);
  while(!feof($fh))
  {
    $a = chop(fgets($fh));
    echo $a.'<br>';
    $count++;
  }
  if($count<=1)
  echo '<br>There are no names in the list<br>';
  fclose($fh);
  }
?>
</body>
</html>

Spring MVC 4: "application/json" Content Type is not being set correctly

I had the dependencies as specified @Greg post. I still faced the issue and could be able to resolve it by adding following additional jackson dependency:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.7.4</version>
</dependency>

Difference between static memory allocation and dynamic memory allocation

Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.

Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.

Converting a datetime string to timestamp in Javascript

Date.parse() isn't a constructor, its a static method.

So, just use

var timeInMillis = Date.parse(s);

instead of

var timeInMillis = new Date.parse(s);

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

mysql->SHOW PROCESSLIST;
kill xxxx; 

and then kill which one in sleep. In my case it is 2456.

enter image description here

Communication between tabs or windows

I wrote an article on this on my blog: http://www.ebenmonney.com/blog/how-to-implement-remember-me-functionality-using-token-based-authentication-and-localstorage-in-a-web-application .

Using a library I created storageManager you can achieve this as follows:

storageManager.savePermanentData('data', 'key'): //saves permanent data
storageManager.saveSyncedSessionData('data', 'key'); //saves session data to all opened tabs
storageManager.saveSessionData('data', 'key'); //saves session data to current tab only
storageManager.getData('key'); //retrieves data

There are other convenient methods as well to handle other scenarios as well

How to convert Windows end of line in Unix end of line (CR/LF to LF)

Actually, vim does allow what you're looking for. Enter vim, and type the following commands:

:args **/*.java
:argdo set ff=unix | update | next

The first of these commands sets the argument list to every file matching **/*.java, which is all Java files, recursively. The second of these commands does the following to each file in the argument list, in turn:

  • Sets the line-endings to Unix style (you already know this)
  • Writes the file out iff it's been changed
  • Proceeds to the next file

Rename all files in a folder with a prefix in a single command

Try the rename command in the folder with the files:

rename 's/^/Unix_/' *

The argument of rename (sed s command) indicates to replace the regex ^ with Unix_. The caret (^) is a special character that means start of the line.

Encrypt and decrypt a string in C#?

If you are using ASP.Net you can now use built in functionality in .Net 4.0 onwards.

System.Web.Security.MachineKey

.Net 4.5 has MachineKey.Protect() and MachineKey.Unprotect().

.Net 4.0 has MachineKey.Encode() and MachineKey.Decode(). You should just set the MachineKeyProtection to 'All'.

Outside of ASP.Net this class seems to generate a new key with every app restart so doesn't work. With a quick peek in ILSpy it looks to me like it generates its own defaults if the appropriate app.settings are missing. So you may actually be able to set it up outside ASP.Net.

I haven't been able to find a non-ASP.Net equivalent outside the System.Web namespace.

Position last flex item at the end of container

This flexbox principle also works horizontally

During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Setting an automatic left margin for the Last Item will do the work.

.last-item {
  margin-left: auto;
}

Code Example:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  width: 400px;_x000D_
  outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  margin: 5px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p class="last-item"></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Codepen Snippet

This can be very useful for Desktop Footers.

As Envato did here with the company logo.

Codepen Snippet

How to install PyQt4 on Windows using pip?

install PyQt5 for Windows 10 and python 3.5+.

pip install PyQt5

How to get all count of mongoose model?

You should give an object as argument

userModel.count({name: "sam"});

or

userModel.count({name: "sam"}).exec(); //if you are using promise

or

userModel.count({}); // if you want to get all counts irrespective of the fields

On the recent version of mongoose, count() is deprecated so use

userModel.countDocuments({name: "sam"});

SSH to Vagrant box in Windows?

Another option using git binaries:

  1. Install git: http://git-scm.com/download/win
  2. Start Menu > cmd (shift+enter to go as Administrator)
  3. set PATH=%PATH%;C:\Program Files\Git\usr\bin
  4. vagrant ssh

Hope this helps :)

Just a bonus after months using that on Windows: use Console instead of the Win terminal, so you can always open a new terminal tab with PATH set (configure it on options)

Is log(n!) = T(n·log(n))?

I realize this is a very old question with an accepted answer, but none of these answers actually use the approach suggested by the hint.

It is a pretty simple argument:

n! (= 1*2*3*...*n) is a product of n numbers each less than or equal to n. Therefore it is less than the product of n numbers all equal to n; i.e., n^n.

Half of the numbers -- i.e. n/2 of them -- in the n! product are greater than or equal to n/2. Therefore their product is greater than the product of n/2 numbers all equal to n/2; i.e. (n/2)^(n/2).

Take logs throughout to establish the result.

element with the max height from a set of elements

_x000D_
_x000D_
function startListHeight($tag) {_x000D_
  _x000D_
    function setHeight(s) {_x000D_
        var max = 0;_x000D_
        s.each(function() {_x000D_
            var h = $(this).height();_x000D_
            max = Math.max(max, h);_x000D_
        }).height('').height(max);_x000D_
    }_x000D_
  _x000D_
    $(window).on('ready load resize', setHeight($tag));_x000D_
}_x000D_
_x000D_
jQuery(function($) {_x000D_
    $('#list-lines').each(function() {_x000D_
        startListHeight($('li', this));_x000D_
    });_x000D_
});
_x000D_
#list-lines {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
#list-lines li {_x000D_
    float: left;_x000D_
    display: table;_x000D_
    width: 33.3334%;_x000D_
    list-style-type: none;_x000D_
}_x000D_
_x000D_
#list-lines li img {_x000D_
    width: 100%;_x000D_
    height: auto;_x000D_
}_x000D_
_x000D_
#list-lines::after {_x000D_
    content: "";_x000D_
    display: block;_x000D_
    clear: both;_x000D_
    overflow: hidden;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
_x000D_
<ul id="list-lines">_x000D_
    <li>_x000D_
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="" />_x000D_
        <br /> Line 1_x000D_
        <br /> Line 2_x000D_
    </li>_x000D_
    <li>_x000D_
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="" />_x000D_
        <br /> Line 1_x000D_
        <br /> Line 2_x000D_
        <br /> Line 3_x000D_
        <br /> Line 4_x000D_
    </li>_x000D_
    <li>_x000D_
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="" />_x000D_
        <br /> Line 1_x000D_
    </li>_x000D_
    <li>_x000D_
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="" />_x000D_
        <br /> Line 1_x000D_
        <br /> Line 2_x000D_
    </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to use particular CSS styles based on screen size / device

@media queries serve this purpose. Here's an example:

@media only screen and (max-width: 991px) and (min-width: 769px){
 /* CSS that should be displayed if width is equal to or less than 991px and larger 
  than 768px goes here */
}

@media only screen and (max-width: 991px){
 /* CSS that should be displayed if width is equal to or less than 991px goes here */
}

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Getting indices of True values in a boolean list

Using element-wise multiplication and a set:

>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> set(multiply(states,range(1,len(states)+1))-1).difference({-1})

Output: {4, 5, 7}

How do I import a .sql file in mysql database using PHP?

I have Test your code, this error shows when you already have the DB imported or with some tables with the same name, also the Array error that shows is because you add in in the exec parenthesis, here is the fixed version:

<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlDatabaseName ='test';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='dbbackupmember.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
$output=array();
exec($command,$output,$worked);
switch($worked){
    case 0:
        echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
        break;
    case 1:
        echo 'There was an error during import.';
        break;
}
?> 

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

SELECT RTRIM(' Author ') AS Name;

Output will be without any trailing spaces.

Name —————— ‘ Author’

Access camera from a browser

There is a really cool solution from Danny Markov for that. It uses navigator.getUserMedia method and should work in modern browsers. I have tested it successfully with Firefox and Chrome. IE didn't work:

Here is a demo:

https://tutorialzine.github.io/pwa-photobooth/

Link to Danny Markovs description page:

http://tutorialzine.com/2016/09/everything-you-should-know-about-progressive-web-apps/

Link to GitHub:

https://github.com/tutorialzine/pwa-photobooth/

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

Regular expression negative lookahead

If you revise your regular expression like this:

drupal-6.14/(?=sites(?!/all|/default)).*
             ^^

...then it will match all inputs that contain drupal-6.14/ followed by sites followed by anything other than /all or /default. For example:

drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall

Changing ?= to ?! to match your original regex simply negates those matches:

drupal-6.14/(?!sites(?!/all|/default)).*
             ^^

So, this simply means that drupal-6.14/ now cannot be followed by sites followed by anything other than /all or /default. So now, these inputs will satisfy the regex:

drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42

But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/ is followed by anything other than sites as well. For example:

drupal-6.14/foo
drupal-6.14/xsites

Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14 except those subdirectories of sites whose name begins with anything other than all or default.

Swift programmatically navigate to another view controller/scene

According to @jaiswal Rajan in his answer. You can do a pushViewController like this:

let storyBoard: UIStoryboard = UIStoryboard(name: "NewBotStoryboard", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "NewViewController") as! NewViewController
self.navigationController?.pushViewController(newViewController, animated: true)

JavaScript: filter() for Objects

First of all, it's considered bad practice to extend Object.prototype. Instead, provide your feature as utility function on Object, just like there already are Object.keys, Object.assign, Object.is, ...etc.

I provide here several solutions:

  1. Using reduce and Object.keys
  2. As (1), in combination with Object.assign
  3. Using map and spread syntax instead of reduce
  4. Using Object.entries and Object.fromEntries

1. Using reduce and Object.keys

With reduce and Object.keys to implement the desired filter (using ES6 arrow syntax):

_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
    Object.keys(obj)_x000D_
          .filter( key => predicate(obj[key]) )_x000D_
          .reduce( (res, key) => (res[key] = obj[key], res), {} );_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

Note that in the above code predicate must be an inclusion condition (contrary to the exclusion condition the OP used), so that it is in line with how Array.prototype.filter works.

2. As (1), in combination with Object.assign

In the above solution the comma operator is used in the reduce part to return the mutated res object. This could of course be written as two statements instead of one expression, but the latter is more concise. To do it without the comma operator, you could use Object.assign instead, which does return the mutated object:

_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
    Object.keys(obj)_x000D_
          .filter( key => predicate(obj[key]) )_x000D_
          .reduce( (res, key) => Object.assign(res, { [key]: obj[key] }), {} );_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

3. Using map and spread syntax instead of reduce

Here we move the Object.assign call out of the loop, so it is only made once, and pass it the individual keys as separate arguments (using the spread syntax):

_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
    Object.assign(...Object.keys(obj)_x000D_
                    .filter( key => predicate(obj[key]) )_x000D_
                    .map( key => ({ [key]: obj[key] }) ) );_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

4. Using Object.entries and Object.fromEntries

As the solution translates the object to an intermediate array and then converts that back to a plain object, it would be useful to make use of Object.entries (ES2017) and the opposite (i.e. create an object from an array of key/value pairs) with Object.fromEntries (ES2019).

It leads to this "one-liner" method on Object:

_x000D_
_x000D_
Object.filter = (obj, predicate) => _x000D_
                  Object.fromEntries(Object.entries(obj).filter(predicate));_x000D_
_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
};_x000D_
_x000D_
var filtered = Object.filter(scores, ([name, score]) => score > 1); _x000D_
console.log(filtered);
_x000D_
_x000D_
_x000D_

The predicate function gets a key/value pair as argument here, which is a bit different, but allows for more possibilities in the predicate function's logic.

JS map return object

If you want to alter the original objects, then a simple Array#forEach will do:

rockets.forEach(function(rocket) {
    rocket.launches += 10;
});

If you want to keep the original objects unaltered, then use Array#map and copy the objects using Object#assign:

var newRockets = rockets.forEach(function(rocket) {
    var newRocket = Object.assign({}, rocket);
    newRocket.launches += 10;
    return newRocket;
});

Get the previous month's first and last day dates in c#

DateTime LastMonthLastDate = DateTime.Today.AddDays(0 - DateTime.Today.Day);
DateTime LastMonthFirstDate = LastMonthLastDate.AddDays(1 - LastMonthLastDate.Day);

Conditionally hide CommandField or ButtonField in Gridview

You can hide a CommandField or ButtonField based on the position (index) in the GridView.

For example, if your CommandField is in the first position (index = 0), you can hide it adding the following code in the event RowDataBound of the GridView:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((System.Web.UI.Control)e.Row.Cells[0].Controls[0]).Visible = false;
    }
}

PHP - SSL certificate error: unable to get local issuer certificate

I was facing a problem like this in my local system but not in the live server. I also mentioned another solution on this page its before, but that was not working in localhost.so find a new solution of this, that is working in the localhost-WAMP Server.

cURL Error #:SSL certificate problem: unable to get local issuer certificate

sometimes system could not find your cacert.pem in your drive. so you can define this in your code where you are going to use CURL

Note that i am fulfilling all conditions for this like OPEN-SSL library active and other things.

check this code of CURL.

 $curl = curl_init();
 curl_setopt_array($curl, array(
            CURLOPT_URL =>$url,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_RETURNTRANSFER=> true,
        ));
curl_setopt($curl, CURLOPT_CAINFO, "f:/wamp/bin/cacert.pem"); // <------ 
curl_setopt($curl, CURLOPT_CAPATH, "f:/wamp/bin/cacert.pem"); // <------
$response = json_decode(curl_exec($curl),true);
$err = curl_error($curl);
curl_close($curl);

but this solution may not work in live server. because of absolute path of cacert.pem

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

JavaScript file upload size validation

I made something like that:

_x000D_
_x000D_
$('#image-file').on('change', function() {
 var numb = $(this)[0].files[0].size/1024/1024;
numb = numb.toFixed(2);
if(numb > 2){
alert('to big, maximum is 2MiB. You file size is: ' + numb +' MiB');
} else {
alert('it okey, your file has ' + numb + 'MiB')
}
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="file" id="image-file">
_x000D_
_x000D_
_x000D_

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The reason behind this error is : Flask app is already running, hasn't shut down and in middle of that we try to start another instance by: with app.app_context(): #Code Before we use this with statement we need to make sure that scope of the previous running app is closed.

Is there a program to decompile Delphi?

You can use IDR it is a great program to decompile Delphi, it is updated to the current Delphi versions and it has a lot of features.

Github Windows 'Failed to sync this branch'

I tried with Android Studio to commit Changes and push it to master But Window Showed a popup that I have to enter Github Credentials (https://github.com). I did Signup with my Gmail account So I tried to enter my Gmail id along with its password, Obviously Git do not have my Gmail password and can't match it with what I'm providing, So I ended up canceling the push.
When I tried to sync my changes through GitHub GUI Window I encounter this error. On git status command Git Shell suggested to push changes as

Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

I did the same as Git Shell suggested (git push) and everything is ok now.

Note: for someone who is new to git you have to change your path to the folder where your .git file is otherwise on Every Command you enter Git Shell will show error that its not a git repository.

fatal: Not a git repository (or any of the parent directories):

For example if your Project is in D drive in some folder you have to do something like below as you do in cmd to change directory.

cd D:\someFolder     // if your project is not deep in `D`

And if its within nested folder in D

cd D:\somefolder\someNestedFolder\nestedInNested     // if your project is not deep in `D`

If someone know how to login into Github popup from windows as I did signup with google account and here are 2 fields only Github username, password Please let me know. I have resolved the issue but with waste of some time so I want to know about login too.

RecyclerView inside ScrollView is not working

If RecyclerView showing only one row inside ScrollView. You just need to set height of your row to android:layout_height="wrap_content".

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

This is Oracle bug, memory leak in shared_pool, most likely db managing lots of partitions. Solution: In my opinion patch not exists, check with oracle support. You can try with subpools or en(de)able AMM ...

How to use Simple Ajax Beginform in Asp.net MVC 4?

All This Work :)

Model

  public partial class ClientMessage
    {
        public int IdCon { get; set; } 
        public string Name { get; set; }
        public string Email { get; set; }  
    }

Controller

   public class TestAjaxBeginFormController : Controller{  

 projectNameEntities db = new projectNameEntities();

        public ActionResult Index(){  
            return View();
        }

        [HttpPost] 
        public ActionResult GetClientMessages(ClientMessage Vm) {
            var model = db.ClientMessages.Where(x => x.Name.Contains(Vm.Name));
            return PartialView("_PartialView", model);
        } 
}

View index.cshtml

@model  projectName.Models.ClientMessage 
@{ 
    Layout = null;
}

<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
    //\\\\\\\ JS  retrun message SucccessPost or FailPost
    function SuccessMessage() {
        alert("Succcess Post");
    }
    function FailMessage() {
        alert("Fail Post");
    } 
</script>

<h1>Page Index</h1> 

@using (Ajax.BeginForm("GetClientMessages", "TestAjaxBeginForm", null , new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "SuccessMessage",
    OnFailure = "FailMessage" ,
    UpdateTargetId = "resultTarget"  
}, new { id = "MyNewNameId" })) // set new Id name for  Form
{
    @Html.AntiForgeryToken()

    @Html.EditorFor(x => x.Name) 
     <input type="submit" value="Search" /> 

}


<div id="resultTarget">  </div>

View _PartialView.cshtml

@model  IEnumerable<projectName.Models.ClientMessage >
<table> 

@foreach (var item in Model) { 

    <tr> 
        <td>@Html.DisplayFor(modelItem => item.IdCon)</td>
        <td>@Html.DisplayFor(modelItem => item.Name)</td>
        <td>@Html.DisplayFor(modelItem => item.Email)</td>
    </tr>

}

</table>