Programs & Examples On #Codeigniter 2

CodeIgniter 2.x is an old and no longer supported version of the popular PHP framework. Please refer to the [tag:codeigniter] for more information.

Where do I put image files, css, js, etc. in Codeigniter?

I just wanted to add that the problem may be even simpler -

I've been scratching my head for hours with this problem - I have read all the solutions, nothing worked. Then I managed to check the actual file name.

I had "image.jpg.jpg" rather than "image.jpg".

If you use $ ls public/..path to image assets../ you can quickly check the file names.

Sounds stupid but I never thought to look at something so simple as file name given the all the technical advice here.

Only variable references should be returned by reference - Codeigniter

Edit filename: core/Common.php, line number: 257

Before

return $_config[0] =& $config; 

After

$_config[0] =& $config;
return $_config[0]; 

Update

Added by NikiC

In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).

Update

This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.

CodeIgniter: How to get Controller, Action, URL information

Last segment of URL will always be the action. Please get like this:

$this->uri->segment('last_segment');

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Just adding my problem i had:

$this->load->model("planning/plan_model.php");

and the .php shouldnt be there, so it should have been:

$this->load->model("planning/plan_model");

hope this helps someone

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

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

Using Mysql WHERE IN clause in codeigniter

You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now subquery writing in available And now here is your query with active record

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');

And the thing is done. Cheers!!!
Note : While using sub queries you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.
Watch this too

How can I rewrite this SQL into CodeIgniter's Active Records?

Note : In Codeigntier 3 these functions are already public so you do not need to hack them.

Can't find bundle for base name

BalusC is right. Version 1.0.13 is current, but 1.0.9 appears to have the required bundles:

$ jar tf lib/jfreechart-1.0.9.jar | grep LocalizationBundle.properties 
org/jfree/chart/LocalizationBundle.properties
org/jfree/chart/editor/LocalizationBundle.properties
org/jfree/chart/plot/LocalizationBundle.properties

Change default global installation directory for node.js modules in Windows?

trying to install global packages into C:\Program Files (x86)\nodejs\ gave me Run as Administrator issues, because npm was trying to install into
C:\Program Files (x86)\nodejs\node_modules\

to resolve this, change global install directory to C:\Users\{username}\AppData\Roaming\npm:

in C:\Users\{username}\, create .npmrc file with contents:

prefix = "C:\\Users\\{username}\\AppData\\Roaming\\npm"

reference

environment
nodejs x86 installer into C:\Program Files (x86)\nodejs\ on Windows 7 Ultimate N 64-bit SP1
node --version : v0.10.28
npm --version : 1.4.10

Read the package name of an Android APK

If you don't have the Android SDK installed, like in some test scenarios, you can get the package name using the following bash method:

getAppIdFromApk() {
  local apk_path="$1"

  # regular expression (required)
  local re="^\"L.*/MainActivity;"
  # sed substitute expression
  local se="s:^\"L\(.*\)/MainActivity;:\1:p"
  # tr expression
  local te=' / .';

  local app_id="$(unzip -p $apk_path classes.dex | strings | grep -Eo $re | sed -n -e $se | tr $te)"

  echo "$app_id"
}

Tested on a mac. 'strings' and 'unzip' are standard on most linux's, so should work on linux too.

Python if-else short-hand

Try this:

x = a > b and 10 or 11

This is a sample of execution:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11

Paging UICollectionView by cells, not screen

OK, so I found the solution here: targetContentOffsetForProposedContentOffset:withScrollingVelocity without subclassing UICollectionViewFlowLayout

I should have searched for targetContentOffsetForProposedContentOffset in the begining.

Remove characters from a String in Java

Kotlin Solution

Kotlin has a built-in function for this, removeSuffix (Documentation)

var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"

If the suffix does not exist in the string, it just returns the original

var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"

You can also check out removePrefix and removeSurrounding which are similar

Add 10 seconds to a Date

There's a setSeconds method as well:

var t = new Date();
t.setSeconds(t.getSeconds() + 10);

For a list of the other Date functions, you should check out MDN


setSeconds will correctly handle wrap-around cases:

_x000D_
_x000D_
var d;_x000D_
d = new Date('2014-01-01 10:11:55');_x000D_
alert(d.getMinutes() + ':' + d.getSeconds()); //11:55_x000D_
d.setSeconds(d.getSeconds() + 10);_x000D_
alert(d.getMinutes() + ':0' + d.getSeconds()); //12:05
_x000D_
_x000D_
_x000D_

How to change shape color dynamically?

circle.xml (drawable)

<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<solid
    android:color="#000"/>

<size
    android:width="10dp"
    android:height="10dp"/>
</shape>

layout

<ImageView
      android:id="@+id/circleColor"
      android:layout_width="15dp"
       android:layout_height="15dp"
      android:textSize="12dp"
       android:layout_gravity="center"
       android:layout_marginLeft="10dp"
      android:background="@drawable/circle"/>

in activity

   circleColor = (ImageView) view.findViewById(R.id.circleColor);
   int color = Color.parseColor("#00FFFF");
   ((GradientDrawable)circleColor.getBackground()).setColor(color);

http://localhost/ not working on Windows 7. What's the problem?

Got any other Programs running ? msn ect... ? some bind to port 8080 then your webserver wouldnt start and would cause a 404 , try binding it to a different port 80 which its default should be

Setting mime type for excel document

I believe the standard MIME type for Excel files is application/vnd.ms-excel.

Regarding the name of the document, you should set the following header in the response:

header('Content-Disposition: attachment; filename="name_of_excel_file.xls"');

What is the best way to compare 2 folder trees on windows?

Beyond compare allows you to do that and much more.

It's one of those tools I can't live without.
Take a look here for a reference on the scripting options

Change the background color of a row in a JTable

The other answers given here work well since you use the same renderer in every column.

However, I tend to believe that generally when using a JTable you will have different types of data in each columm and therefore you won't be using the same renderer for each column. In these cases you may find the Table Row Rendering approach helpfull.

Reverse a string in Java

recursion:

 public String stringReverse(String string) {
    if (string == null || string.length() == 0) {
        return string;
    }
    return stringReverse(string.substring(1)) + string.charAt(0);
 }

Xcode process launch failed: Security

Xcode is able to build and install the app, but isn't able to launch it the first time. You just need to tap on the app's icon on the phone, then you will be prompted to ask if you want to trust the developer. Allow it and the app will launch, then Xcode will be able to automatically install & launch this and your other apps.

How do I determine the current operating system with Node.js

You are looking for the OS native module for Node.js:

v4: https://nodejs.org/dist/latest-v4.x/docs/api/os.html#os_os_platform

or v5 : https://nodejs.org/dist/latest-v5.x/docs/api/os.html#os_os_platform

os.platform()

Returns the operating system platform. Possible values are 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of process.platform.

How do I run all Python unit tests in a directory?

This is now possible directly from unittest: unittest.TestLoader.discover.

import unittest
loader = unittest.TestLoader()
start_dir = 'path/to/your/test/files'
suite = loader.discover(start_dir)

runner = unittest.TextTestRunner()
runner.run(suite)

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

What happened to console.log in IE8?

I found this on github:

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f() {
    log.history = log.history || [];
    log.history.push(arguments);
    if (this.console) {
        var args = arguments,
            newarr;
        args.callee = args.callee.caller;
        newarr = [].slice.call(args);
        if (typeof console.log === 'object') log.apply.call(console.log, console, newarr);
        else console.log.apply(console, newarr);
    }
};

// make it safe to use console.log always
(function(a) {
    function b() {}
    for (var c = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","), d; !! (d = c.pop());) {
        a[d] = a[d] || b;
    }
})(function() {
    try {
        console.log();
        return window.console;
    } catch(a) {
        return (window.console = {});
    }
} ());

Android - Handle "Enter" in an EditText

Here's what you do. It's also hidden in the Android Developer's sample code 'Bluetooth Chat'. Replace the bold parts that say "example" with your own variables and methods.

First, import what you need into the main Activity where you want the return button to do something special:

import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.view.KeyEvent;

Now, make a variable of type TextView.OnEditorActionListener for your return key (here I use exampleListener);

TextView.OnEditorActionListener exampleListener = new TextView.OnEditorActionListener(){

Then you need to tell the listener two things about what to do when the return button is pressed. It needs to know what EditText we're talking about (here I use exampleView), and then it needs to know what to do when the Enter key is pressed (here, example_confirm()). If this is the last or only EditText in your Activity, it should do the same thing as the onClick method for your Submit (or OK, Confirm, Send, Save, etc) button.

public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
   if (actionId == EditorInfo.IME_NULL  
      && event.getAction() == KeyEvent.ACTION_DOWN) { 
      example_confirm();//match this behavior to your 'Send' (or Confirm) button
   }
   return true;
}

Finally, set the listener (most likely in your onCreate method);

exampleView.setOnEditorActionListener(exampleListener);

How to use WinForms progress bar?

Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

public void DoWork(IProgress<int> progress)
{
    // This method is executed in the context of
    // another thread (different than the main UI thread),
    // so use only thread-safe code
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);

        // Use progress to notify UI thread that progress has
        // changed
        if (progress != null)
            progress.Report((j + 1) * 100 / 100000);
    }
}

private async void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;

    var progress = new Progress<int>(v =>
    {
        // This lambda is executed in context of UI thread,
        // so it can safely update form controls
        progressBar1.Value = v;
    });

    // Run operation in another thread
    await Task.Run(() => DoWork(progress));

    // TODO: Do something after all calculations
}

Tasks are currently the preferred way to implement what BackgroundWorker does.

Tasks and Progress are explained in more detail here:

Windows error 2 occured while loading the Java VM

In cmd

C:\Users\Downloads>install.exe LAX_VM "C:\Program Files\Java\jdk1.8.0_60\bin\java.exe"

PHP create key => value pairs within a foreach

function createOfferUrlArray($Offer) {
    $offerArray = array();
    foreach ($Offer as $key => $value) { 
        $offerArray[$key] = $value[4];
    }
    return $offerArray;
}

or

function createOfferUrlArray($offer) {
    foreach ( $offer as &$value ) {
        $value = $value[4];
    }
    unset($value);
    return $offer;
}

converting a base 64 string to an image and saving it

If you have a string of binary data which is Base64 encoded, you should be able to do the following:

byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);

You should be able to write the resulting array to a file.

Fastest way to check if a string matches a regexp in ruby?

What I am wondering is if there is any strange way to make this check even faster, maybe exploiting some strange method in Regexp or some weird construct.

Regexp engines vary in how they implement searches, but, in general, anchor your patterns for speed, and avoid greedy matches, especially when searching long strings.

The best thing to do, until you're familiar with how a particular engine works, is to do benchmarks and add/remove anchors, try limiting searches, use wildcards vs. explicit matches, etc.

The Fruity gem is very useful for quickly benchmarking things, because it's smart. Ruby's built-in Benchmark code is also useful, though you can write tests that fool you by not being careful.

I've used both in many answers here on Stack Overflow, so you can search through my answers and will see lots of little tricks and results to give you ideas of how to write faster code.

The biggest thing to remember is, it's bad to prematurely optimize your code before you know where the slowdowns occur.

Regex to check with starts with http://, https:// or ftp://

I think the regex / string parsing solutions are great, but for this particular context, it seems like it would make sense just to use java's url parser:

https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

Taken from that page:

import java.net.*;
import java.io.*;

public class ParseURL {
    public static void main(String[] args) throws Exception {

        URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                           + "/index.html?name=networking#DOWNLOADING");

        System.out.println("protocol = " + aURL.getProtocol());
        System.out.println("authority = " + aURL.getAuthority());
        System.out.println("host = " + aURL.getHost());
        System.out.println("port = " + aURL.getPort());
        System.out.println("path = " + aURL.getPath());
        System.out.println("query = " + aURL.getQuery());
        System.out.println("filename = " + aURL.getFile());
        System.out.println("ref = " + aURL.getRef());
    }
}

yields the following:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

jQuery - Dynamically Create Button and Attach Event Handler

You were just adding the html string. Not the element you created with a click event listener.

Try This:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
    <table id="addNodeTable">
        <tr>
            <td>
                Row 1
            </td>
        </tr>
        <tr >
            <td>
                Row 2
            </td>
        </tr>
    </table>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function() {
        var test = $('<button>Test</button>').click(function () {
            alert('hi');
        });
        $("#addNodeTable tr:last").append('<tr><td></td></tr>').find("td:last").append(test);

    });
</script>

How to remove the default link color of the html hyperlink 'a' tag?

This will work

    a:hover, a:focus, a:active {
        outline: none;
    }

What this does is removes the outline for all the three pseudo-classes.

Show percent % instead of counts in charts of categorical variables

As of March 2017, with ggplot2 2.2.1 I think the best solution is explained in Hadley Wickham's R for data science book:

ggplot(mydataf) + stat_count(mapping = aes(x=foo, y=..prop.., group=1))

stat_count computes two variables: count is used by default, but you can choose to use prop which shows proportions.

Add days to JavaScript Date

The simplest approach that I have implemented is to use Date() itself. `

const days = 15; 
// Date.now() gives the epoch date value (in milliseconds) of current date 
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)

`

Working with $scope.$emit and $scope.$on

This is my function:

$rootScope.$emit('setTitle', newVal.full_name);

$rootScope.$on('setTitle', function(event, title) {
    if (scope.item) 
        scope.item.name = title;
    else 
        scope.item = {name: title};
});

jQuery: Test if checkbox is NOT checked

Simple and easy to check or unchecked condition

<input type="checkbox" id="ev-click" name="" value="" >

<script>
    $( "#ev-click" ).click(function() {
        if(this.checked){
            alert('checked');
        }
        if(!this.checked){
            alert('Unchecked');
        }
    });
</script>

How to get a DOM Element from a JQuery Selector

I needed to get the element as a string.

jQuery("#bob").get(0).outerHTML;

Which will give you something like:

<input type="text" id="bob" value="hello world" />

...as a string rather than a DOM element.

Is the LIKE operator case-sensitive with MSSQL Server?

You can easy change collation in Microsoft SQL Server Management studio.

  • right click table -> design.
  • choose your column, scroll down i column properties to Collation.
  • Set your sort preference by check "Case Sensitive"

"The system cannot find the file specified" when running C++ program

As others have mentioned, this is an old thread and even with this thread there tends to be different solutions that worked for different people. The solution that worked for is as follows:

Right Click Project Name > Properties
Linker > General 
Output File > $(OutDir)$(TargetName)$(TargetExt) as indicated by @ReturnVoid
Click Apply

For whatever reason this initial correction didn't fix my problem (I'm using VS2015 Community to build c++ program). If you still get the error message try the following additional steps:

Back in Project > Properties > Linker > General > Output File > 

You'll see the previously entered text in bold

Select Drop Down > Select "inherit from parent or project defaults"
Select Apply

Previously bold font is no longer bold

Build > Rebuild > Debug

It doesn't make since to me to require these additional steps in addition to what @ReturnVoid posted but...what works is what works...hope it helps someone else out too. Thanks @ReturnVoid

Stopping a CSS3 Animation on last frame

-webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */
animation-fill-mode: forwards;

Browser Support

  • Chrome 43.0 (4.0 -webkit-)
  • IE 10.0
  • Mozilla 16.0 ( 5.0 -moz-)
  • Shafari 4.0 -webkit-
  • Opera 15.0 -webkit- (12.112.0 -o-)

Usage:-

.fadeIn {
  animation-name: fadeIn;
    -webkit-animation-name: fadeIn;

    animation-duration: 1.5s;
    -webkit-animation-duration: 1.5s;

    animation-timing-function: ease;
    -webkit-animation-timing-function: ease;

     animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
}


@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

How to create correct JSONArray in Java using JSONObject

Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

Make sure you have following configuration in your pom.xml file.

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

How to set Android camera orientation properly?

I faced the issue when i was using ZBar for scanning in tabs. Camera orientation issue. Using below code i was able to resolve issue. This is not the whole code snippet, Please take only help from this.

 public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
     if (isPreviewRunning) {
            mCamera.stopPreview();
        }

 setCameraDisplayOrientation(mCamera);

        previewCamera();

    }



 public void previewCamera() {

        try {
            // Hard code camera surface rotation 90 degs to match Activity view
            // in portrait
            mCamera.setPreviewDisplay(mHolder);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            mCamera.autoFocus(autoFocusCallback);
            isPreviewRunning = true;
        } catch (Exception e) {
            Log.d("DBG", "Error starting camera preview: " + e.getMessage());
        }


    }


public void setCameraDisplayOrientation(android.hardware.Camera camera) {
        Camera.Parameters parameters = camera.getParameters();

        android.hardware.Camera.CameraInfo camInfo =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(getBackFacingCameraId(), camInfo);


        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int rotation = display.getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (camInfo.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (camInfo.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }




    private int getBackFacingCameraId() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {

                cameraId = i;
                break;
            }
        }
        return cameraId;
    }

Merge 2 DataTables and store in a new one

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.

Multiple models in a view

  1. Create one new class in your model and properties of LoginViewModel and RegisterViewModel:

    public class UserDefinedModel() 
    {
        property a1 as LoginViewModel 
        property a2 as RegisterViewModel 
    }
    
  2. Then use UserDefinedModel in your view.

How can I make my match non greedy in vim?

Plugin eregex.vim handles Perl-style non-greedy operators *? and +?

Send Message in C#

Some other options:

Common Assembly

Create another assembly that has some common interfaces that can be implemented by the assemblies.

Reflection

This has all sorts of warnings and drawbacks, but you could use reflection to instantiate / communicate with the forms. This is both slow and runtime dynamic (no static checking of this code at compile time).

How to simulate a mouse click using JavaScript?

(Modified version to make it work without prototype.js)

function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}

You can use it like this:

simulate(document.getElementById("btn"), "click");

Note that as a third parameter you can pass in 'options'. The options you don't specify are taken from the defaultOptions (see bottom of the script). So if you for example want to specify mouse coordinates you can do something like:

simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 })

You can use a similar approach to override other default options.

Credits should go to kangax. Here's the original source (prototype.js specific).

C# ASP.NET Single Sign-On Implementation

I am late to the party, but for option #1, I would go with IdentityServer3(.NET 4.6 or below) or IdentityServer4 (compatible with Core) .

You can reuse your existing user store in your app and plug that to be IdentityServer's User Store. Then the clients must be pointed to your IdentityServer as the open id provider.

How do you enable mod_rewrite on any OS?

network solutions offers the advice to put a php.ini in the cgi-bin to enable mod_rewrite

Twitter Bootstrap 3: How to center a block

You can use class .center-block in combination with style="width:400px;max-width:100%;" to preserve responsiveness.

Using .col-md-* class with .center-block will not work because of the float on .col-md-*.

How can I get a specific number child using CSS?

For modern browsers, use td:nth-child(2) for the second td, and td:nth-child(3) for the third. Remember that these retrieve the second and third td for every row.

If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.

Matplotlib-Animation "No MovieWriters Available"

I had the following error while running the cell. enter image description here

This may be due to not having ffmpeg in your system. Try the following command in your terminal.

sudo apt install ffmpeg

This works for me. I hope it will work out for you too.

How to set order of repositories in Maven settings.xml

Also, consider to use a repository manager such as Nexus and configure all your repositories there.

Why do I need to explicitly push a new branch?

You don't, see below

I find this 'feature' rather annoying since I'm not trying to launch rockets to the moon, just push my damn branch. You probably do too or else you wouldn't be here!

Here is the fix: if you want it to implicitly push for the current branch regardless of if that branch exists on origin just issue this command once and you will never have to again anywhere:

git config --global push.default current

So if you make branches like this:

git checkout -b my-new-branch

and then make some commits and then do a

git push -u

to get them out to origin (being on that branch) and it will create said branch for you if it doesn't exist.

Note the -u bit makes sure they are linked if you were to pull later on from said branch. If you have no plans to pull the branch later (or are okay with another one liner if you do) -u is not necessary.

If REST applications are supposed to be stateless, how do you manage sessions?

Historical view of user application state management

Sessions in the traditional sense keep the user's state in the application inside the server. This may be the current page in a flow or what has been previously entered but not persisted to the main database yet.

The reason for this need was the lack of standards on the client side to effectively maintain the state without making client specific (i.e. browser specific) applications or plug-ins.

HTML5 and XML Header Request has over time standardized the notion of storing complex data including application state in standard way on the client (i.e. browser) side without resorting to going back and forth between the server.

General usage of REST services

REST services are generally called when there is a transaction that needs to be performed or if it needs to retrieve data.

REST services are meant to be called by the client-side application and not the end user directly.

Authenticating

For any request to the server, part of the request should contain the authorization token. How it is implemented is application specific, but in general is either a BASIC or CERTIFICATE form of authentication.

Form based authentication is not used by REST services. However, as noted above REST services are not meant to be called by the user, but by the application. The application needs to manage getting the authentication token. In my case I used cookies with JASPIC with OAuth 2.0 to connect to Google for authentication and simple HTTP Authentication for automated testing. I also used HTTP Header authentication via JASPIC for local testing as well (though the same approach can be performed in SiteMinder)

As per those examples, the authentication is managed on the client side (though SiteMinder or Google would store the authentication session on their end), there's nothing that can be done about that state, but it is not part of the REST service application.

Retrieval requests

Retrieval requests in REST are GET operations where a specific resource is requested and is cacheable. There is no need for server sessions because the request has everything it would need to retrieve the data: authentication and the URI.

Transaction scripts

As noted above, the client-side application itself calls the REST services along with the authentication that it manages on the client side as well.

What this means for REST services [if done correctly] is to take a single request to the REST server will contain everything that is needed for a single user operation that does everything that is needed in a single transaction, a Transaction Script is what the pattern is called.

This is done through a POST request usually, but others such as PUT can also be used.

A lot of contrived examples of REST (I myself did this) tried to follow as much of what has been defined in the HTTP protocol, after going through that I decided to be more pragmatic and left it to GET and POST only. The POST method does not even have to implement the POST-REDIRECT-GET pattern.

Regardless though, as I had noted above, the client-side application will be the one calling the service and it will only call the POST request with all the data when it needs to (not every time). This prevents constant requests to the server.

Polling

Though REST can be used for polling as well, I won't recommend it unless you have to use it because of browser compatibility. For that I would use WebSockets which I had designed an API contract for as well. Another alternative for older browsers is CometD.

using awk with column value conditions

Depending on the AWK implementation are you using == is ok or not.

Have you tried ~?. For example, if you want $1 to be "hello":

awk '$1 ~ /^hello$/{ print $3; }' <infile>

^ means $1 start, and $ is $1 end.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I solved this issue for myself, I found there's was two files of http-client with different version of other dependent jar files. So there may version were collapsing between libraries files so remove all old/previous libraries files and re-add are jar files from lib folder of this zip file:

Donwload Zip file from here

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Windows - set environment variable permanently:

setx ANDROID_HOME "C:\Program Files\Android\android-sdk"

or

setx ANDROID_HOME "C:\Program Files (x86)\Android\android-sdk"

Removing padding gutter from grid columns in Bootstrap 4

You can use this css code to get gutterless grid in bootstrap.

.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
  margin-left: 0;
  margin-right: 0;
}

.no-gutter>[class^="col-"]{
  padding-left: 0;
  padding-right: 0;
}

Exception from HRESULT: 0x800A03EC Error

This must be the world's most generic error message because I got it today on the following command using Excel Interop:

Excel.WorkbookConnection conn;
conn.ODBCConnection.Connection = "DSN=myserver;";

What fixed it was specifying ODBC in the connection string:

conn.ODBCConnection.Connection = "ODBC;DSN=myserver;";

On the off chance anyone else has this error, I hope it helps.

Button Center CSS

The problem is with the following CSS line on .nav_button:

margin: 0 auto;

That would only work if you had one button, that's why they're off-centered when there are more than one nav_button divs.

If you want all your buttons centered nest the nav_buttons in another div:

<div class="nav">
    <div class="centerButtons">
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Home</div>
            <div class="b_right"></div>
        </div>
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Contact Us</div>
            <div class="b_right"></div>
        </div>
    </div>
</div>

And style it this way:

.nav{
    margin-top:167px;
    width:1024px;
    height:34px;
}

/* Centers the div that nests the nav_buttons */
.centerButtons {
    margin: 0 auto;
    float: left;
} 

.nav_button{
    height:34px;
    margin-right:10px;
    float: left;
}

Scheduling Python Script to run every hour accurately

On the version posted by sunshinekitty called "Version < 3.0" , you may need to specify apscheduler 2.1.2 . I accidentally had version 3 on my 2.7 install, so I went:

pip uninstall apscheduler
pip install apscheduler==2.1.2

It worked correctly after that. Hope that helps.

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

Neither code is always better. They do different things, so they are good at different things.

InvariantCultureIgnoreCase uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.

OrdinalIgnoreCase compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é or ö. This is also faster because there are no extra rules to apply before comparing.

Copy multiple files from one directory to another from Linux shell

Try this simpler one,

cp /home/ankur/folder/file{1,2} /home/ankur/dest

If you want to copy all the 10 files then run this command,

 cp ~/Desktop/{xyz,file{1,2},next,files,which,are,not,similer} foo-bar

Is it possible to use global variables in Rust?

Heap allocations are possible for static variables if you use the lazy_static macro as seen in the docs

Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.

// Declares a lazily evaluated constant HashMap. The HashMap will be evaluated once and
// stored behind a global static reference.

use lazy_static::lazy_static;
use std::collections::HashMap;

lazy_static! {
    static ref PRIVILEGES: HashMap<&'static str, Vec<&'static str>> = {
        let mut map = HashMap::new();
        map.insert("James", vec!["user", "admin"]);
        map.insert("Jim", vec!["user"]);
        map
    };
}

fn show_access(name: &str) {
    let access = PRIVILEGES.get(name);
    println!("{}: {:?}", name, access);
}

fn main() {
    let access = PRIVILEGES.get("James");
    println!("James: {:?}", access);

    show_access("Jim");
}

Switch php versions on commandline ubuntu 16.04

You can use the below script to switch between PHP version easily I have included phpize configuration too.

https://github.com/anilkumararumulla/switch-php-version

Download the script file and run

sh switch.sh

Decoding a Base64 string in Java

If you don't want to use apache, you can use Java8:

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw=="); 
System.out.println(new String(decodedBytes) + "\n");

Adding iOS UITableView HeaderView (not section header)

In Swift:

override func viewDidLoad() {
    super.viewDidLoad()

    // We set the table view header.
    let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
    cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
    self.tableView.tableHeaderView = cellTableViewHeader

    // We set the table view footer, just know that it will also remove extra cells from tableview.
    let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
    cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
    self.tableView.tableFooterView = cellTableViewFooter
}

Electron: jQuery is not defined

A better and more generic solution IMO:

<!-- Insert this line above script imports  -->
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>

<!-- normal script imports etc  -->
<script src="scripts/jquery.min.js"></script>    
<script src="scripts/vendor.js"></script>    

<!-- Insert this line after script imports -->
<script>if (window.module) module = window.module;</script>

Benefits

  • Works for both browser and electron with the same code
  • Fixes issues for ALL 3rd-party libraries (not just jQuery) without having to specify each one
  • Script Build / Pack Friendly (i.e. Grunt / Gulp all scripts into vendor.js)
  • Does NOT require node-integration to be false

source here

Update query PHP MySQL

First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error() directly after a query to debug.

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/index.html

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

How to call loading function with React useEffect only once

I like to define a mount function, it tricks EsLint in the same way useMount does and I find it more self-explanatory.

const mount = () => {
  console.log('mounted')
  // ...

  const unmount = () => {
    console.log('unmounted')
    // ...
  }
  return unmount
}
useEffect(mount, [])

Keyboard shortcuts in WPF

How to associate the command with a MenuItem:

<MenuItem Header="My command" Command="{x:Static local:MyWindow.MyCommand}"/>

PHP - Check if two arrays are equal

Here is the example how to compare to arrays and get what is different between them.

$array1 = ['1' => 'XXX', 'second' => [
            'a' => ['test' => '2'],
            'b' => 'test'
        ], 'b' => ['no test']];

        $array2 = [
            '1' => 'XX',
            'second' => [
                'a' => ['test' => '5', 'z' => 5],
                'b' => 'test'
            ],
            'test'
        ];


        function compareArrayValues($arrayOne, $arrayTwo, &$diff = [], $reversed = false)
        {
            foreach ($arrayOne as $key => $val) {
                if (!isset($arrayTwo[$key])) {
                    $diff[$key] = 'MISSING IN ' . ($reversed ? 'FIRST' : 'SECOND');
                } else if (is_array($val) && (json_encode($arrayOne[$key]) !== json_encode($arrayTwo[$key]))) {
                    compareArrayValues($arrayOne[$key], $arrayTwo[$key], $diff[$key], $reversed);
                } else if ($arrayOne[$key] !== $arrayTwo[$key]) {
                    $diff[$key] = 'DIFFERENT';
                }
            }
        }

        $diff = [];
        $diffSecond = [];

        compareArrayValues($array1, $array2, $diff);
        compareArrayValues($array2, $array1, $diffSecond, true);

        print_r($diff);
        print_r($diffSecond);

        print_r(array_merge($diff, $diffSecond));

Result:

Array
(
    [0] => DIFFERENT
    [second] => Array
        (
            [a] => Array
                (
                    [test] => DIFFERENT
                    [z] => MISSING IN FIRST
                )

        )

    [b] => MISSING IN SECOND
    [1] => DIFFERENT
    [2] => MISSING IN FIRST
)

How to SUM two fields within an SQL query

ID  VALUE1  VALUE2
===================
1   1       2

1   2       2
2   3       4
2   4       5

select ID, (coalesce(VALUE1 ,0) + coalesce(VALUE2 ,0) as Total from TableName

Excel function to get first word from sentence in other cell

How about something like

=LEFT(A1,SEARCH(" ",A1)-1)

or

=LEFT(A1,SEARCH("<b>",A1)-1)

Have a look at MS Excel: Search Function and Excel 2007 LEFT Function

Access PHP variable in JavaScript

You can't, you'll have to do something like

<script type="text/javascript">
   var php_var = "<?php echo $php_var; ?>";
</script>

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

How do I convert speech to text?

.NET can do it with its System.Speech namespace.

You would have to convert to .wav first or capture the audio live from the mic.

Details on implementation can be found here: Transcribing Audio with .NET

How to render an ASP.NET MVC view as a string?

Here is a class I wrote to do this for ASP.NETCore RC2. I use it so I can generate html email using Razor.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using System.IO;
using System.Threading.Tasks;

namespace cloudscribe.Web.Common.Razor
{
    /// <summary>
    /// the goal of this class is to provide an easy way to produce an html string using 
    /// Razor templates and models, for use in generating html email.
    /// </summary>
    public class ViewRenderer
    {
        public ViewRenderer(
            ICompositeViewEngine viewEngine,
            ITempDataProvider tempDataProvider,
            IHttpContextAccessor contextAccesor)
        {
            this.viewEngine = viewEngine;
            this.tempDataProvider = tempDataProvider;
            this.contextAccesor = contextAccesor;
        }

        private ICompositeViewEngine viewEngine;
        private ITempDataProvider tempDataProvider;
        private IHttpContextAccessor contextAccesor;

        public async Task<string> RenderViewAsString<TModel>(string viewName, TModel model)
        {

            var viewData = new ViewDataDictionary<TModel>(
                        metadataProvider: new EmptyModelMetadataProvider(),
                        modelState: new ModelStateDictionary())
            {
                Model = model
            };

            var actionContext = new ActionContext(contextAccesor.HttpContext, new RouteData(), new ActionDescriptor());
            var tempData = new TempDataDictionary(contextAccesor.HttpContext, tempDataProvider);

            using (StringWriter output = new StringWriter())
            {

                ViewEngineResult viewResult = viewEngine.FindView(actionContext, viewName, true);

                ViewContext viewContext = new ViewContext(
                    actionContext,
                    viewResult.View,
                    viewData,
                    tempData,
                    output,
                    new HtmlHelperOptions()
                );

                await viewResult.View.RenderAsync(viewContext);

                return output.GetStringBuilder().ToString();
            }
        }
    }
}

Why both no-cache and no-store should be used in HTTP response?

no-store should not be necessary in normal situations, and can harm both speed and usability. It is intended for use where the HTTP response contains information so sensitive it should never be written to a disk cache at all, regardless of the negative effects that creates for the user.

How it works:

  • Normally, even if a user agent such as a browser determines that a response shouldn't be cached, it may still store it to the disk cache for reasons internal to the user agent. This version may be utilised for features like "view source", "back", "page info", and so on, where the user hasn't necessarily requested the page again, but the browser doesn't consider it a new page view and it would make sense to serve the same version the user is currently viewing.

  • Using no-store will prevent that response being stored, but this may impact the browser's ability to give "view source", "back", "page info" and so on without making a new, separate request for the server, which is undesirable. In other words, the user may try viewing the source and if the browser didn't keep it in memory, they'll either be told this isn't possible, or it will cause a new request to the server. Therefore, no-store should only be used when the impeded user experience of these features not working properly or quickly is outweighed by the importance of ensuring content is not stored in the cache.

My current understanding is that it is just for intermediate cache server. Even if "no-cache" is in response, intermediate cache server can still save the content to non-volatile storage.

This is incorrect. Intermediate cache servers compatible with HTTP 1.1 will obey the no-cache and must-revalidate instructions, ensuring that content is not cached. Using these instructions will ensure that the response is not cached by any intermediate cache, and that all subsequent requests are sent back to the origin server.

If the intermediate cache server does not support HTTP 1.1, then you will need to use Pragma: no-cache and hope for the best. Note that if it doesn't support HTTP 1.1 then no-store is irrelevant anyway.

Find unused npm packages in package.json

many of the answer here are how to find unused items.

I wanted to remove them automatically.

  1. Install this node project.

    $ npm install -g typescript tslint tslint-etc


  1. At the root dir, add a new file tslint-imports.json

    { "extends": [ "tslint-etc" ], "rules": { "no-unused-declaration": true } }


  1. Run this at your own risk, make a backup :)

    $ tslint --config tslint-imports.json --fix --project .

explode string in jquery

Try This

var data = 'allow~5'; 
var result=data.split('~');

RESULT

alert(result[0]);

jQuery - multiple $(document).ready ...?

All will get executed and On first Called first run basis!!

<div id="target"></div>

<script>
  $(document).ready(function(){
    jQuery('#target').append('target edit 1<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 2<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 3<br>');
  });
</script>

Demo As you can see they do not replace each other

Also one thing i would like to mention

in place of this

$(document).ready(function(){});

you can use this shortcut

jQuery(function(){
   //dom ready codes
});

What is the difference between concurrent programming and parallel programming?

I will try to explain it in my own style, it might not be in computer terms but it gives you the general idea.

Let's take an example, say Household chores: cleaning dishes, taking out trash, mowing the lawn etc, also we have 3 people(threads) A, B, C to do them

Concurrent: The three individuals start different tasks independently i.e.,

A --> cleaning dishes
B --> taking out trash 
C --> mowing the lawn 

Here, the order of tasks are indeterministic and responses depends on the amount of work

Parallel: Here if we want to improve the throughput we can assign multiple people to the single task, for example, cleaning dishes we assign two people, A soaping the dishes and B washing the dishes which might improve the throughput.

cleaning the dishes:

A --> soaping the dishes
B --> washing the dishes

so on

Hope this gives an idea! now move on to the technical terms which are explained in the other answers ;)

Force browser to refresh css, javascript, etc

You can use the Firefox/Chrome developer toolbar:

  1. Open Dev Toolbar Ctrl + Shift + I
  2. Go to network tab
  3. Press the "disable cache" checkbox (Firefox: top right of toolbar; Chrome: top centre of toolbar)

How to check for a JSON response using RSpec?

JSON comparison solution

Yields a clean but potentially large Diff:

actual = JSON.parse(response.body, symbolize_names: true)
expected = { foo: "bar" }
expect(actual).to eq expected

Example of console output from real data:

expected: {:story=>{:id=>1, :name=>"The Shire"}}
     got: {:story=>{:id=>1, :name=>"The Shire", :description=>nil, :body=>nil, :number=>1}}

   (compared using ==)

   Diff:
   @@ -1,2 +1,2 @@
   -:story => {:id=>1, :name=>"The Shire"},
   +:story => {:id=>1, :name=>"The Shire", :description=>nil, ...}

(Thanks to comment by @floatingrock)

String comparison solution

If you want an iron-clad solution, you should avoid using parsers which could introduce false positive equality; compare the response body against a string. e.g:

actual = response.body
expected = ({ foo: "bar" }).to_json
expect(actual).to eq expected

But this second solution is less visually friendly as it uses serialized JSON which would include lots of escaped quotation marks.

Custom matcher solution

I tend to write myself a custom matcher that does a much better job of pinpointing at exactly which recursive slot the JSON paths differ. Add the following to your rspec macros:

def expect_response(actual, expected_status, expected_body = nil)
  expect(response).to have_http_status(expected_status)
  if expected_body
    body = JSON.parse(actual.body, symbolize_names: true)
    expect_json_eq(body, expected_body)
  end
end

def expect_json_eq(actual, expected, path = "")
  expect(actual.class).to eq(expected.class), "Type mismatch at path: #{path}"
  if expected.class == Hash
    expect(actual.keys).to match_array(expected.keys), "Keys mismatch at path: #{path}"
    expected.keys.each do |key|
      expect_json_eq(actual[key], expected[key], "#{path}/:#{key}")
    end
  elsif expected.class == Array
    expected.each_with_index do |e, index|
      expect_json_eq(actual[index], expected[index], "#{path}[#{index}]")
    end
  else
    expect(actual).to eq(expected), "Type #{expected.class} expected #{expected.inspect} but got #{actual.inspect} at path: #{path}"
  end
end

Example of usage 1:

expect_response(response, :no_content)

Example of usage 2:

expect_response(response, :ok, {
  story: {
    id: 1,
    name: "Shire Burning",
    revisions: [ ... ],
  }
})

Example output:

Type String expected "Shire Burning" but got "Shire Burnin" at path: /:story/:name

Another example output to demonstrate a mismatch deep in a nested array:

Type Integer expected 2 but got 1 at path: /:story/:revisions[0]/:version

As you can see, the output tells you EXACTLY where to fix your expected JSON.

Plotting a list of (x, y) coordinates in python matplotlib

If you have a numpy array you can do this:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([
    [1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()

Difference Between Schema / Database in MySQL

Microsoft SQL Server for instance, Schemas refer to a single user and is another level of a container in the order of indicating the server, database, schema, tables, and objects.

For example, when you are intending to update dbo.table_a and the syntax isn't full qualified such as UPDATE table.a the DBMS can't decide to use the intended table. Essentially by default the DBMS will utilize myuser.table_a

Extract a single (unsigned) integer from a string

Follow this step it will convert string to number

$value = '$0025.123';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
settype($onlyNumeric,"float");

$result=($onlyNumeric+100);
echo $result;

Another way to do it :

$res = preg_replace("/[^0-9.]/", "", "$15645623.095605659");

How do I tell a Python script to use a particular version

For those using pyenv to control their virtual environments, I have found this to work in a script:

#!/home/<user>/.pyenv/versions/<virt_name>/bin/python

DO_STUFF

how to setup ssh keys for jenkins to publish via ssh

You don't need to create the SSH keys on the Jenkins server, nor do you need to store the SSH keys on the Jenkins server's filesystem. This bit of information is crucial in environments where Jenkins servers instances may be created and destroyed frequently.

Generating the SSH Key Pair

On any machine (Windows, Linux, MacOS ...doesn't matter) generate an SSH key pair. Use this article as guide:

On the Target Server

On the target server, you will need to place the content of the public key (id_rsa.pub per the above article) into the .ssh/authorized_keys file under the home directory of the user which Jenkins will be using for deployment.

In Jenkins

Using "Publish over SSH" Plugin

Ref: https://plugins.jenkins.io/publish-over-ssh/

Visit: Jenkins > Manage Jenkins > Configure System > Publish over SSH

  • If the private key is encrypted, then you will need to enter the passphrase for the key into the "Passphrase" field, otherwise leave it alone.
  • Leave the "Path to key" field empty as this will be ignored anyway when you use a pasted key (next step)
  • Copy and paste the contents of the private key (id_rsa per the above article) into the "Key" field
  • Under "SSH Servers", "Add" a new server configuration for your target server.

Using Stored Global Credentials

Visit: Jenkins > Credentials > System > Global credentials (unrestricted) > Add Credentials

  • Kind: "SSH Username with private key"
  • Scope: "Global"
  • ID: [CREAT A UNIQUE ID FOR THIS KEY]
  • Description: [optionally, enter a decription]
  • Username: [USERNAME JENKINS WILL USE TO CONNECT TO REMOTE SERVER]
  • Private Key: [select "Enter directly"]
  • Key: [paste the contents of the private key (id_rsa per the above article)]
  • Passphrase: [enter the passphrase for the key, or leave it blank if the key is not encrypted]

php implode (101) with quotes

Another possible option, depending on what you need the array for:

$array = array('lastname', 'email', 'phone');
echo json_encode($array);

This will put '[' and ']' around the string, which you may or may not want.

Tracking Google Analytics Page Views with AngularJS

For those of you using AngularUI Router instead of ngRoute can use the following code to track page views.

app.run(function ($rootScope) {
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        ga('set', 'page', toState.url);
        ga('send', 'pageview');
    });
});

Hashset vs Treeset

1.HashSet allows null object.

2.TreeSet will not allow null object. If you try to add null value it will throw a NullPointerException.

3.HashSet is much faster than TreeSet.

e.g.

 TreeSet<String> ts = new TreeSet<String>();
 ts.add(null); // throws NullPointerException

 HashSet<String> hs = new HashSet<String>();
 hs.add(null); // runs fine

How do you do exponentiation in C?

or you could just write the power function, with recursion as a added bonus

int power(int x, int y){
      if(y == 0)
        return 1;
     return (x * power(x,y-1) );
    }

yes,yes i know this is less effecient space and time complexity but recursion is just more fun!!

Create Table from JSON Data with angularjs and ng-repeat

To render any json in tabular format:

<table>
    <thead>
      <tr>
        <th ng-repeat="(key, value) in vm.records[0]">{{key}}</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="(key, value) in vm.records">
        <td ng-repeat="(key, value) in value">
          {{value}}
        </td>
      </tr>
    </tbody>
</table>

See complete code in detail with other features

GET URL parameter in PHP

$Query_String  = explode("&", explode("?", $_SERVER['REQUEST_URI'])[1] );
var_dump($Query_String)

Array ( [ 0] => link=www.google.com )

Word-wrap in an HTML table

A solution which work with Google Chrome and Firefox (not tested with Internet Explorer) is to set display: table-cell as a block element.

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

Select value from list of tuples where condition

One solution to this would be a list comprehension, with pattern matching inside your tuple:

>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]
[55]

Another way would be using map and filter:

>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
[55]

Does the Java &= operator apply & or &&?

i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.

This worked for me:

a &= a && b()

Win32Exception (0x80004005): The wait operation timed out

If you're using Entity Framework, you can extend the default timeout (to give a long-running query more time to complete) by doing:

myDbContext.Database.CommandTimeout = 300;

Where myDbContext is your DbContext instance, and 300 is the timeout value in seconds.

(Syntax current as of Entity Framework 6.)

How to declare global variables in Android?

You can have a static field to store this kind of state. Or put it to the resource Bundle and restore from there on onCreate(Bundle savedInstanceState). Just make sure you entirely understand Android app managed lifecycle (e.g. why login() gets called on keyboard orientation change).

Detecting user leaving page with react-router

For react-router v0.13.x with react v0.13.x:

this is possible with the willTransitionTo() and willTransitionFrom() static methods. For newer versions, see my other answer below.

From the react-router documentation:

You can define some static methods on your route handlers that will be called during route transitions.

willTransitionTo(transition, params, query, callback)

Called when a handler is about to render, giving you the opportunity to abort or redirect the transition. You can pause the transition while you do some asynchonous work and call callback(error) when you're done, or omit the callback in your argument list and it will be called for you.

willTransitionFrom(transition, component, callback)

Called when an active route is being transitioned out giving you an opportunity to abort the transition. The component is the current component, you'll probably need it to check its state to decide if you want to allow the transition (like form fields).

Example

  var Settings = React.createClass({
    statics: {
      willTransitionTo: function (transition, params, query, callback) {
        auth.isLoggedIn((isLoggedIn) => {
          transition.abort();
          callback();
        });
      },

      willTransitionFrom: function (transition, component) {
        if (component.formHasUnsavedData()) {
          if (!confirm('You have unsaved information,'+
                       'are you sure you want to leave this page?')) {
            transition.abort();
          }
        }
      }
    }

    //...
  });

For react-router 1.0.0-rc1 with react v0.14.x or later:

this should be possible with the routerWillLeave lifecycle hook. For older versions, see my answer above.

From the react-router documentation:

To install this hook, use the Lifecycle mixin in one of your route components.

  import { Lifecycle } from 'react-router'

  const Home = React.createClass({

    // Assuming Home is a route component, it may use the
    // Lifecycle mixin to get a routerWillLeave method.
    mixins: [ Lifecycle ],

    routerWillLeave(nextLocation) {
      if (!this.state.isSaved)
        return 'Your work is not saved! Are you sure you want to leave?'
    },

    // ...

  })

Things. may change before the final release though.

How can I disable inherited css styles?

If you control both the HTML and CSS, I'd suggest switching to using ID's on all the divs needed for the rounded corner.

CSS

#d1 {
    background: #CFFEB6 url('tr.gif') no-repeat top right;
}
#d2 {
    background: url('br.gif') no-repeat bottom right;
}
#d3 {
    background: url('bl.gif') no-repeat bottom left;
}
#d4 {
    padding: 10px;
}

HTML

<div id="d1"><div id="d2"><div id="d3"><div id="d4">
    <div class='button'><a href='#'>Test</a></div>
</div></div></div></div>

Submit Button Image

<input type="image" src="path to image" name="submit" />

UPDATE:

For button states, you can use type="submit" and then add a class to it

<input type="submit" name="submit" class="states" />

Then in css, use background images for:

.states{
background-image:url(path to url);
height:...;
width:...;
}

.states:hover{
background-position:...;
}

.states:active{
background-position:...;
}

How to replace a whole line with sed?

If you would like to use awk then this would work too

awk -F= '{$2="xxx";print}' OFS="\=" filename

Select elements by attribute in CSS

    [data-value] {
  /* Attribute exists */
}

[data-value="foo"] {
  /* Attribute has this exact value */
}

[data-value*="foo"] {
  /* Attribute value contains this value somewhere in it */
}

[data-value~="foo"] {
  /* Attribute has this value in a space-separated list somewhere */
}

[data-value^="foo"] {
  /* Attribute value starts with this */
}

[data-value|="foo"] {
  /* Attribute value starts with this in a dash-separated list */
}

[data-value$="foo"] {
  /* Attribute value ends with this */
}

batch to copy files with xcopy

After testing most of the switches this worked for me:

xcopy C:\folder1 C:\folder2\folder1 /t /e /i /y

This will copy the folder folder1 into the folder folder2. So the directory tree would look like:

C:
   Folder1
   Folder2
      Folder1

How to Add Date Picker To VBA UserForm

In Access 2013. Drop a "Text Box" control onto your form. On the Property Sheet for the control under the Format tab find the Format property. Set this to one of the date format options. Job's done.

How to disable textbox from editing?

        textBox1.Enabled = false;

"false" property will make the text box disable. and "true" will make it in regular form. Thanks.

Change icon-bar (?) color in bootstrap

The reason your CSS isn't working is because of specificity. The Bootstrap selector has a higher specificity than yours, so your style is completely ignored.

Bootstrap styles this with the selector: .navbar-default .navbar-toggle .icon-bar. This selector has a B specificity value of 3, whereas yours only has a B specificity value of 1.

Therefore, to override this, simply use the same selector in your CSS (assuming your CSS is included after Bootstrap's):

.navbar-default .navbar-toggle .icon-bar {
    background-color: black;
}

Creating a JSON array in C#

You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:

public class Item
{
    public string name { get; set; }
    public string index { get; set; }
    public string optional { get; set; }
}

public class RootObject
{
    public List<Item> items { get; set; }
}

Usage:

var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item> 
                          {
                             new Item { name = "test1", index = "index1" },
                             new Item { name = "test2", index = "index2" }
                          };

And in the result you won't have to change things several times if you need to change data-structure.

p.s. Here's very nice tool for complex jsons

How to hide iOS status bar

In the Plist add the following properties.

Status bar is initially hidden = YES

View controller-based status bar appearance = NO

now the status bar will hidden.

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

How to kill a running SELECT statement

As you keep getting pages of results I'm assuming you started the session in SQL*Plus. If so, the easy thing to do is to bash ctrl + break many, many times until it stops.

The more complicated and the more generic way(s) I detail below in order of increasing ferocity / evil. The first one will probably work for you but if it doesn't you can keep moving down the list.

Most of these are not recommended and can have unintended consequences.


1. Oracle level - Kill the process in the database

As per ObiWanKenobi's answer and the ALTER SESSION documentation

alter system kill session 'sid,serial#';

To find the sid, session id, and the serial#, serial number, run the following query - summarised from OracleBase - and find your session:

select s.sid, s.serial#, p.spid, s.username, s.schemaname
     , s.program, s.terminal, s.osuser
  from v$session s
  join v$process p
    on s.paddr = p.addr
 where s.type != 'BACKGROUND'

If you're running a RAC then you need to change this slightly to take into account the multiple instances, inst_id is what identifies them:

select s.inst_id, s.sid, s.serial#, p.spid, s.username
     , s.schemaname, s.program, s.terminal, s.osuser
  from Gv$session s
  join Gv$process p
    on s.paddr = p.addr
   and s.inst_id = p.inst_id
 where s.type != 'BACKGROUND'

This query would also work if you're not running a RAC.

If you're using a tool like PL/SQL Developer then the sessions window will also help you find it.

For a slightly stronger "kill" you can specify the IMMEDIATE keyword, which instructs the database to not wait for the transaction to complete:

alter system kill session 'sid,serial#' immediate;

2. OS level - Issue a SIGTERM

kill pid

This assumes you're using Linux or another *nix variant. A SIGTERM is a terminate signal from the operating system to the specific process asking it to stop running. It tries to let the process terminate gracefully.

Getting this wrong could result in you terminating essential OS processes so be careful when typing.

You can find the pid, process id, by running the following query, which'll also tell you useful information like the terminal the process is running from and the username that's running it so you can ensure you pick the correct one.

select p.*
  from v$process p
  left outer join v$session s
    on p.addr = s.paddr
 where s.sid = ?
   and s.serial# = ?

Once again, if you're running a RAC you need to change this slightly to:

select p.*
  from Gv$process p
  left outer join Gv$session s
    on p.addr = s.paddr
 where s.sid = ?
   and s.serial# = ?

Changing the where clause to where s.status = 'KILLED' will help you find already killed process that are still "running".

3. OS - Issue a SIGKILL

kill -9 pid

Using the same pid you picked up in 2, a SIGKILL is a signal from the operating system to a specific process that causes the process to terminate immediately. Once again be careful when typing.

This should rarely be necessary. If you were doing DML or DDL it will stop any rollback being processed and may make it difficult to recover the database to a consistent state in the event of failure.

All the remaining options will kill all sessions and result in your database - and in the case of 6 and 7 server as well - becoming unavailable. They should only be used if absolutely necessary...

4. Oracle - Shutdown the database

shutdown immediate

This is actually politer than a SIGKILL, though obviously it acts on all processes in the database rather than your specific process. It's always good to be polite to your database.

Shutting down the database should only be done with the consent of your DBA, if you have one. It's nice to tell the people who use the database as well.

It closes the database, terminating all sessions and does a rollback on all uncommitted transactions. It can take a while if you have large uncommitted transactions that need to be rolled back.

5. Oracle - Shutdown the database ( the less nice way )

shutdown abort

This is approximately the same as a SIGKILL, though once again on all processes in the database. It's a signal to the database to stop everything immediately and die - a hard crash. It terminates all sessions and does no rollback; because of this it can mean that the database takes longer to startup again. Despite the incendiary language a shutdown abort isn't pure evil and can normally be used safely.

As before inform people the relevant people first.

6. OS - Reboot the server

reboot

Obviously, this not only stops the database but the server as well so use with caution and with the consent of your sysadmins in addition to the DBAs, developers, clients and users.

7. OS - The last stage

I've had reboot not work... Once you've reached this stage you better hope you're using a VM. We ended up deleting it...

How to get host name with port from a http or https request

You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.

StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
  host = host.substring(idx); //remove scheme if present
}

SQL JOIN and different types of JOINs

I have created an illustration that explains better than words, in my opinion: SQL Join table of explanation

Why isn't my Pandas 'apply' function referencing multiple columns working?

All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations (as pointed out here).

import pandas as pd
import numpy as np


df = pd.DataFrame ({'a' : np.random.randn(6),
             'b' : ['foo', 'bar'] * 3,
             'c' : np.random.randn(6)})

Example 1: looping with pandas.apply():

%%timeit
def my_test2(row):
    return row['a'] % row['c']

df['Value'] = df.apply(my_test2, axis=1)

The slowest run took 7.49 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 481 µs per loop

Example 2: vectorize using pandas.apply():

%%timeit
df['a'] % df['c']

The slowest run took 458.85 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 70.9 µs per loop

Example 3: vectorize using numpy arrays:

%%timeit
df['a'].values % df['c'].values

The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 6.39 µs per loop

So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.

Django CharField vs TextField

For eg.,. 2 fields are added in a model like below..

description = models.TextField(blank=True, null=True)
title = models.CharField(max_length=64, blank=True, null=True)

Below are the mysql queries executed when migrations are applied.


for TextField(description) the field is defined as a longtext

ALTER TABLE `sometable_sometable` ADD COLUMN `description` longtext NULL;

The maximum length of TextField of MySQL is 4GB according to string-type-overview.


for CharField(title) the max_length(required) is defined as varchar(64)

ALTER TABLE `sometable_sometable` ADD COLUMN `title` varchar(64) NULL;
ALTER TABLE `sometable_sometable` ALTER COLUMN `title` DROP DEFAULT;

How to get value at a specific index of array In JavaScript?

You can just use []:

var valueAtIndex1 = myValues[1];

Difference between IISRESET and IIS Stop-Start command

Take IISReset as a suite of commands that helps you manage IIS start / stop etc.

Which means you need to specify option (/switch) what you want to do to carry any operation.

Default behavior OR default switch is /restart with iisreset so you do not need to run command twice with /start and /stop.

Hope this clarifies your question. For reference the output of iisreset /? is:

IISRESET.EXE (c) Microsoft Corp. 1998-2005

Usage:
iisreset [computername]

    /RESTART            Stop and then restart all Internet services.
    /START              Start all Internet services.
    /STOP               Stop all Internet services.
    /REBOOT             Reboot the computer.
    /REBOOTONERROR      Reboot the computer if an error occurs when starting,
                        stopping, or restarting Internet services.
    /NOFORCE            Do not forcefully terminate Internet services if
                        attempting to stop them gracefully fails.
    /TIMEOUT:val        Specify the timeout value ( in seconds ) to wait for
                        a successful stop of Internet services. On expiration
                        of this timeout the computer can be rebooted if
                        the /REBOOTONERROR parameter is specified.
                        The default value is 20s for restart, 60s for stop,
                        and 0s for reboot.
    /STATUS             Display the status of all Internet services.
    /ENABLE             Enable restarting of Internet Services
                        on the local system.
    /DISABLE            Disable restarting of Internet Services
                        on the local system.

Format Instant to String

DateTimeFormatter.ISO_INSTANT.format(Instant.now())

This saves you from having to convert to UTC. However, some other language's time frameworks may not support the milliseconds so you should do

DateTimeFormatter.ISO_INSTANT.format(Instant.now().truncatedTo(ChronoUnit.SECONDS))

How to get the URL of the current page in C#

I guess its enough to return absolute path..

 Path.GetFileName( Request.Url.AbsolutePath )

using System.IO;

"error: assignment to expression with array type error" when I assign a struct field (C)

You are facing issue in

 s1.name="Paolo";

because, in the LHS, you're using an array type, which is not assignable.

To elaborate, from C11, chapter §6.5.16

assignment operator shall have a modifiable lvalue as its left operand.

and, regarding the modifiable lvalue, from chapter §6.3.2.1

A modifiable lvalue is an lvalue that does not have array type, [...]

You need to use strcpy() to copy into the array.

That said, data s1 = {"Paolo", "Rossi", 19}; works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]

Change value of input and submit form in JavaScript

This might help you.

Your HTML

<form id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="save()" />
</form>

Your Script

    <script>
        function save(){
            $('#myinput').val('1');
            $('#form').submit();
        }
    </script>

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

How do I use modulus for float/double?

Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):

From JLS §15.17.3:

The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:

  • If either operand is NaN, the result is NaN.
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r=n-(d·q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

You just need to manually set the desired permissions with chmod():

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);

    // Set perms with chmod()
    chmod($file, 0777);
    return true;
}

How to fix Ora-01427 single-row subquery returns more than one row in select?

The only subquery appears to be this - try adding a ROWNUM limit to the where to be sure:

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE on the matched date.

For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.

 SELECT 
    ...
    REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
            ' ',
            '') AS WORKDATE,
    ...
 INNER JOIN T_EMPLOYEE_MS E
    ...
     LEFT OUTER JOIN T_COMPENSATION C
          ON C.I_COMPENSATEDDATE = A.I_REQDATE
          AND C.I_EMPID = A.I_EMPID
    ...

Char array declaration and initialization in C

myarray = "abc";

...is the assignation of a pointer on "abc" to the pointer myarray.

This is NOT filling the myarray buffer with "abc".

If you want to fill the myarray buffer manually, without strcpy(), you can use:

myarray[0] = 'a', myarray[1] = 'b', myarray[2] = 'c', myarray[3] = 0;

or

char *ptr = myarray;
*ptr++ = 'a', *ptr++ = 'b', *ptr++ = 'c', *ptr = 0;

Your question is about the difference between a pointer and a buffer (an array). I hope you now understand how C addresses each kind.

Difference between Date(dateString) and new Date(dateString)

I know this is old but by far the easier solution is to just use

var temp = new Date("2010-08-17T12:09:36");

python encoding utf-8

You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode before it can encode it back to UTF-8. That is what is failing here:

>>> data = u'\u00c3'            # Unicode data
>>> data = data.encode('utf8')  # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8')         # Try to *re*-encode it
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Just write your data directly to the file, there is no need to encode already-encoded data.

If you instead build up unicode values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open() instead, which returns a file object that will encode unicode values to UTF-8 for you.

You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).

For your MySQL insert problem, you need to do two things:

  • Add charset='utf8' to your MySQLdb.connect() call.

  • Use unicode objects, not str objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:

    artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode
    
    c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    
    # ...
    
    c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
    

It may actually work better if you used codecs.open() to decode the contents automatically instead:

import codecs

sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
    for line in findex:
        if u'#artiste' not in line:
            continue

        artiste=line.split(u'[:::]')[1].strip()

    cursor = sql.cursor()
    cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    if not cursor.fetchone()[0]:
        cursor = sql.cursor()
        cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
        artists_inserted += 1

You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:

In SQL Server, what does "SET ANSI_NULLS ON" mean?

SET ANSI_NULLS ON

IT Returns all values including null values in the table

SET ANSI_NULLS off

it Ends when columns contains null values

Initializing a member array in constructor initializer

Workaround:

template<class T, size_t N>
struct simple_array { // like std::array in C++0x
   T arr[N];
};


class C : private simple_array<int, 3> 
{
      static simple_array<int, 3> myarr() {
           simple_array<int, 3> arr = {1,2,3};
           return arr;
      }
public:
      C() : simple_array<int, 3>(myarr()) {}
};

How to open an external file from HTML

You may need an extra "/"

<a href="file:///server/directory/file.xlsx">Click me!</a>

Code snippet or shortcut to create a constructor in Visual Studio

Type the name of any code snippet and press TAB.

To get code for properties you need to choose the correct option and press TAB twice because Visual Studio has more than one option which starts with 'prop', like 'prop', 'propa', and 'propdp'.

Add to Array jQuery

push is a native javascript method. You could use it like this:

var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]

String.strip() in Python

No, it is better practice to leave them out.

Without strip(), you can have empty keys and values:

apples<tab>round, fruity things
oranges<tab>round, fruity things
bananas<tab>

Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I had the same problem with System.Web.Http.WebHost, Version=5.2.6.0 being referenced but the latest NuGet package was 5.2.7.0. I edited the web.config files, re-installed the NuGet package, then edited the visual studio project files for all of my projects to make sure no references to 5.2.6.0 persisted. Even after all this, the problem persisted.

Then I looked in the bin folder for the project that was throwing the exception, where I found a DLL for one of my other projects that is not a dependency and should never have been there. I deleted the offending DLL (which had been compiled using the 5.2.6.0 version of System.Web.Http.WebHost), rebuilt the troublesome project, and now it is working.

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Converting from IEnumerable to List

If you're using an implementation of System.Collections.IEnumerable you can do like following to convert it to a List. The following uses Enumerable.Cast method to convert IEnumberable to a Generic List.

//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");

List<string> provinces = _provinces.Cast<string>().ToList();

If you're using Generic version IEnumerable<T>, The conversion is straight forward. Since both are generics, you can do like below,

IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();

But if the IEnumerable is null, when you try to convert it to a List, you'll get ArgumentNullException saying Value cannot be null.

IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();

enter image description here

Therefore as mentioned in the other answer, remember to do a null check before converting it to a List.

How to install Boost on Ubuntu

Get the version of Boost that you require. This is for 1.55 but feel free to change or manually download yourself:

wget -O boost_1_55_0.tar.gz https://sourceforge.net/projects/boost/files/boost/1.55.0/boost_1_55_0.tar.gz/download
tar xzvf boost_1_55_0.tar.gz
cd boost_1_55_0/

Get the required libraries, main ones are icu for boost::regex support:

sudo apt-get update
sudo apt-get install build-essential g++ python-dev autotools-dev libicu-dev libbz2-dev libboost-all-dev

Boost's bootstrap setup:

./bootstrap.sh --prefix=/usr/

Then build it with:

./b2

and eventually install it:

sudo ./b2 install

What is the preferred/idiomatic way to insert into a map?

In short, [] operator is more efficient for updating values because it involves calling default constructor of the value type and then assigning it a new value, while insert() is more efficient for adding values.

The quoted snippet from Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library by Scott Meyers, Item 24 might help.

template<typename MapType, typename KeyArgType, typename ValueArgType>
typename MapType::iterator
insertKeyAndValue(MapType& m, const KeyArgType&k, const ValueArgType& v)
{
    typename MapType::iterator lb = m.lower_bound(k);

    if (lb != m.end() && !(m.key_comp()(k, lb->first))) {
        lb->second = v;
        return lb;
    } else {
        typedef typename MapType::value_type MVT;
        return m.insert(lb, MVT(k, v));
    }
}

You may decide to choose a generic-programming-free version of this, but the point is that I find this paradigm (differentiating 'add' and 'update') extremely useful.

scale Image in an UIButton to AspectFit?

None of the answers here really worked for me, I solved the problem with the following code:

button.contentMode = UIViewContentModeScaleToFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

You can do this in the Interface Builder as well.

enter image description here

Cannot access wamp server on local network

Perhaps your Apache is bounded to localhost only. Look in your apache configuration file for:

Listen 127.0.0.1:80

If you found it, replace it for:

Listen 80

(More info about Apache Binding)

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

In my case, it was caused by a missing (0) in javascript:void(0) in an anchor.

Truncate a string straight JavaScript

Yes, substring works great:

stringTruncate('Hello world', 5); //output "Hello..."
stringTruncate('Hello world', 20);//output "Hello world"

var stringTruncate = function(str, length){
  var dots = str.length > length ? '...' : '';
  return str.substring(0, length)+dots;
};

Collision resolution in Java HashMap

First of all, you have got the concept of hashing a little wrong and it had been rectified by Mr. Sanjay.

And yes, Java indeed implement a collision resolution technique. When two keys get hashed to a same value (as the internal array used is finite in size and at some point the hashcode() method will return same hash value for two different keys) at this time, a linked list is formed at the bucket location where all the informations are entered as an Map.Entry object that contains a key-value pair. Accessing an object via a key will at worst require O(n) if the entry in present in such a lists. Comparison between the key you passed with each key in such list will be done by the equals() method.

Although, from Java 8 , the linked lists are replaced with trees (O(log n))

Using varchar(MAX) vs TEXT on SQL Server

The VARCHAR(MAX) type is a replacement for TEXT. The basic difference is that a TEXT type will always store the data in a blob whereas the VARCHAR(MAX) type will attempt to store the data directly in the row unless it exceeds the 8k limitation and at that point it stores it in a blob.

Using the LIKE statement is identical between the two datatypes. The additional functionality VARCHAR(MAX) gives you is that it is also can be used with = and GROUP BY as any other VARCHAR column can be. However, if you do have a lot of data you will have a huge performance issue using these methods.

In regard to if you should use LIKE to search, or if you should use Full Text Indexing and CONTAINS. This question is the same regardless of VARCHAR(MAX) or TEXT.

If you are searching large amounts of text and performance is key then you should use a Full Text Index.

LIKE is simpler to implement and is often suitable for small amounts of data, but it has extremely poor performance with large data due to its inability to use an index.

Saving response from Requests to file

I believe all the existing answers contain the relevant information, but I would like to summarize.

The response object that is returned by requests get and post operations contains two useful attributes:

Response attributes

  • response.text - Contains str with the response text.
  • response.content - Contains bytes with the raw response content.

You should choose one or other of these attributes depending on the type of response you expect.

  • For text-based responses (html, json, yaml, etc) you would use response.text
  • For binary-based responses (jpg, png, zip, xls, etc) you would use response.content.

Writing response to file

When writing responses to file you need to use the open function with the appropriate file write mode.

  • For text responses you need to use "w" - plain write mode.
  • For binary responses you need to use "wb" - binary write mode.

Examples

Text request and save

# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
    f.write(response.text)

Binary request and save

# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
    f.write(response.content)

Answering the original question

The original code should work by using wb and response.content:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "wb")
file.write(response.content)
file.close()

But I would go further and use the with context manager for open.

import requests

with open('1.pdf', 'rb') as file:
    files = {'f': ('1.pdf', file)}
    response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)

response.raise_for_status() # ensure we notice bad responses

with open("out.xls", "wb") as file:
    file.write(response.content)

Running interactive commands in Paramiko

You can use this method to send whatever confirmation message you want like "OK" or the password. This is my solution with an example:

def SpecialConfirmation(command, message, reply):
    net_connect.config_mode()    # To enter config mode
    net_connect.remote_conn.sendall(str(command)+'\n' )
    time.sleep(3)
    output = net_connect.remote_conn.recv(65535).decode('utf-8')
    ReplyAppend=''
    if str(message) in output:
        for i in range(0,(len(reply))):
            ReplyAppend+=str(reply[i])+'\n'
        net_connect.remote_conn.sendall(ReplyAppend)
        output = net_connect.remote_conn.recv(65535).decode('utf-8') 
    print (output)
    return output

CryptoPkiEnroll=['','','no','no','yes']

output=SpecialConfirmation ('crypto pki enroll TCA','Password' , CryptoPkiEnroll )
print (output)

How to list all the available keyspaces in Cassandra?

  1. login to cqlsh

  2. use below command to get names/list of keyspaces present

         SELECT keyspace_name FROM system_schema.keyspaces;
    

Android Studio Emulator and "Process finished with exit code 0"

In AVD Manager,

Go to Edit Icon on AVD Manager for selected Device.

Click on show advanced settings and increase ram size from 1500 mb to 2 GB.

Then it works.

NOTE: Some virtual devices do not allow you to update RAM, but if so, try installing Nexus 4. because it does.

NOTE2: If still doesnt work, dont give up. just uninstall and reinstall the device with changing RAM again. in some cases this is how it works

NOTE3: If still doesnt work, this means your pc doesnt have enough ram space. so increase the ram to 3gb. it might work but it will suffer

NOTE4: If still doesnt work, try it with multicore 2 instead of 4.

NOTE5: Still doesnt work. Close the Android Studio and NEVER open it back :)

CSS position:fixed inside a positioned element

I achieved to have an element with a fixed position (wiewport) but relative to the width of its parent.

I just had to wrap my fixed element and give the parent a width 100%. At the same time, the wrapped fixed element and the parent are in a div which width changes depending on the page, containing the content of the website. With this approach I can have the fixed element always at the same distance of the content, depending on the width of this one. In my case this was a 'to top' button, always showing at 15px from the bottom and 15px right from the content.

https://codepen.io/rafaqf/pen/MNqWKB

<div class="body">
  <div class="content">
    <p>Some content...</p>
    <div class="top-wrapper">
      <a class="top">Top</a>
    </div>
  </div>
</div>

.content {
  width: 600px; /*change this width to play with the top element*/
  background-color: wheat;
  height: 9999px;
  margin: auto;
  padding: 20px;
}
.top-wrapper {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  z-index: 9;
  .top {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    border-radius: 100%;
    background-color: yellowgreen;
    position: fixed;
    bottom: 20px;
    margin-left: 100px;
    cursor: pointer;
    &:hover {
      opacity: .6;
    }
  }
}

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

You can use this css:

.inactiveLink {
   pointer-events: none;
   cursor: default;
}

And then assign the class to your html code:

<a style="" href="page.html" class="inactiveLink">page link</a>

It makes the link not clickeable and the cursor style an arrow, not a hand as the links have.

or use this style in the html:

<a style="pointer-events: none; cursor: default;" href="page.html">page link</a>

but I suggest the first approach.

Add/remove HTML inside div using JavaScript

Add HTML inside div using JavaScript

Syntax:

element.innerHTML += "additional HTML code"

or

element.innerHTML = element.innerHTML + "additional HTML code"

Remove HTML inside div using JavaScript

elementChild.remove();

Multiple radio button groups in one form

Just do one thing, We need to set the name property for the same types. for eg.

Try below:

<form>
    <div id="group1">
        <input type="radio" value="val1" name="group1">
        <input type="radio" value="val2" name="group1">
    </div>
</form>

And also we can do it in angular1,angular 2 or in jquery also.

<div *ngFor="let option of question.options; index as j">
<input type="radio" name="option{{j}}" value="option{{j}}" (click)="checkAnswer(j+1)">{{option}}
</div>  

How to compile Tensorflow with SSE4.2 and AVX instructions?

These are SIMD vector processing instruction sets.

Using vector instructions is faster for many tasks; machine learning is such a task.

Quoting the tensorflow installation docs:

To be compatible with as wide a range of machines as possible, TensorFlow defaults to only using SSE4.1 SIMD instructions on x86 machines. Most modern PCs and Macs support more advanced instructions, so if you're building a binary that you'll only be running on your own machine, you can enable these by using --copt=-march=native in your bazel build command.

How to use java.net.URLConnection to fire and handle HTTP requests?

Update

The new HTTP Client shipped with Java 9 but as part of an Incubator module named jdk.incubator.httpclient. Incubator modules are a means of putting non-final APIs in the hands of developers while the APIs progress towards either finalization or removal in a future release.

In Java 9, you can send a GET request like:

// GET
HttpResponse response = HttpRequest
    .create(new URI("http://www.stackoverflow.com"))
    .headers("Foo", "foovalue", "Bar", "barvalue")
    .GET()
    .response();

Then you can examine the returned HttpResponse:

int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());

Since this new HTTP Client is in java.httpclient jdk.incubator.httpclient module, you should declare this dependency in your module-info.java file:

module com.foo.bar {
    requires jdk.incubator.httpclient;
}

Installing Bower on Ubuntu

Hi another solution to this problem is to simply add the node nodejs binary folder to your PATH using the following command:

ln -s /usr/bin/nodejs /usr/bin/node

See NPM GitHub for better explanation

Horizontal scroll css?

Below worked for me.

Height & width are taken to show that, if you 2 such children, it will scroll horizontally, since height of child is greater than height of parent scroll vertically.

Parent CSS:

.divParentClass {
    width: 200px;
    height: 100px;
    overflow: scroll;
    white-space: nowrap;
}

Children CSS:

.divChildClass {
    width: 110px;
    height: 200px;
    display: inline-block;
}

To scroll horizontally only:

overflow-x: scroll;
overflow-y: hidden;

To scroll vertically only:

overflow-x: hidden;
overflow-y: scroll;

How do I execute a stored procedure in a SQL Agent job?

You just need to add this line to the window there:

exec (your stored proc name) (and possibly add parameters)

What is your stored proc called, and what parameters does it expect?

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

This should be able to set to whatever keybindings you want for indent/outdent here:

Menu FilePreferencesKeyboard Shortcuts

editor.action.indentLines

editor.action.outdentLines

How to create a JQuery Clock / Timer

var timeInterval = 5;
    var blinkTime = 1;
    var open_signal = 'top_left';

    $(document).ready(function () {
        $('#div_top_left .timer').html(timeInterval);
        $('#div_top_right .timer').html(timeInterval);
        $('#div_bottom_right .timer').html(timeInterval * 2);
        $('#div_bottom_left .timer').html(timeInterval * 3);

        $('#div_top_left .green').css('background-color', 'green');
        $('#div_top_right .red').css('background-color', 'red');
        $('#div_bottom_right .red').css('background-color', 'red');
        $('#div_bottom_left .red').css('background-color', 'red');

        setInterval(function () {
            manageSignals();
        }, 1000);
    });

    function manageSignals() {
        var top_left_time = parseInt($('#div_top_left .timer').html()) - 1;
        var top_right_time = parseInt($('#div_top_right .timer').html()) - 1;
        var bottom_left_time = parseInt($('#div_bottom_left .timer').html()) - 1;
        var bottom_right_time = parseInt($('#div_bottom_right .timer').html()) - 1;

        if (top_left_time == -1 && open_signal == 'top_left') open_signal = 'top_right';
        else if (top_right_time == -1 && open_signal == 'top_right') open_signal = 'bottom_right';
        else if (bottom_right_time == -1 && open_signal == 'bottom_right') open_signal = 'bottom_left';
        else if (bottom_left_time == -1 && open_signal == 'bottom_left') open_signal = 'top_left';

        if (top_left_time == -1) {
            if (open_signal == 'top_right') {
                top_left_time = (timeInterval * 3) - 1;
                $('#div_top_left .red').css('background-color', 'red');
                $('#div_top_left .yellow').css('background-color', 'white');
                $('#div_top_left .green').css('background-color', 'white');
            }
            else if (open_signal == 'top_left') {
                top_left_time = timeInterval - 1;
                $('#div_top_left .red').css('background-color', 'white');
                $('#div_top_left .yellow').css('background-color', 'white');
                $('#div_top_left .green').css('background-color', 'green');
            }
        }

        if (top_right_time == -1) {
            if (open_signal == 'bottom_right') {
                top_right_time = (timeInterval * 3) - 1;
                $('#div_top_right .red').css('background-color', 'red');
                $('#div_top_right .yellow').css('background-color', 'white');
                $('#div_top_right .green').css('background-color', 'white');
            }
            else if (open_signal == 'top_right') {
                top_right_time = timeInterval - 1;
                $('#div_top_right .red').css('background-color', 'white');
                $('#div_top_right .yellow').css('background-color', 'white');
                $('#div_top_right .green').css('background-color', 'green');
            }
        }

        if (bottom_right_time == -1) {
            if (open_signal == 'bottom_left') {
                bottom_right_time = (timeInterval * 3) - 1;
                $('#div_bottom_right .red').css('background-color', 'red');
                $('#div_bottom_right .yellow').css('background-color', 'white');
                $('#div_bottom_right .green').css('background-color', 'white');
            }
            else if (open_signal == 'bottom_right') {
                bottom_right_time = timeInterval - 1;
                $('#div_bottom_right .red').css('background-color', 'white');
                $('#div_bottom_right .yellow').css('background-color', 'white');
                $('#div_bottom_right .green').css('background-color', 'green');
            }
        }

        if (bottom_left_time == -1) {
            if (open_signal == 'top_left') {
                bottom_left_time = (timeInterval * 3) - 1;
                $('#div_bottom_left .red').css('background-color', 'red');
                $('#div_bottom_left .yellow').css('background-color', 'white');
                $('#div_bottom_left .green').css('background-color', 'white');
            }
            else if (open_signal == 'bottom_left') {
                bottom_left_time = timeInterval - 1;
                $('#div_bottom_left .red').css('background-color', 'white');
                $('#div_bottom_left .yellow').css('background-color', 'white');
                $('#div_bottom_left .green').css('background-color', 'green');
            }
        }

        if (top_left_time == blinkTime && open_signal == 'top_left') {
            $('#div_top_left .yellow').css('background-color', 'yellow');
            $('#div_top_left .green').css('background-color', 'white');
        }
        if (top_right_time == blinkTime && open_signal == 'top_right') {
            $('#div_top_right .yellow').css('background-color', 'yellow');
            $('#div_top_right .green').css('background-color', 'white');
        }
        if (bottom_left_time == blinkTime && open_signal == 'bottom_left') {
            $('#div_bottom_left .yellow').css('background-color', 'yellow');
            $('#div_bottom_left .green').css('background-color', 'white');
        }
        if (bottom_right_time == blinkTime && open_signal == 'bottom_right') {
            $('#div_bottom_right .yellow').css('background-color', 'yellow');
            $('#div_bottom_right .green').css('background-color', 'white');
        }

        $('#div_top_left .timer').html(top_left_time);
        $('#div_top_right .timer').html(top_right_time);
        $('#div_bottom_left .timer').html(bottom_left_time);
        $('#div_bottom_right .timer').html(bottom_right_time);
    }

Subtract two dates in SQL and get days of the result

How about

Select I.Fee
From Item I
WHERE  (days(GETDATE()) - days(I.DateCreated) < 365)

Select distinct values from a table field

By example:

# select distinct code from Platform where id in ( select platform__id from Build where product=p)
pl_ids = Build.objects.values('platform__id').filter(product=p)
platforms = Platform.objects.values_list('code', flat=True).filter(id__in=pl_ids).distinct('code')
platforms = list(platforms) if platforms else []

How do you do Impersonation in .NET?

Here is some good overview of .NET impersonation concepts.

Basically you will be leveraging these classes that are out of the box in the .NET framework:

The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

How to update Git clone

If you want to fetch + merge, run

git pull

if you want simply to fetch :

git fetch

How do you list the primary key of a SQL Server table?

SELECT Col.Column_Name from 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
WHERE 
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY'
    AND Col.Table_Name = '<your table name>'

AND/OR in Python?

As Matt Ball's answer explains, or is "and/or". But or doesn't work with in the way you use it above. You have to say if "a" in someList or "á" in someList or.... Or better yet,

if any(c in someList for c in ("a", "á", "à", "ã", "â")):
    ...

That's the answer to your question as asked.

Other Notes

However, there are a few more things to say about the example code you've posted. First, the chain of someList.remove... or someList remove... statements here is unnecessary, and may result in unexpected behavior. It's also hard to read! Better to break it into individual lines:

someList.remove("a")
someList.remove("á")
...

Even that's not enough, however. As you observed, if the item isn't in the list, then an error is thrown. On top of that, using remove is very slow, because every time you call it, Python has to look at every item in the list. So if you want to remove 10 different characters, and you have a list that has 100 characters, you have to perform 1000 tests.

Instead, I would suggest a very different approach. Filter the list using a set, like so:

chars_to_remove = set(("a", "á", "à", "ã", "â"))
someList = [c for c in someList if c not in chars_to_remove]

Or, change the list in-place without creating a copy:

someList[:] = (c for c in someList if c not in chars_to_remove)

These both use list comprehension syntax to create a new list. They look at every character in someList, check to see of the character is in chars_to_remove, and if it is not, they include the character in the new list.

This is the most efficient version of this code. It has two speed advantages:

  1. It only passes through someList once. Instead of performing 1000 tests, in the above scenario, it performs only 100.
  2. It can test all characters with a single operation, because chars_to_remove is a set. If it chars_to_remove were a list or tuple, then each test would really be 10 tests in the above scenario -- because each character in the list would need to be checked individually.

How to replace all occurrences of a string in Javascript?

In terms of performance related to the main answers these are some online tests.

While the following are some performance tests using console.time() (they work best in your own console, the time is very short to be seen in the snippet)

_x000D_
_x000D_
console.time('split and join');_x000D_
"javascript-test-find-and-replace-all".split('-').join(' ');_x000D_
console.timeEnd('split and join')_x000D_
_x000D_
console.time('regular expression');_x000D_
"javascript-test-find-and-replace-all".replace(new RegExp('-', 'g'), ' ');_x000D_
console.timeEnd('regular expression');_x000D_
_x000D_
console.time('while');_x000D_
let str1 = "javascript-test-find-and-replace-all";_x000D_
while (str1.indexOf('-') !== -1) {_x000D_
    str1 = str1.replace('-', ' ');_x000D_
}_x000D_
console.timeEnd('while');
_x000D_
_x000D_
_x000D_

The interesting thing to notice is that if you run them multiple time the results are always different even though the RegExp solution seems the fastest on average and the while loop solution the slowest.

Create a folder inside documents folder in iOS apps

I do that the following way:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

Matplotlib: "Unknown projection '3d'" error

I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.

but I should add more infomation when you use pycharm and enable auto import.

when you format the code, the code from mpl_toolkits.mplot3d import Axes3D will auto remove by pycharm.

so, my solution is

from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D  # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

and it works well!

Spring Boot REST API - request timeout?

You can try server.connection-timeout=5000 in your application.properties. From the official documentation:

server.connection-timeout= # Time in milliseconds that connectors will wait for another HTTP request before closing the connection. When not set, the connector's container-specific default will be used. Use a value of -1 to indicate no (i.e. infinite) timeout.

On the other hand, you may want to handle timeouts on the client side using Circuit Breaker pattern as I have already described in my answer here: https://stackoverflow.com/a/44484579/2328781

How to change Navigation Bar color in iOS 7?

For Color :

[[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];

For Image

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navigationBar_320X44.png"] forBarMetrics:UIBarMetricsDefault];

Disable Pinch Zoom on Mobile Web

Found here you can use user-scalable=no:

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

Post a json object to mvc controller with jquery and ajax

instead of receiving the json string a model binding is better. For example:

[HttpPost]       
public ActionResult AddUser(UserAddModel model)
{
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" });
    }
    return Json(new { Response = "Error" });
}

<script>
function submitForm() {    
    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: $("form[name=UserAddForm]").serialize(),
        success: function (data) {
            console.log(data);
        }
    });
}
</script>

How to lay out Views in RelativeLayout programmatically?

Try:

EditText edt = (EditText) findViewById(R.id.YourEditText);
RelativeLayout.LayoutParams lp =
    new RelativeLayout.LayoutParams
    (
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT
    );
lp.setMargins(25, 0, 0, 0); // move 25 px to right (increase left margin)
edt.setLayoutParams(lp); // lp.setMargins(left, top, right, bottom);

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

Lot's of great answer. I just want to add a small note about decoupling the stream.

cin.tie(NULL);

I have faced an issue while decoupling the stream with CodeChef platform. When I submitted my code, the platform response was "Wrong Answer" but after tying the stream and testing the submission. It worked.

So, If anyone wants to untie the stream, the output stream must be flushed.

Edit: I am not familiar with all the platform but this is what I have experienced.

Cassandra cqlsh - connection refused

cqlsh --cqlversion="3.4.0" Connected to Test Cluster at 127.0.0.1:9042. [cqlsh 5.0.1 | Cassandra 3.0.9 | CQL spec 3.4.0 | Native protocol v4]

try the above command. It works for me.

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

How to concatenate two numbers in javascript?

This is the easy way to do this

var value = 5 + "" + 6;

How do I check the operating system in Python?

If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:

>>> import platform
>>> platform.system()
'Linux'  # or 'Windows'/'Darwin'

The platform.system function uses uname internally.

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

How do I test a private function or a class that has private methods, fields or inner classes?

A quick addition to @Cem Catikka's comment, when using ExpectedException:

Keep in mind that your expected exception will be wrapped in an InvocationTargetException, so in order to get to your exception you will have to throw the cause of the InvocationTargetException you received. Something like (testing private method validateRequest() on BizService):

@Rule
public ExpectedException thrown = ExpectedException.none();

@Autowired(required = true)
private BizService svc;


@Test
public void testValidateRequest() throws Exception {

    thrown.expect(BizException.class);
    thrown.expectMessage(expectMessage);

    BizRequest request = /* Mock it, read from source - file, etc. */;
    validateRequest(request);
}

private void validateRequest(BizRequest request) throws Exception {
    Method method = svc.getClass().getDeclaredMethod("validateRequest", BizRequest.class);
    method.setAccessible(true);
    try {
        method.invoke(svc, request);
    }
    catch (InvocationTargetException e) {
        throw ((BizException)e.getCause());
    }
 }

CSS: How to remove pseudo elements (after, before,...)?

p:after {
  content: none;
}

This is a way to remove the :after and you can do the same for :before

How to make clang compile to llvm IR

If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8 but you can use any other version):

  1. generate all .ll files

    clang-3.8 -S -emit-llvm *.c
    
  2. link them into a single one

    llvm-link-3.8 -S -v -o single.ll *.ll
    
  3. (Optional) Optimise your code (maybe some alias analysis)

    opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
    
  4. Generate assembly (generates a optimised.s file)

    llc-3.8 optimised.ll
    
  5. Create executable (named a.out)

    clang-3.8 optimised.s
    

What's the best way to convert a number to a string in JavaScript?

If you are curious as to which is the most performant check this out where I compare all the different Number -> String conversions.

Looks like 2+'' or 2+"" are the fastest.

https://jsperf.com/int-2-string

How do you change the document font in LaTeX?

For a different approach, I would suggest using the XeTeX or LuaTex system. They allow you to access system fonts (TrueType, OpenType, etc) and set font features. In a typical LaTeX document, you just need to include this in your headers:

\usepackage{fontspec}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont{Times}
\setmonofont{Lucida Sans Typewriter}

It's the fontspec package that allows for \setmainfont and \setmonofont. The ability to choose a multitude of font features is beyond my expertise, but I would suggest looking up some examples and seeing if this would suit your needs.

Just don't forget to replace your favorite latex compiler by the appropriate one (xelatex or lualatex).

Possible heap pollution via varargs parameter

Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

This can lead to "unexplainable" ClassCastExceptions.

// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0); 

@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.

However, if the method actually is not safe, users will no longer be warned.

How to validate GUID is a GUID

See if these helps :-

  1. Guid.Parse - Docs
Guid guidResult = Guid.Parse(inputString)
  1. Guid.TryParse - Docs
bool isValid = Guid.TryParse(inputString, out guidOutput)

Make a DIV fill an entire table cell

If your reason for wanting a 100% div inside a table cell was to be able to have a background color extend to the full height but still be able to have spacing between the cells, you could give the <td> itself the background color and use the CSS border-spacing property to create the margin between the cells.

If you truly need a 100% height div, however, then as others here have mentioned you need to either assign a fixed height to the <table> or use Javascript.

Rails 4 Authenticity Token

Did you try?

 protect_from_forgery with: :null_session, if: Proc.new {|c| c.request.format.json? }

What is the best way to use a HashMap in C++?

The standard library includes the ordered and the unordered map (std::map and std::unordered_map) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.

An example with (ordered) std::map:

#include <map>
#include <iostream>
#include <cassert>

int main(int argc, char **argv)
{
  std::map<std::string, int> m;
  m["hello"] = 23;
  // check if key is present
  if (m.find("world") != m.end())
    std::cout << "map contains key world!\n";
  // retrieve
  std::cout << m["hello"] << '\n';
  std::map<std::string, int>::iterator i = m.find("hello");
  assert(i != m.end());
  std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
  return 0;
}

Output:

23
Key: hello Value: 23

If you need ordering in your container and are fine with the O(log n) runtime then just use std::map.

Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map, which has a similar to std::map API (e.g. in the above example you just have to search and replace map with unordered_map).

The unordered_map container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11 to the CXXFLAGS).

Even before the C++11 release GCC supported unordered_map - in the namespace std::tr1. Thus, for old GCC compilers you can try to use it like this:

#include <tr1/unordered_map>

std::tr1::unordered_map<std::string, int> m;

It is also part of boost, i.e. you can use the corresponding boost-header for better portability.

Append lines to a file using a StreamWriter

Try this:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();

JavaScript/regex: Remove text between parentheses

If you need to remove text inside nested parentheses, too, then:

        var prevStr;
        do {
            prevStr = str;
            str = str.replace(/\([^\)\(]*\)/, "");
        } while (prevStr != str);

How to open my files in data_folder with pandas using relative path?

Pandas will start looking from where your current python file is located. Therefore you can move from your current directory to where your data is located with '..' For example:

pd.read_csv('../../../data_folder/data.csv')

Will go 3 levels up and then into a data_folder (assuming it's there) Or

pd.read_csv('data_folder/data.csv')

assuming your data_folder is in the same directory as your .py file.

How do I close a tkinter window?

from tkinter import *

def quit(root):
    root.close()

root = Tk()
root.title("Quit Window")

def quit(root):
    root.close()

button = Button(root, text="Quit", command=quit.pack()

root.mainloop()

Retrieve column names from java.sql.ResultSet

import java.sql.*;

public class JdbcGetColumnNames {

    public static void main(String args[]) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/komal", "root", "root");

            st = con.createStatement();

            String sql = "select * from person";
            rs = st.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();

            int rowCount = metaData.getColumnCount();

            System.out.println("Table Name : " + metaData.getTableName(2));
            System.out.println("Field  \tDataType");

            for (int i = 0; i < rowCount; i++) {
                System.out.print(metaData.getColumnName(i + 1) + "  \t");
                System.out.println(metaData.getColumnTypeName(i + 1));
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Table Name : person Field DataType id VARCHAR cname VARCHAR dob DATE

Invalid syntax when using "print"?

You need parentheses:

print(2**100)