Programs & Examples On #Lorem ipsum

Lorem ipsum is a standard piece of meaningless pseudo-Latin text used to fill in text layouts when the actual text is not available.

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

Just to add my own opinion, in case it might be useful to someone. This is what I used.

<div th:class="${request.read ? 'mdl-color-text--grey-800 w500' : ''}"> </div>

input() error - NameError: name '...' is not defined

Since you are writing for Python 3.x, you'll want to begin your script with:

#!/usr/bin/env python3

If you use:

#!/usr/bin/env python

It will default to Python 2.x. These go on the first line of your script, if there is nothing that starts with #! (aka the shebang).

If your scripts just start with:

#! python

Then you can change it to:

#! python3

Although this shorter formatting is only recognized by a few programs, such as the launcher, so it is not the best choice.

The first two examples are much more widely used and will help ensure your code will work on any machine that has Python installed.

Keras model.summary() result - Understanding the # of Parameters

For Dense Layers:

output_size * (input_size + 1) == number_parameters 

For Conv Layers:

output_channels * (input_channels * window_size + 1) == number_parameters

Consider following example,

model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
Conv2D(128, (3, 3), activation='relu'),
Dense(num_classes, activation='softmax')
])

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 222, 222, 32)      896       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 220, 220, 64)      18496     
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 218, 218, 128)     73856     
_________________________________________________________________
dense_9 (Dense)              (None, 218, 218, 10)      1290      
=================================================================

Calculating params,

assert 32 * (3 * (3*3) + 1) == 896
assert 64 * (32 * (3*3) + 1) == 18496
assert 128 * (64 * (3*3) + 1) == 73856
assert num_classes * (128 + 1) == 1290

How to convert AAR to JAR

Android Studio (version: 1.3.2) allows you to seamlessly access the .jar inside a .aar.

Bonus: it automatically decompiles the classes!

Simply follow these steps:

  1. File > New > New Module > Import .JAR/.AAR Package to import you .aar as a module

  2. Add the newly created module as a dependency to your main project (not sure if needed)

  3. Right click on "classes.jar" as shown in the capture below, and click "Show in explorer". Here is your .jar.

access .jar from .aar

cmake error 'the source does not appear to contain CMakeLists.txt'

You should do mkdir build and cd build while inside opencv folder, not the opencv-contrib folder. The CMakeLists.txt is there.

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

You are returning Observable<Product> and expecting it to be Product[] inside subscribe callback.

The Type returned from http.get() and getProducts() should be Observable<Product[]>

public getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(`api/products/v1/`);
}

Is there Unicode glyph Symbol to represent "Search"

Use the ? symbol (encoded as &#9906; or &#x26B2;), and rotate it to achieve the desired effect:

<div style="-webkit-transform: rotate(45deg); 
               -moz-transform: rotate(45deg); 
                 -o-transform: rotate(45deg);
                    transform: rotate(45deg);">
    &#9906;
</div>

It rotates a symbol :)

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

Multiple inheritance for an anonymous class

An anonymous class usually implements an interface:

new Runnable() { // implements Runnable!
   public void run() {}
}

JFrame.addWindowListener( new WindowAdapter() { // extends  class
} );

If you mean whether you can implement 2 or more interfaces, than I think that's not possible. You can then make a private interface which combines the two. Though I cannot easily imagine why you would want an anonymous class to have that:

 public class MyClass {
   private interface MyInterface extends Runnable, WindowListener { 
   }

   Runnable r = new MyInterface() {
    // your anonymous class which implements 2 interaces
   }

 }

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

Freely convert between List<T> and IEnumerable<T>

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();

How to change or add theme to Android Studio?

//you need to go to the File-> settings in that choose IDE settings-> Appearance in that choose the Theme: options

enter image description here

How to reload current page?

This is the most simple solution if you just need to refresh the entire page

   refreshPage() {
    window.location.reload();
   }

How to trigger HTML button when you press Enter in textbox?

You could add an event handler to your input like so:

document.getElementById('addLinks').onkeypress=function(e){
    if(e.keyCode==13){
        document.getElementById('linkadd').click();
    }
}

Read String line by line

You can try the following regular expression:

\r?\n

Code:

String input = "\nab\n\n    \n\ncd\nef\n\n\n\n\n";
String[] lines = input.split("\\r?\\n", -1);
int n = 1;
for(String line : lines) {
    System.out.printf("\tLine %02d \"%s\"%n", n++, line);
}

Output:

Line 01 ""
Line 02 "ab"
Line 03 ""
Line 04 "    "
Line 05 ""
Line 06 "cd"
Line 07 "ef"
Line 08 ""
Line 09 ""
Line 10 ""
Line 11 ""
Line 12 ""

Change project name on Android Studio

Video tutorial: https://youtu.be/7aQjiae2doU

  1. Refactor the name to com.example.[NewFileName] in path:

    app>java>com.example.[OldFileName]


  1. Go to strings.xml and change code to <string name="app_name”>[NewFileName]</string> in path:

    app>res>values>strings.xml


  1. Go to build.gradle (Module: app) and change code to applicationId "com.example.[NewFileName]” in path:

    Gradle Scripts>build.gradle (Module: app)


  1. Go to settings.gradle (Project Settings) and change code to rootProject.name='[NewFileName]' in path:

    Gradle Scripts>build.gradle (Project Settings)


  1. Press Sync now prompt

  1. Rename your folder to [NewFileName] outside Android Studio

  1. Reopen your project and rebuild project in path:

    Build>Rebuild Project


How to print a stack trace in Node.js?

For what I know printing the complete stack trace in nodejs is not possible, you can just print a "partial" stack trace, you can not see from where you came from in the code, just where the Exception occur. That's what Ryan Dahl explains in this youtube video. http://youtu.be/jo_B4LTHi3I at min 56:30 for being precise. Hope this helps

A simple command line to download a remote maven2 artifact to the local repository?

Give them a trivial pom with these jars listed as dependencies and instructions to run:

mvn dependency:go-offline

This will pull the dependencies to the local repo.

A more direct solution is dependency:get, but it's a lot of arguments to type:

mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version

Python Pandas merge only certain columns

You can use .loc to select the specific columns with all rows and then pull that. An example is below:

pandas.merge(dataframe1, dataframe2.iloc[:, [0:5]], how='left', on='key')

In this example, you are merging dataframe1 and dataframe2. You have chosen to do an outer left join on 'key'. However, for dataframe2 you have specified .iloc which allows you to specific the rows and columns you want in a numerical format. Using :, your selecting all rows, but [0:5] selects the first 5 columns. You could use .loc to specify by name, but if your dealing with long column names, then .iloc may be better.

What are some reasons for jquery .focus() not working?

You need to either put the code below the HTML or load if using the document load event:

<input type="text" id="goal-input" name="goal" />
<script type="text/javascript">
$(function(){
    $("#goal-input").focus();
});
</script>

Update:

Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:

if (goal) {
      step1.fadeOut('fast', function() {
          step1.hide();
          step2.fadeIn('fast', function() {  
              $("#name").focus();
          });
      });
}

Why compile Python code?

There is a performance increase in running compiled python. However when you run a .py file as an imported module, python will compile and store it, and as long as the .py file does not change it will always use the compiled version.

With any interpeted language when the file is used the process looks something like this:
1. File is processed by the interpeter.
2. File is compiled
3. Compiled code is executed.

obviously by using pre-compiled code you can eliminate step 2, this applies python, PHP and others.

Heres an interesting blog post explaining the differences http://julipedia.blogspot.com/2004/07/compiled-vs-interpreted-languages.html
And here's an entry that explains the Python compile process http://effbot.org/zone/python-compile.htm

Difference between "as $key => $value" and "as $value" in PHP foreach

here $key will contain the $key associated with $value in $featured. The difference is that now you have that key.

array("thekey"=>array("name"=>"joe"))

here $value is

array("name"=>"joe")

$key is "thekey"

npm install gives error "can't find a package.json file"

node comes with npm installed so you should have a version of npm, however npm gets updated more frequently than node does, so you'll want to make sure it's the latest version.

sudo npm install npm -g

Test: Run npm -v. The version should be higher than 2.1.8.

npm install

THAT'S IT!

https://www.youtube.com/watch?v=wREima9e6vk

git: Your branch is ahead by X commits

In my case it was because I switched to master using

 git checkout -B master

Just to pull the new version of it instead of

 git checkout master

The first command resets the head of master to my latest commits

I used

git reset --hard origin/master

To fix that

Setting background-image using jQuery CSS property

Alternatively to what the others are correctly suggesting, I find it easier usually to toggle CSS classes, instead of individual CSS settings (especially background image URLs). For example:

// in CSS 
.bg1 
{
  background-image: url(/some/image/url/here.jpg);
}

.bg2 
{
  background-image: url(/another/image/url/there.jpg);
}

// in JS
// based on value of imageUrl, determine what class to remove and what class to add.
$('myOjbect').removeClass('bg1').addClass('bg2');

Get root password for Google Cloud Engine VM

This work at least in the Debian Jessie image hosted by Google:

The way to enable to switch from you regular to the root user (AKA “super user”) after authentificating with your Google Computer Engine (GCE) User in the local environment (your Linux server in GCE) is pretty straight forward, in fact it just involves just one command to enable it and another every time to use it:

$ sudo passwd
Enter the new UNIX password: <your new root password>
Retype the new UNIX password: <your new root password>
passwd: password updated successfully

After executing the previous command and once logged with your GCE User you will be able to switch to root anytime by just entering the following command:

$ su
Password: <your newly created root password>
root@intance:/#

As we say in economics “caveat emptor” or buyer be aware: Using the root user is far from a best practice in system’s administration. Using it can be the cause a lot of trouble, from wiping everything in your drives and boot disks without a hiccup to many other nasty stuff that would be laborious to backtrack, troubleshoot and rebuilt. On the other hand, I have never met a SysAdmin that doesn’t think he knows better and root more than he should.

REMEMBER: We humans are programmed in such a way that given enough time at one at some point or another are going to press enter without taking into account that we have escalated to root and I can assure you that it will great source of pain, regret and extra work. PLEASE USE ROOT PRIVILEGES SPARSELY AND WITH EXTREME CARE.

Having said all the boring stuff, Have fun, live on the edge, life is short, you only get to live it once, the more you break the more you learn.

How to detect shake event with android?

This is for Kotlin and use SensorEventListener

Create new class ShakeDetector

class ShakeDetector : SensorEventListener {
    private var mListener: OnShakeListener? = null
    private var mShakeTimestamp: Long = 0
    private var mShakeCount = 0
    fun setOnShakeListener(listener: OnShakeListener?) {
        mListener = listener
    }

    interface OnShakeListener {
        fun onShake(count: Int)
    }

    override fun onAccuracyChanged(
        sensor: Sensor,
        accuracy: Int
    ) { // ignore
    }

    override fun onSensorChanged(event: SensorEvent) {
        if (mListener != null) {
            val x = event.values[0]
            val y = event.values[1]
            val z = event.values[2]
            val gX = x / SensorManager.GRAVITY_EARTH
            val gY = y / SensorManager.GRAVITY_EARTH
            val gZ = z / SensorManager.GRAVITY_EARTH
            // gForce will be close to 1 when there is no movement.
            val gForce: Float = sqrt(gX * gX + gY * gY + gZ * gZ)
            if (gForce > SHAKE_THRESHOLD_GRAVITY) {
                val now = System.currentTimeMillis()
                // ignore shake events too close to each other (500ms)
                if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
                    return
                }
                // reset the shake count after 3 seconds of no shakes
                if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
                    mShakeCount = 0
                }
                mShakeTimestamp = now
                mShakeCount++
                mListener!!.onShake(mShakeCount)
            }
        }
    }

    companion object {
        /*
     * The gForce that is necessary to register as shake.
     * Must be greater than 1G (one earth gravity unit).
     * You can install "G-Force", by Blake La Pierre
     * from the Google Play Store and run it to see how
     *  many G's it takes to register a shake
     */
        private const val SHAKE_THRESHOLD_GRAVITY = 2.7f
        private const val SHAKE_SLOP_TIME_MS = 500
        private const val SHAKE_COUNT_RESET_TIME_MS = 3000
    }
}

Your main Activity

class MainActivity : AppCompatActivity() {

    // The following are used for the shake detection
    private var mSensorManager: SensorManager? = null
    private var mAccelerometer: Sensor? = null
    private var mShakeDetector: ShakeDetector? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initSensor()
    }
    override fun onResume() {
        super.onResume()
        // Add the following line to register the Session Manager Listener onResume
        mSensorManager!!.registerListener(
            mShakeDetector,
            mAccelerometer,
            SensorManager.SENSOR_DELAY_UI
        )
    }

    override fun onPause() { // Add the following line to unregister the Sensor Manager onPause
        mSensorManager!!.unregisterListener(mShakeDetector)
        super.onPause()
    }

    private fun initSensor() {
        // ShakeDetector initialization
        // ShakeDetector initialization
        mSensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        mAccelerometer = mSensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        mShakeDetector = ShakeDetector()
        mShakeDetector!!.setOnShakeListener(object : OnShakeListener {
            override fun onShake(count: Int) { /*
                 * The following method, "handleShakeEvent(count):" is a stub //
                 * method you would use to setup whatever you want done once the
                 * device has been shook.
                 */
                Toast.makeText(this@MainActivity, count.toString(), Toast.LENGTH_SHORT).show()
            }
        })
    }
}

Finally add this code to Manifests to make sure the phone has an accelerometer

<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />

Getting a union of two arrays in JavaScript

_x000D_
_x000D_
function unionArrays() {_x000D_
    var args = arguments,_x000D_
    l = args.length,_x000D_
    obj = {},_x000D_
    res = [],_x000D_
    i, j, k;_x000D_
_x000D_
    while (l--) {_x000D_
        k = args[l];_x000D_
        i = k.length;_x000D_
_x000D_
        while (i--) {_x000D_
            j = k[i];_x000D_
            if (!obj[j]) {_x000D_
                obj[j] = 1;_x000D_
                res.push(j);_x000D_
            }_x000D_
        }   _x000D_
    }_x000D_
_x000D_
    return res;_x000D_
}_x000D_
var unionArr = unionArrays([34, 35, 45, 48, 49], [44, 55]);_x000D_
console.log(unionArr);
_x000D_
_x000D_
_x000D_

Somewhat similar in approach to alejandro's method, but a little shorter and should work with any number of arrays.

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

I had the same issue, after accepting the license launching XCode or running sudo xcodebuild -license accept i had to restart my Mac – otherwise it did not worked.

C# - How to get Program Files (x86) on Windows 64 bit

One way would be to look for the "ProgramFiles(x86)" environment variable:

String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");

How can I capitalize the first letter of each word in a string using JavaScript?

function LetterCapitalize(str) { 
  return str.split(" ").map(item=>item.substring(0,1).toUpperCase()+item.substring(1)).join(" ")
}

How do I get the path to the current script with Node.js?

I found it after looking through the documentation again. What I was looking for were the __filename and __dirname module-level variables.

  • __filename is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js)
  • __dirname is the directory name of the current module. (ex:/home/kyle/some/dir)

How to detect when keyboard is shown and hidden

Swift 4 - dd 20 october 2017

override func viewDidLoad() {
    [..]

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
}

@objc func keyboardWillAppear(_ notification: NSNotification) {
    if let userInfo = notification.userInfo, 
       let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue).cgRectValue {
           let inset = keyboardFrame.height // if scrollView is not aligned to bottom of screen, subtract offset
           scrollView.contentInset.bottom = inset
           scrollView.scrollIndicatorInsets.bottom = inset
    }
}

@objc func keyboardWillDisappear(_ notification: NSNotification) {
    scrollView.contentInset.bottom = 0
    scrollView.scrollIndicatorInsets.bottom = 0
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

What's the difference between compiled and interpreted language?

As other have said, compiled and interpreted are specific to an implementation of a programming language; they are not inherent in the language. For example, there are C interpreters.

However, we can (and in practice we do) classify programming languages based on its most common (sometimes canonical) implementation. For example, we say C is compiled.

First, we must define without ambiguity interpreters and compilers:

An interpreter for language X is a program (or a machine, or just some kind of mechanism in general) that executes any program p written in language X such that it performs the effects and evaluates the results as prescribed by the specification of X.

A compiler from X to Y is a program (or a machine, or just some kind of mechanism in general) that translates any program p from some language X into a semantically equivalent program p' in some language Y in such a way that interpreting p' with an interpreter for Y will yield the same results and have the same effects as interpreting p with an interpreter for X.

Notice that from a programmer point of view, CPUs are machine interpreters for their respective native machine language.

Now, we can do a tentative classification of programming languages into 3 categories depending on its most common implementation:

  • Hard Compiled languages: When the programs are compiled entirely to machine language. The only interpreter used is a CPU. Example: Usually, to run a program in C, the source code is compiled to machine language, which is then executed by a CPU.
  • Interpreted languages: When there is no compilation of any part of the original program to machine language. In other words, no new machine code is generated; only existing machine code is executed. An interpreter other than the CPU must also be used (usually a program).Example: In the canonical implementation of Python, the source code is compiled first to Python bytecode and then that bytecode is executed by CPython, an interpreter program for Python bytecode.
  • Soft Compiled languages: When an interpreter other than the CPU is used but also parts of the original program may be compiled to machine language. This is the case of Java, where the source code is compiled to bytecode first and then, the bytecode may be interpreted by the Java Interpreter and/or further compiled by the JIT compiler.

Sometimes, soft and hard compiled languages are refered to simply compiled, thus C#, Java, C, C++ are said to be compiled.

Within this categorization, JavaScript used to be an interpreted language, but that was many years ago. Nowadays, it is JIT-compiled to native machine language in most major JavaScript implementations so I would say that it falls into soft compiled languages.

How to rearrange Pandas column sequence?

I would suggest you just write a function to do what you're saying probably using drop (to delete columns) and insert to insert columns at a position. There isn't an existing API function to do what you're describing.

How to avoid warning when introducing NAs by coercion

Use suppressWarnings():

suppressWarnings(as.numeric(c("1", "2", "X")))
[1]  1  2 NA

This suppresses warnings.

laravel 5.3 new Auth::routes()

Auth::routes() is just a helper class that helps you generate all the routes required for user authentication. You can browse the code here https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/Router.php instead.

Here are the routes

// Authentication Routes...
$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');
$this->post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
$this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm');
$this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm');
$this->post('password/reset', 'Auth\ResetPasswordController@reset');

Return back to MainActivity from another activity

Here's why you saw the menu with the code you listed in your onClick method:

You were creating an Intent with the constructor that takes a string for the action parameter of the Intent's IntentFilter. You passed "android.intent.action.MAIN" as the argument to that constructor, which specifies that the Intent can be satisfied by any Activity with an IntentFilter including <action="android.intent.action.MAIN">.

When you called startActivity with that Intent, you effectively told the Android OS to go find an Activity (in any app installed on the system) that specifies the android.intent.action.MAIN action. When there are multiple Activities that qualify (and there are in this case since every app will have a main Activity with an IntentFilter including the "android.intent.action.MAIN" action), the OS presents a menu to let the user choose which app to use.

As to the question of how to get back to your main activity, as with most things, it depends on the specifics of your app. While the accepted answer probably worked in your case, I don't think it's the best solution, and it's probably encouraging you to use a non-idiomatic UI in your Android app. If your Button's onClick() method contains only a call to finish() then you should most likely remove the Button from the UI and just let the user push the hardware/software back button, which has the same functionality and is idiomatic for Android. (You'll often see back Buttons used to emulate the behavior of an iOS UINavigationController navigationBar which is discouraged in Android apps).

If your main activity launches a stack of Activities and you want to provide an easy way to get back to the main activity without repeatedly pressing the back button, then you want to call startActivity after setting the flag Intent.FLAG_ACTIVITY_CLEAR_TOP which will close all the Activities in the call stack which are above your main activity and bring your main activity to the top of the call stack. See below (assuming your main activity subclass is called MainActivity:

btnReturn1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent i=new Intent(this, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
    }
)};

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

How to convert An NSInteger to an int?

I'm not sure about the circumstances where you need to convert an NSInteger to an int.

NSInteger is just a typedef:

NSInteger Used to describe an integer independently of whether you are building for a 32-bit or a 64-bit system.

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 
typedef long NSInteger;
#else
typedef int NSInteger;
#endif

You can use NSInteger any place you use an int without converting it.

Including a .js file within a .js file

I basically do like this, create new element and attach that to <head>

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

You may also use onload event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.

x.onload=callback_function;

Error Installing Homebrew - Brew Command Not Found

You can run in terminal

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"

then install https://github.com/robbyrussell/oh-my-zsh.

When those complate run i.e pico editor pico .zshrc and past those lines:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

remember use brew doctor :)

enter image description here

Tips for debugging .htaccess rewrite rules

as pointed out by @JCastell, the online tester does a good job of testing individual redirects against an .htaccess file. However, more interesting is the api exposed which can be used to batch test a list of urls using a json object. However, to make it more useful, I have written a small bash script file which makes use of curl and jq to submit a list of urls and parse the json response into a CSV formated output with the line number and rule matched in the htaccess file along with the redirected url, making it quite handy to compare a list of urls in a spreadsheet and quickly determine which rules are not working.

How to have multiple colors in a Windows batch file?

If your console supports ANSI colour codes (e.g. ConEmu, Clink or ANSICON) you can do this:

SET    GRAY=%ESC%[0m
SET     RED=%ESC%[1;31m
SET   GREEN=%ESC%[1;32m
SET  ORANGE=%ESC%[0;33m
SET    BLUE=%ESC%[0;34m
SET MAGENTA=%ESC%[0;35m
SET    CYAN=%ESC%[1;36m
SET   WHITE=%ESC%[1;37m

where ESC variable contains ASCII character 27.

I found a way to populate the ESC variable here: http://www.dostips.com/forum/viewtopic.php?p=6827#p6827 and using tasklist it's possible to test what DLLs are loaded into a process.

The following script gets the process ID of the cmd.exe that the script is running in. Checks if it has a dll that will add ANSI support injected, and then sets colour variables to contain escape sequences or be empty depending on whether colour is supported or not.

@echo off

call :INIT_COLORS

echo %RED%RED %GREEN%GREEN %ORANGE%ORANGE %BLUE%BLUE %MAGENTA%MAGENTA %CYAN%CYAN %WHITE%WHITE %GRAY%GRAY

:: pause if double clicked on instead of run from command line.
SET interactive=0
ECHO %CMDCMDLINE% | FINDSTR /L %COMSPEC% >NUL 2>&1
IF %ERRORLEVEL% == 0 SET interactive=1
@rem ECHO %CMDCMDLINE% %COMSPEC% %interactive%
IF "%interactive%"=="1" PAUSE
EXIT /B 0
Goto :EOF

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
: SUBROUTINES                                                          :
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

::::::::::::::::::::::::::::::::
:INIT_COLORS
::::::::::::::::::::::::::::::::

call :supportsANSI
if ERRORLEVEL 1 (
  SET GREEN=
  SET RED=
  SET GRAY=
  SET WHITE=
  SET ORANGE=
  SET CYAN=
) ELSE (

  :: If you can, insert ASCII CHAR 27 after equals and remove BL.String.CreateDEL_ESC routine
  set "ESC="
  :: use this if can't type ESC CHAR, it's more verbose, but you can copy and paste it
  call :BL.String.CreateDEL_ESC

  SET    GRAY=%ESC%[0m
  SET     RED=%ESC%[1;31m
  SET   GREEN=%ESC%[1;32m
  SET  ORANGE=%ESC%[0;33m
  SET    BLUE=%ESC%[0;34m
  SET MAGENTA=%ESC%[0;35m
  SET    CYAN=%ESC%[1;36m
  SET   WHITE=%ESC%[1;37m
)

exit /b

::::::::::::::::::::::::::::::::
:BL.String.CreateDEL_ESC
::::::::::::::::::::::::::::::::
:: http://www.dostips.com/forum/viewtopic.php?t=1733
::
:: Creates two variables with one character DEL=Ascii-08 and ESC=Ascii-27
:: DEL and ESC can be used  with and without DelayedExpansion
setlocal
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  ENDLOCAL
  set "DEL=%%a"
  set "ESC=%%b"
  goto :EOF
)

::::::::::::::::::::::::::::::::
:supportsANSI
::::::::::::::::::::::::::::::::
:: returns ERRORLEVEL 0 - YES, 1 - NO
::
:: - Tests for ConEmu, ANSICON and Clink
:: - Returns 1 - NO support, when called via "CMD /D" (i.e. no autoruns / DLL injection)
::   on a system that would otherwise support ANSI.

if "%ConEmuANSI%" == "ON" exit /b 0

call :getPID PID

setlocal

for /f usebackq^ delims^=^"^ tokens^=^* %%a in (`tasklist /fi "PID eq %PID%" /m /fo CSV`) do set "MODULES=%%a"

set MODULES=%MODULES:"=%
set NON_ANSI_MODULES=%MODULES%

:: strip out ANSI dlls from module list:
:: ANSICON adds ANSI64.dll or ANSI32.dll
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ANSI=%"
:: ConEmu attaches ConEmuHk but ConEmu also sets ConEmuANSI Environment VAR
:: so we've already checked for that above and returned early.
@rem set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ConEmuHk=%"
:: Clink supports ANSI https://github.com/mridgers/clink/issues/54
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:clink_dll=%"

if "%MODULES%" == "%NON_ANSI_MODULES%" endlocal & exit /b 1
endlocal

exit /b 0

::::::::::::::::::::::::::::::::
:getPID  [RtnVar]
::::::::::::::::::::::::::::::::
:: REQUIREMENTS:
::
:: Determine the Process ID of the currently executing script,
:: but in a way that is multiple execution safe especially when the script can be executing multiple times
::   - at the exact same time in the same millisecond,
::   - by multiple users,
::   - in multiple window sessions (RDP),
::   - by privileged and non-privileged (e.g. Administrator) accounts,
::   - interactively or in the background.
::   - work when the cmd.exe window cannot appear
::     e.g. running from TaskScheduler as LOCAL SERVICE or using the "Run whether user is logged on or not" setting
::
:: https://social.msdn.microsoft.com/Forums/vstudio/en-US/270f0842-963d-4ed9-b27d-27957628004c/what-is-the-pid-of-the-current-cmdexe?forum=msbuild
::
:: http://serverfault.com/a/654029/306
::
:: Store the Process ID (PID) of the currently running script in environment variable RtnVar.
:: If called without any argument, then simply write the PID to stdout.
::
::
setlocal disableDelayedExpansion
:getLock
set "lock=%temp%\%~nx0.%time::=.%.lock"
set "uid=%lock:\=:b%"
set "uid=%uid:,=:c%"
set "uid=%uid:'=:q%"
set "uid=%uid:_=:u%"
setlocal enableDelayedExpansion
set "uid=!uid:%%=:p!"
endlocal & set "uid=%uid%"
2>nul ( 9>"%lock%" (
  for /f "skip=1" %%A in (
    'wmic process where "name='cmd.exe' and CommandLine like '%%<%uid%>%%'" get ParentProcessID'
  ) do for %%B in (%%A) do set "PID=%%B"
  (call )
))||goto :getLock
del "%lock%" 2>nul
endlocal & if "%~1" equ "" (echo(%PID%) else set "%~1=%PID%"
exit /b

How can one see content of stack with GDB?

info frame to show the stack frame info

To read the memory at given addresses you should take a look at x

x/x $esp for hex x/d $esp for signed x/u $esp for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip etc.

"commence before first target. Stop." error

This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.

Mysql adding user for remote access

for what DB is the user? look at this example

mysql> create database databasename;
Query OK, 1 row affected (0.00 sec)
mysql> grant all on databasename.* to cmsuser@localhost identified by 'password';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

so to return to you question the "%" operator means all computers in your network.

like aspesa shows I'm also sure that you have to create or update a user. look for all your mysql users:

SELECT user,password,host FROM user;

as soon as you got your user set up you should be able to connect like this:

mysql -h localhost -u gmeier -p

hope it helps

Call method in directive controller from other controller

You can also use events to trigger the Popdown.

Here's a fiddle based on satchmorun's solution. It dispenses with the PopdownAPI, and the top-level controller instead $broadcasts 'success' and 'error' events down the scope chain:

$scope.success = function(msg) { $scope.$broadcast('success', msg); };
$scope.error   = function(msg) { $scope.$broadcast('error', msg); };

The Popdown module then registers handler functions for these events, e.g:

$scope.$on('success', function(event, msg) {
    $scope.status = 'success';
    $scope.message = msg;
    $scope.toggleDisplay();
});

This works, at least, and seems to me to be a nicely decoupled solution. I'll let others chime in if this is considered poor practice for some reason.

When adding a Javascript library, Chrome complains about a missing source map, why?

In my case I had to remove React Dev Tools from Chrome to stop seeing the strange errors during development of React app using a local Express server with a create-react-app client (which uses Webpack). In the interest of community I did a sanity check and quit everything - server/client server/Chrome - and then I opened Chrome and reinstalled React Dev Tools... Started things back up and am seeing this funky address and error again: Error seems to be from React Dev Tools extension in my case

Remove Sub String by using Python

>>> import re
>>> st = " i think mabe 124 + <font color=\"black\"><font face=\"Times New Roman\">but I don't have a big experience it just how I see it in my eyes <font color=\"green\"><font face=\"Arial\">fun stuff"
>>> re.sub("<.*?>","",st)
" i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"
>>> 

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

Check if list contains element that contains a string and get that element

Many good answers here, but I use a simple one using Exists, as below:

foreach (var setting in FullList)
{
    if(cleanList.Exists(x => x.ProcedureName == setting.ProcedureName)) 
       setting.IsActive = true; // do you business logic here 
    else
       setting.IsActive = false;
    updateList.Add(setting);
}

Syntax for async arrow function

My async function

const getAllRedis = async (key) => {
  let obj = [];

  await client.hgetall(key, (err, object) => {
    console.log(object);
    _.map(object, (ob)=>{
      obj.push(JSON.parse(ob));
    })
    return obj;
    // res.send(obj);
});
}

Is calling destructor manually always a sign of bad design?

All answers describe specific cases, but there is a general answer:

You call the dtor explicitly every time you need to just destroy the object (in C++ sense) without releasing the memory the object resides in.

This typically happens in all the situation where memory allocation / deallocation is managed independently from object construction / destruction. In those cases construction happens via placement new upon an existent chunk of memory, and destruction happens via explicit dtor call.

Here is the raw example:

{
  char buffer[sizeof(MyClass)];

  {
     MyClass* p = new(buffer)MyClass;
     p->dosomething();
     p->~MyClass();
  }
  {
     MyClass* p = new(buffer)MyClass;
     p->dosomething();
     p->~MyClass();
  }

}

Another notable example is the default std::allocator when used by std::vector: elements are constructed in vector during push_back, but the memory is allocated in chunks, so it pre-exist the element contruction. And hence, vector::erase must destroy the elements, but not necessarily it deallocates the memory (especially if new push_back have to happen soon...).

It is "bad design" in strict OOP sense (you should manage objects, not memory: the fact objects require memory is an "incident"), it is "good design" in "low level programming", or in cases where memory is not taken from the "free store" the default operator new buys in.

It is bad design if it happens randomly around the code, it is good design if it happens locally to classes specifically designed for that purpose.

How to install trusted CA certificate on Android device?

Did you try: Settings -> Security -> Install from SD Card? – Alexander Egger Dec 20 '10 at 20:11

I'm not sure why is this not an answer already, but I just followed this advice and it worked.

Fast way to discover the row count of a table in PostgreSQL

For SQL Server (2005 or above) a quick and reliable method is:

SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('MyTableName')   
AND (index_id=0 or index_id=1);

Details about sys.dm_db_partition_stats are explained in MSDN

The query adds rows from all parts of a (possibly) partitioned table.

index_id=0 is an unordered table (Heap) and index_id=1 is an ordered table (clustered index)

Even faster (but unreliable) methods are detailed here.

Difference between matches() and find() in Java Regex

matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:

public static void main(String[] args) throws ParseException {
    Pattern p = Pattern.compile("\\d\\d\\d");
    Matcher m = p.matcher("a123b");
    System.out.println(m.find());
    System.out.println(m.matches());

    p = Pattern.compile("^\\d\\d\\d$");
    m = p.matcher("123");
    System.out.println(m.find());
    System.out.println(m.matches());
}

/* output:
true
false
true
true
*/

123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.

Find an element in a list of tuples

>>> [i for i in a if 1 in i]

[(1, 2), (1, 4)]

Run Command Prompt Commands

Though technically this doesn't directly answer question posed, it does answer the question of how to do what the original poster wanted to do: combine files. If anything, this is a post to help newbies understand what Instance Hunter and Konstantin are talking about.

This is the method I use to combine files (in this case a jpg and a zip). Note that I create a buffer that gets filled with the content of the zip file (in small chunks rather than in one big read operation), and then the buffer gets written to the back of the jpg file until the end of the zip file is reached:

private void CombineFiles(string jpgFileName, string zipFileName)
{
    using (Stream original = new FileStream(jpgFileName, FileMode.Append))
    {
        using (Stream extra = new FileStream(zipFileName, FileMode.Open, FileAccess.Read))
        {
            var buffer = new byte[32 * 1024];

            int blockSize;
            while ((blockSize = extra.Read(buffer, 0, buffer.Length)) > 0)
            {
                original.Write(buffer, 0, blockSize);
            }
        }
    }
}

How do I create a file and write to it?

Here's a little example program to create or overwrite a file. It's the long version so it can be understood more easily.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class writer {
    public void writing() {
        try {
            //Whatever the file path is.
            File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
            FileOutputStream is = new FileOutputStream(statText);
            OutputStreamWriter osw = new OutputStreamWriter(is);    
            Writer w = new BufferedWriter(osw);
            w.write("POTATO!!!");
            w.close();
        } catch (IOException e) {
            System.err.println("Problem writing to the file statsTest.txt");
        }
    }

    public static void main(String[]args) {
        writer write = new writer();
        write.writing();
    }
}

Converting List<String> to String[] in Java

String[] strarray = strlist.toArray(new String[0]);

if u want List convert to string use StringUtils.join(slist, '\n');

How to get the concrete class name as a string?

 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'

How does OkHttp get Json string?

I am also faced the same issue

use this code:

// notice string() call
String resStr = response.body().string();    
JSONObject json = new JSONObject(resStr);

it definitely works

AppSettings get value from .config file

Read From Config :

You'll need to add a reference to Config

  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"
  4. Get Value with using following code :
string value = Properties.Settings.Default.keyname;

Save to Config :

Properties.Settings.Default.keyName = value;
Properties.Settings.Default.Save();

How to suppress binary file matching results in grep

This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$

How to get input text value from inside td

var values = {};
$('td input').each(function(){
  values[$(this).attr('name')] = $(this).val();
}

Haven't tested, but that should do it...

ActiveX component can't create object

I had the same issue with Excel, I was trying to use a 32 COM DLL with an Excel 64 bits version and I got this error. I rebuild the COM dll to a 64 bits version and the error disappears. So be sure that your COM dll has the same architecture (x86 vs x64) than your application.

What would be the Unicode character for big bullet in the middle of the character?

You can use a span with 50% border radius.

_x000D_
_x000D_
 .mydot{_x000D_
     background: rgb(66, 183, 42);_x000D_
     border-radius: 50%;_x000D_
     display: inline-block;_x000D_
     height: 20px;_x000D_
     margin-left: 4px;_x000D_
     margin-right: 4px;_x000D_
     width: 20px;_x000D_
}    
_x000D_
<span class="mydot"></span>
_x000D_
_x000D_
_x000D_

Check if value exists in Postgres array

"Any" works well. Just make sure that the any keyword is on the right side of the equal to sign i.e. is present after the equal to sign.

Below statement will throw error: ERROR: syntax error at or near "any"

select 1 where any('{hello}'::text[]) = 'hello';

Whereas below example works fine

select 1 where 'hello' = any('{hello}'::text[]);

How do I sort a list of dictionaries by a value of the dictionary?

Here is the alternative general solution - it sorts elements of a dict by keys and values.

The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.

def sort_key_func(item):
    """ Helper function used to sort list of dicts

    :param item: dict
    :return: sorted list of tuples (k, v)
    """
    pairs = []
    for k, v in item.items():
        pairs.append((k, v))
    return sorted(pairs)
sorted(A, key=sort_key_func)

3-dimensional array in numpy

No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".

x = np.zeros((2,3,4)) 

Simply Means:

2 Sets, 3 Rows per Set, 4 Columns

Example:

Input

x = np.zeros((2,3,4))

Output

Set # 1 ---- [[[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]], ---- Row 3 
    
Set # 2 ----  [[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]]] ---- Row 3

Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.

Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".

Set Response Status Code

Since PHP 5.4 you can use http_response_code.

http_response_code(404);

This will take care of setting the proper HTTP headers.

If you are running PHP < 5.4 then you have two options:

  1. Upgrade.
  2. Use this http_response_code function implemented in PHP.

Create a global variable in TypeScript

im using only this

import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;

Python: For each list element apply a function across the list

If you don't mind importing the numpy package, it has a lot of convenient functionality built in. It's likely to be much more efficient to use their data structures than lists of lists, etc.

from __future__ import division

import numpy

data = numpy.asarray([1,2,3,4,5])
dists = data.reshape((1,5)) / data.reshape((5,1))

print dists

which = dists.argmin()
(r,c) = (which // 5, which % 5) # assumes C ordering

# pick whichever is most appropriate for you...
minval = dists[r,c]
minval = dists.min()
minval = dists.ravel()[which]

How to use find command to find all files with extensions from list?

find /path/to/  \( -iname '*.gif' -o -iname '*.jpg' \) -print0

will work. There might be a more elegant way.

ClientScript.RegisterClientScriptBlock?

The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.

Instead use the .NET 2.0 Page.ClientScript.Register* methods. - (The ClientScript property expresses an instance of the ClientScriptManager class )

Guessing the problem

If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.

Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.

An invalid XML character (Unicode: 0xc) was found

The character 0x0C is be invalid in XML 1.0 but would be a valid character in XML 1.1. So unless the xml file specifies the version as 1.1 in the prolog it is simply invalid and you should complain to the producer of this file.

How to set a Fragment tag by code?

You can add the tag as a property for the Fragment arguments. It will be automatically restored if the fragment is destroyed and then recreated by the OS.

Example:-

    final Bundle args = new Bundle();
    args.putString("TAG", "my tag");
    fragment.setArguments(args);

How to toggle font awesome icon on click?

Simply call jQuery's toggleClass() on the i element contained within your a element(s) to toggle either the plus and minus icons:

...click(function() {
    $(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});

Note that this assumes that a class of fa-plus-circle is added to your i element by default.

JSFiddle demo.

Git: How do I list only local branches?

git branch -a - All branches.

git branch -r - Remote branches only.

git branch -l or git branch - Local branches only.

Regex to match only uppercase "words" with some exceptions

Maybe you can run this regex first to see if the line is all caps:

^[A-Z \d\W]+$

That will match only if it's a line like THING P1 MUST CONNECT TO X2.

Otherwise, you should be able to pull out the individual uppercase phrases with this:

[A-Z][A-Z\d]+

That should match "P1" and "J236" in The thing P1 must connect to the J236 thing in the Foo position.

Overlapping elements in CSS

I think you could get away with using relative positioning and then set the top/left positioning of the second DIV until you have it in the position desired.

Visual Studio 2017: Display method references

In previous posts I have read that this feature IS available on VS 2015 community if you FIRST install SQL Server express (free) and THEN install VS. I have tried it and it worked. I just had to reinstall Windows and am going thru the same procedure now and it did not work... so will try again :). I know it worked 6 months ago when I tried.

-Ed

What's a good IDE for Python on Mac OS X?

If you have a budget for your IDE, you should give Wingware Professional a try, see wingware.com .

Auto code completion on Eclipse

Yes. If the suggestion doesn't compare automatically, then press crtl + space button.

Create request with POST, which response codes 200 or 201 and content

I think atompub REST API is a great example of a restful service. See the snippet below from the atompub spec:

POST /edit/ HTTP/1.1
Host: example.org
User-Agent: Thingio/1.0
Authorization: Basic ZGFmZnk6c2VjZXJldA==
Content-Type: application/atom+xml;type=entry
Content-Length: nnn
Slug: First Post

<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title>Atom-Powered Robots Run Amok</title>
  <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
  <updated>2003-12-13T18:30:02Z</updated>
  <author><name>John Doe</name></author>
  <content>Some text.</content>
</entry>

The server signals a successful creation with a status code of 201. The response includes a Location header indicating the Member Entry URI of the Atom Entry, and a representation of that Entry in the body of the response.

HTTP/1.1 201 Created
Date: Fri, 7 Oct 2005 17:17:11 GMT
Content-Length: nnn
Content-Type: application/atom+xml;type=entry;charset="utf-8"
Location: http://example.org/edit/first-post.atom
ETag: "c180de84f991g8"  

<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title>Atom-Powered Robots Run Amok</title>
  <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
  <updated>2003-12-13T18:30:02Z</updated>
  <author><name>John Doe</name></author>
  <content>Some text.</content>
  <link rel="edit"
      href="http://example.org/edit/first-post.atom"/>
</entry>

The Entry created and returned by the Collection might not match the Entry POSTed by the client. A server MAY change the values of various elements in the Entry, such as the atom:id, atom:updated, and atom:author values, and MAY choose to remove or add other elements and attributes, or change element content and attribute values.

What is a segmentation fault?

Segmentation fault occurs when a process (running instance of a program) is trying to access read-only memory address or memory range which is being used by other process or access the non-existent (invalid) memory address. Dangling Reference (pointer) problem means that trying to access an object or variable whose contents have already been deleted from memory, e.g:

int *arr = new int[20];
delete arr;
cout<<arr[1];  //dangling problem occurs here

Check table exist or not before create it in Oracle

Well there are lot of answeres already provided and lot are making sense too.

Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.

I came across similar situation today and here is very simple query I came up with...

declare
begin
  execute immediate '
    create table "TBL" ("ID" number not null)';
  exception when others then
    if SQLCODE = -955 then null; else raise; end if;
end;
/

955 is failure code.

This is simple, if exception come while running query it will be suppressed. and you can use same for SQL or Oracle.

how to remove pagination in datatable

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

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

How to debug an apache virtual host configuration?

I had a new VirtualHost configuration file that was not showing when using the apachectl -S command. After much head scratching I realised that my file did not have suffix ".conf". Once I renamed the file with that suffix my Vhost started showing and working!

Fixing Sublime Text 2 line endings?

The simplest way to modify all files of a project at once (batch) is through Line Endings Unify package:

  1. Ctrl+Shift+P type inst + choose Install Package.
  2. Type line end + choose Line Endings Unify.
  3. Once installed, Ctrl+Shift+P + type end + choose Line Endings Unify.
  4. OR (instead of 3.) copy:

    {
     "keys": ["ctrl+alt+l"],
     "command": "line_endings_unify"
    },
    

    to the User array (right pane, after the opening [) in Preferences -> KeyBindings + press Ctrl+Alt+L.

As mentioned in another answer:

  • The Carriage Return (CR) character (0x0D, \r) [...] Early Macintosh operating systems (OS-9 and earlier).

  • The Line Feed (LF) character (0x0A, \n) [...] UNIX based systems (Linux, Mac OSX)

  • The End of Line (EOL) sequence (0x0D 0x0A, \r\n) [...] (non-Unix: Windows, Symbian OS).

If you have node_modules, build or other auto-generated folders, delete them before running the package.

When you run the package:

  1. you are asked at the bottom to choose which file extensions to search through a comma separated list (type the only ones you need to speed up the replacements, e.g. js,jsx).
  2. then you are asked which Input line ending to use, e.g. if you need LF type \n.
  3. press ENTER and wait until you see an alert window with LineEndingsUnify Complete.

Java error: Only a type can be imported. XYZ resolves to a package

If you are using Maven and packaging your Java classes as JAR, then make sure that JAR is up to date. Still assuming that JAR is in your classpath of course.

Adding new column to existing DataFrame in Python pandas

Easiest ways:-

data['new_col'] = list_of_values

data.loc[ : , 'new_col'] = list_of_values

This way you avoid what is called chained indexing when setting new values in a pandas object. Click here to read further.

How to escape JSON string?

There's a Json library at Codeplex

How to kill a running SELECT statement

Oh! just read comments in question, dear I missed it. but just letting the answer be here in case it can be useful to some other person

I tried "Ctrl+C" and "Ctrl+ Break" none worked. I was using SQL Plus that came with Oracle Client 10.2.0.1.0. SQL Plus is used by most as client for connecting with Oracle DB. I used the Cancel, option under File menu and it stopped the execution!

File Menu, Oracle SQL*Plus

Once you click File wait for few mins then the select command halts and menu appears click on Cancel.

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

What is the simplest way to get indented XML with line breaks from XmlDocument?

XmlTextWriter xw = new XmlTextWriter(writer);
xw.Formatting = Formatting.Indented;

Iterating over Typescript Map

I'm using latest TS and node (v2.6 and v8.9 respectively) and I can do:

let myMap = new Map<string, boolean>();
myMap.set("a", true);
for (let [k, v] of myMap) {
    console.log(k + "=" + v);
}

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

How to display JavaScript variables in a HTML page without document.write

Add an element to your page (such as a div) and write to that div.

HTML:

<html>
    <header>
        <title>Page Title</title>
    </header>

    <body>
        <div id="myDiv"></div>
    </body>
</html>

jQuery:

$('#myDiv').text('hello world!');

javascript:

document.getElementById('myDiv').innerHTML = 'hello world!';

What does MissingManifestResourceException mean and how to fix it?

I had the same problem, but using the Run Custom Tool command as suggested by Timwi did not help in my case.

However it lead me into the right direction, because I ended up in the Properties of the .resx file. Here I noticed a difference to another .resx file that caused no problems.

In my case I had to change the property "Build Action" from "Resource" to "Embedded Resource".

My best guess for the reason is, that I had the .resx in a library that was used from another application. My application did not have its own .resx file, so it had to use the one from the library - which is only available when it's embedded in the library and not "stand alone".

Using Mockito to mock classes with generic parameters

I agree that one shouldn't suppress warnings in classes or methods as one could overlook other, accidentally suppressed warnings. But IMHO it's absolutely reasonable to suppress a warning that affects only a single line of code.

@SuppressWarnings("unchecked")
Foo<Bar> mockFoo = mock(Foo.class);

Can an AJAX response set a cookie?

Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

Options for HTML scraping?

The Python lxml library acts as a Pythonic binding for the libxml2 and libxslt libraries. I like particularly its XPath support and pretty-printing of the in-memory XML structure. It also supports parsing broken HTML. And I don't think you can find other Python libraries/bindings that parse XML faster than lxml.

How to check if a line is blank using regex

The pattern you want is something like this in multiline mode:

^\s*$

Explanation:

  • ^ is the beginning of string anchor.
  • $ is the end of string anchor.
  • \s is the whitespace character class.
  • * is zero-or-more repetition of.

In multiline mode, ^ and $ also match the beginning and end of the line.

References:


A non-regex alternative:

You can also check if a given string line is "blank" (i.e. containing only whitespaces) by trim()-ing it, then checking if the resulting string isEmpty().

In Java, this would be something like this:

if (line.trim().isEmpty()) {
    // line is "blank"
}

The regex solution can also be simplified without anchors (because of how matches is defined in Java) as follows:

if (line.matches("\\s*")) {
    // line is "blank"
}

API references

How can I change UIButton title color?

You can use -[UIButton setTitleColor:forState:] to do this.

Example:

Objective-C

[buttonName setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

Swift 2

buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)

Swift 3

buttonName.setTitleColor(UIColor.white, for: .normal)

Thanks to richardchildan

How to completely uninstall Android Studio on Mac?

Execute these commands in the terminal (excluding the lines with hashtags - they're comments):

# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*

If you would like to delete all projects:

rm -Rf ~/AndroidStudioProjects

To remove gradle related files (caches & wrapper)

rm -Rf ~/.gradle

Use the below command to delete all Android Virtual Devices(AVDs) and keystores.

Note: This folder is used by other Android IDEs as well, so if you still using other IDE you may not want to delete this folder)

rm -Rf ~/.android

To delete Android SDK tools

rm -Rf ~/Library/Android*

Emulator Console Auth Token

rm -Rf ~/.emulator_console_auth_token

Thanks to those who commented/improved on this answer!


Notes

  1. The flags for rm are case-sensitive1 (as with most other commands), which means that the f flag must be in lower case. However, the r flag can also be capitalised.
  2. The flags for rm can be either combined together or separated. They don't have to be combined.

What the flags indicate

  1. The r flag indicates that the rm command should-

    attempt to remove the file hierarchy rooted in each file argument. - DESCRIPTION section on the manpage for rm (See man rm for more info)

  2. The f flag indicates that the rm command should-

    attempt to remove the files without prompting for confirmation, regardless of the file's permissions. - DESCRIPTION section on the manpage for rm (See man rm for more info)

How to emit an event from parent to child?

Use the @Input() decorator in your child component to allow the parent to bind to this input.

In the child component you declare it as is :

@Input() myInputName: myType

To bind a property from parent to a child you must add in you template the binding brackets and the name of your input between them.

Example :

<my-child-component [myChildInputName]="myParentVar"></my-child-component>

But beware, objects are passed as a reference, so if the object is updated in the child the parent's var will be too updated. This might lead to some unwanted behaviour sometime. With primary types the value is copied.

To go further read this :

Docs : https://angular.io/docs/ts/latest/cookbook/component-communication.html

Using Composer's Autoload

In my opinion, Sergiy's answer should be the selected answer for the given question. I'm sharing my understanding.

I was looking to autoload my package files using composer which I have under the dir structure given below.

<web-root>
    |--------src/
    |           |--------App/
    |           |
    |           |--------Test/
    |
    |---------library/
    |
    |---------vendor/
    |           |
    |           |---------composer/
    |           |           |---------autoload_psr4.php
    |           |           
    |           |----------autoload.php
    |
    |-----------composer.json
    |

I'm using psr-4 autoloading specification.

Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.

"autoload": {
        "psr-4": {
            "OrgName\\AppType\\AppName\\": ["src/App", "src/Test", "library/"]
        }
    } 

This is pretty much self explaining. OrgName\AppType\AppName is my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php -

namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration

use OrgName\AppType\AppName\Controller\Provider\User; // when using the class

Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php

Now if composer is installed properly all that is required is #composer update

After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'OrgName\\AppType\\AppName\\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
);

This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php

Differences between JDK and Java SDK

The JDK (Java Development Kit) is an SDK (Software Dev Kit).

It is used to build software/applications on Java and of course it includes the JRE (Java Runtime Edition) to execute that software. If you just want to execute a Java application, download only the JRE.

By the way, Java EE (Enterprise Edition) contains libraries of packages of classes "with methods (functions)" to build apps for the WEB environment and Java ME (Micro Edition) for mobile devices. If you are interested in it (Java ME) I would recommend to take a look at Google's Android DevKit and API.

Take a look here: it's gonna explain bit more.. http://www.oracle.com/technetwork/java/archive-139210.html

Creating a Jenkins environment variable using Groovy

For me the following worked on Jenkins 2.190.1 and was much simpler than some of the other workarounds:

matcher = manager.getLogMatcher('^.*Text we want comes next: (.*)$');

if (matcher.matches()) {
    def myVar = matcher.group(1);
    def envVar = new EnvVars([MY_ENV_VAR: myVar]);
    def newEnv = Environment.create(envVar);
    manager.build.environments.add(0, newEnv);
    // now the matched text from the LogMatcher is passed to an
    // env var we can access at $MY_ENV_VAR in post build steps
}

This was using the Groovy Script plugin with no additional changes to Jenkins.

How to fire an event when v-model changes?

You should use @input:

<input @input="handleInput" />

@input fires when user changes input value.

@change fires when user changed value and unfocus input (for example clicked somewhere outside)

You can see the difference here: https://jsfiddle.net/posva/oqe9e8pb/

How to create an array of 20 random bytes?

Try the Random.nextBytes method:

byte[] b = new byte[20];
new Random().nextBytes(b);

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

You can directly set the content type like below:

res.writeHead(200, {'Content-Type': 'text/plain'});

For reference go through the nodejs Docs link.

What are some great online database modeling tools?

I've used DBDesigner before. It is an open source tool. You might check that out. Not sure if it fits your needs.

Best of luck!

Is there a foreach loop in Go?

This may be obvious, but you can inline the array like so:

package main

import (
    "fmt"
)

func main() {
    for _, element := range [3]string{"a", "b", "c"} {
        fmt.Print(element)
    }
}

outputs:

abc

https://play.golang.org/p/gkKgF3y5nmt

Django request get parameters

You can use [] to extract values from a QueryDict object like you would any ordinary dictionary.

# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]

# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]

# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]

How to format DateTime in Flutter , How to get current time in flutter?

Here's my simple solution. That does not require any dependency.

However, the date will be in string format. If you want the time then change the substring values

print(new DateTime.now()
            .toString()
            .substring(0,10)
     );   // 2020-06-10

R solve:system is exactly singular

I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.

Most efficient way to find mode in numpy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1, also to validate if it is actually representative of the central distribution of your data you may check whether it falls inside your standard deviation interval.

Make an HTTP request with android

UPDATE

This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:

Original Answer

First of all, request a permission to access network, add following to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

Then the easiest way is to use Apache http client bundled with Android:

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        String responseString = out.toString();
        out.close();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }

If you want it to run on separate thread I'd recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

You then can make a request by:

   new RequestTask().execute("http://stackoverflow.com");

How can I get the full/absolute URL (with domain) in Django?

To create a complete link to another page from a template, you can use this:

{{ request.META.HTTP_HOST }}{% url 'views.my_view' my_arg %}

request.META.HTTP_HOST gives the host name, and url gives the relative name. The template engine then concatenates them into a complete url.

How to export settings?

With the current version of Visual Studio Code as of this writing (1.22.1), you can find your settings in

  • ~/.config/Code/User on Linux (in my case, an, Ubuntu derivative)
  • C:\Users\username\AppData\Roaming\Code\User on Windows 10
  • ~/Library/Application Support/Code/User/ on Mac OS X (thank you, Christophe De Troyer)

The files are settings.json and keybindings.json. Simply copy them to the target machine.

Your extensions are in

  • ~/.vscode/extensions on Linux and Mac OS X
  • C:\Users\username\.vscode\extensions on Windows 10 (e.g., essentially the same place)

Alternately, just go to the Extensions, show installed extensions, and install those on your target installation. For me, copying the extensions worked just fine, but it may be extension-specific, particularly if moving between platforms, depending on what the extension does.

How to set default Checked in checkbox ReactJS?

<div className="display__lbl_input">
              <input
                type="checkbox"
                onChange={this.handleChangeFilGasoil}
                value="Filter Gasoil"
                name="Filter Gasoil"
                id=""
              />
              <label htmlFor="">Filter Gasoil</label>
            </div>

handleChangeFilGasoil = (e) => {
    if(e.target.checked){
        this.setState({
            checkedBoxFG:e.target.value
        })
        console.log(this.state.checkedBoxFG)
    }
    else{
     this.setState({
        checkedBoxFG : ''
     })
     console.log(this.state.checkedBoxFG)
    }
  };

What is trunk, branch and tag in Subversion?

A good book on Subversion is Pragmatic Version Control using Subversion where your question is explained, and it gives a lot more information.

Configure Flask dev server to be visible across the network

You can also set the host (to expose it on a network facing IP address) and port via environment variables.

$ export FLASK_APP=app.py
$ export FLASK_ENV=development
$ export FLASK_RUN_PORT=8000
$ export FLASK_RUN_HOST=0.0.0.0

$ flask run
 * Serving Flask app "app.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on https://0.0.0.0:8000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 329-665-000

See How to get all available Command Options to set environment variables?

AngularJS ng-if with multiple conditions

OR operator:

<div ng-repeat="k in items">
    <div ng-if="k || 'a' or k == 'b'">
        <!-- SOME CONTENT -->
    </div>
</div>

Even though it is simple enough to read, I hope as a developer you are use better names than 'a' 'k' 'b' etc..

For Example:

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin || group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

Another OR example

<p ng-if="group.title != 'Dispatcher News' or group.title != 'Coordinator News'" style="padding: 5px;">No links in group.</p>

AND operator (For those stumbling across this stackoverflow answer looking for an AND instead of OR condition)

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin && group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

This error message

error: (-215)size.width>0 && size.height>0 in function imshow

simply means that imshow() is not getting video frame from input-device. You can try using

cap = cv2.VideoCapture(1) 

instead of

cap = cv2.VideoCapture(0) 

& see if the problem still persists.

Why do people write #!/usr/bin/env python on the first line of a Python script?

Considering the portability issues between python2 and python3, you should always specify either version unless your program is compatible with both.

Some distributions are shipping python symlinked to python3 for a while now - do not rely on python being python2.

This is emphasized by PEP 394:

In order to tolerate differences across platforms, all new code that needs to invoke the Python interpreter should not specify python, but rather should specify either python2 or python3 (or the more specific python2.x and python3.x versions; see the Migration Notes). This distinction should be made in shebangs, when invoking from a shell script, when invoking via the system() call, or when invoking in any other context.

How do I do a HTTP GET in Java?

If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.

An example looks like this:

String urlString = "http://wherever.com/someAction?param1=value1&param2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream

How to add text inside the doughnut chart using Chart.js?

You have to modify the code like: in chart.Doughnut.defaults

labelFontFamily : "Arial",
labelFontStyle : "normal",
labelFontSize : 24,
labelFontColor : "#666"

and then in function drawPieSegments

ctx.fillText(data[0].value + "%", width/2 - 20, width/2, 200);

See this pull: https://github.com/nnnick/Chart.js/pull/35

here is a fiddle http://jsfiddle.net/mayankcpdixit/6xV78/ implementing the same.

Getting started with OpenCV 2.4 and MinGW on Windows 7

On Windows 64bits it´s works:

  1. Download opencv-3.0 (beta), MinGW (command line tool);
  2. Add above respective bin folder to PATH var;
  3. Create an folder "release" (could be any name) into ;
  4. Into created folder, open prompt terminal and exec the below commands;
  5. Copy and Past this command

    cmake -G "MinGW Makefiles" -D CMAKE_CXX_COMPILER=mingw32-g++.exe -D WITH_IPP=OFF MAKE_MAKE_PROGRAM=mingw32-make.exe ..\

  6. Execute this command mingw32-make

  7. Execute this command mingw32-make install

DONE

Take a full page screenshot with Firefox on the command-line

Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.

To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.


(source: mozilla.net)

indexOf Case Sensitive?

Here's a version closely resembling Apache's StringUtils version:

public int indexOfIgnoreCase(String str, String searchStr) {
    return indexOfIgnoreCase(str, searchStr, 0);
}

public int indexOfIgnoreCase(String str, String searchStr, int fromIndex) {
    // https://stackoverflow.com/questions/14018478/string-contains-ignore-case/14018511
    if(str == null || searchStr == null) return -1;
    if (searchStr.length() == 0) return fromIndex;  // empty string found; use same behavior as Apache StringUtils
    final int endLimit = str.length() - searchStr.length() + 1;
    for (int i = fromIndex; i < endLimit; i++) {
        if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) return i;
    }
    return -1;
}

How do I get the HTML code of a web page in PHP?

You may want to check out the YQL libraries from Yahoo: http://developer.yahoo.com/yql

The task at hand is as simple as

select * from html where url = 'http://stackoverflow.com/questions/ask'

You can try this out in the console at: http://developer.yahoo.com/yql/console (requires login)

Also see Chris Heilmanns screencast for some nice ideas what more you can do: http://developer.yahoo.net/blogs/theater/archives/2009/04/screencast_collating_distributed_information.html

Open a new tab in the background?

THX for this question! Works good for me on all popular browsers:

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = window.location.pathname;
    var evt = document.createEvent("MouseEvents");
    //the tenth parameter of initMouseEvent sets ctrl key
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
    var url = window.location.pathname;
    var win = window.open(url, '_blank');
} else {
    openNewBackgroundTab();
}

MySQL JOIN ON vs USING?

It is mostly syntactic sugar, but a couple differences are noteworthy:

ON is the more general of the two. One can join tables ON a column, a set of columns and even a condition. For example:

SELECT * FROM world.City JOIN world.Country ON (City.CountryCode = Country.Code) WHERE ...

USING is useful when both tables share a column of the exact same name on which they join. In this case, one may say:

SELECT ... FROM film JOIN film_actor USING (film_id) WHERE ...

An additional nice treat is that one does not need to fully qualify the joining columns:

SELECT film.title, film_id -- film_id is not prefixed
FROM film
JOIN film_actor USING (film_id)
WHERE ...

To illustrate, to do the above with ON, we would have to write:

SELECT film.title, film.film_id -- film.film_id is required here
FROM film
JOIN film_actor ON (film.film_id = film_actor.film_id)
WHERE ...

Notice the film.film_id qualification in the SELECT clause. It would be invalid to just say film_id since that would make for an ambiguity:

ERROR 1052 (23000): Column 'film_id' in field list is ambiguous

As for select *, the joining column appears in the result set twice with ON while it appears only once with USING:

mysql> create table t(i int);insert t select 1;create table t2 select*from t;
Query OK, 0 rows affected (0.11 sec)

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

Query OK, 1 row affected (0.19 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select*from t join t2 on t.i=t2.i;
+------+------+
| i    | i    |
+------+------+
|    1 |    1 |
+------+------+
1 row in set (0.00 sec)

mysql> select*from t join t2 using(i);
+------+
| i    |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

mysql>

Get line number while using grep

grep -A20 -B20 pattern file.txt

Search pattern and show 20 lines after and before pattern

How to create a self-signed certificate with OpenSSL

As of 2021, the following command serves all your needs, including SAN:

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout example.key -out example.crt -extensions san -config \
  <(echo "[req]"; 
    echo distinguished_name=req; 
    echo "[san]"; 
    echo subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1
    ) \
  -subj "/CN=example.com"

In OpenSSL = 1.1.1, this can be shortened to:

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout example.key -out example.crt -subj "/CN=example.com" \
  -addext "subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1"

It creates a certificate that is

  • valid for the (sub)domains example.com and www.example.net (SAN),
  • also valid for the IP address 10.0.0.1 (SAN),
  • relatively strong (as of 2021) and
  • valid for 3650 days (~10 years).

It creates the following files:

  • Private key: example.key
  • Certificate: example.crt

All information is provided at the command line. There is no interactive input that annoys you. There are no config files you have to mess around with. All necessary steps are executed by a single OpenSSL invocation: from private key generation up to the self-signed certificate.

Remark #1: Crypto parameters

Since the certificate is self-signed and needs to be accepted by users manually, it doesn't make sense to use a short expiration or weak cryptography.

In the future, you might want to use more than 4096 bits for the RSA key and a hash algorithm stronger than sha256, but as of 2021 these are sane values. They are sufficiently strong while being supported by all modern browsers.

Remark #2: Parameter "-nodes"

Theoretically you could leave out the -nodes parameter (which means "no DES encryption"), in which case example.key would be encrypted with a password. However, this is almost never useful for a server installation, because you would either have to store the password on the server as well, or you'd have to enter it manually on each reboot.

Remark #3: See also

Google Maps API v3 marker with label

the above solutions wont work on ipad-2

recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)

HTML Canvas Full Screen

If you want to show it in a presentation then consider using requestFullscreen() method

let canvas = document.getElementById("canvas_id");
canvas.requestFullscreen();

that should make it fullscreen whatever the current circumstances are.

also check the support table https://caniuse.com/?search=requestFullscreen

Set the layout weight of a TextView programmatically

In the earlier answers weight is passed to the constructor of a new SomeLayoutType.LayoutParams object. Still in many cases it's more convenient to use existing objects - it helps to avoid dealing with parameters we are not interested in.

An example:

// Get our View (TextView or anything) object:
View v = findViewById(R.id.our_view); 

// Get params:
LinearLayout.LayoutParams loparams = (LinearLayout.LayoutParams) v.getLayoutParams();

// Set only target params:
loparams.height = 0;
loparams.weight = 1;
v.setLayoutParams(loparams);

CSS: Center block, but align contents to the left

<div>
    <div style="text-align: left; width: 400px; border: 1px solid black; margin: 0 auto;">
         <pre>
Hello
Testing
Beep
         </pre>
    </div>
</div>

T-SQL and the WHERE LIKE %Parameter% clause

you may try this one, used CONCAT

WHERE LastName LIKE Concat('%',@LastName,'%')

Java, How to specify absolute value and square roots

Use the java.lang.Math class, and specifically for absolute value and square root:, the abs() and sqrt() methods.

How to convert int to float in python?

In Python 3 this is the default behavior, but if you aren't using that you can import division like so:

>>> from __future__ import division
>>> 144/314
0.4585987261146497

Alternatively you can cast one of the variables to a float when doing your division which will do the same thing

sum = 144
women_onboard = 314
proportion_womenclass3_survived = sum / float(np.size(women_onboard))

Get folder name of the file in Python

You could get the full path as a string then split it into a list using your operating system's separator character. Then you get the program name, folder name etc by accessing the elements from the end of the list using negative indices.

Like this:

import os
strPath = os.path.realpath(__file__)
print( f"Full Path    :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( "List of Folders:", nmFolders )
print( f"Program Name :{nmFolders[-1]}" )
print( f"Folder Name  :{nmFolders[-2]}" )
print( f"Folder Parent:{nmFolders[-3]}" )

The output of the above was this:

Full Path    :C:\Users\terry\Documents\apps\environments\dev\app_02\app_02.py
List of Folders: ['C:', 'Users', 'terry', 'Documents', 'apps', 'environments', 'dev', 'app_02', 'app_02.py']
Program Name :app_02.py
Folder Name  :app_02
Folder Parent:dev

Match exact string

"^" For the begining of the line "$" for the end of it. Eg.:

var re = /^abc$/;

Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

How to save and load cookies using Python + Selenium WebDriver

Just a slight modification for the code written by Roel Van de Paar, as all credit goes to him. I am using this in Windows and it is working perfectly, both for setting and adding cookies:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('chromedriver.exe',options=chrome_options)
driver.get('https://web.whatsapp.com')  # Already authenticated
time.sleep(30)

Excel VBA App stops spontaneously with message "Code execution has been halted"

One solution is here:

The solution for this problem is to add the line of code “Application.EnableCancelKey = xlDisabled” in the first line of your macro.. This will fix the problem and you will be able to execute the macro successfully without getting the error message “Code execution has been interrupted”.

But, after I inserted this line of code, I was not able to use Ctrl+Break any more. So it works but not greatly.

Why not use tables for layout in HTML?

Here's a section of html from a recent project:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>{DYNAMIC(TITLE)}</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <link rel="stylesheet" type="text/css" href="./styles/base.css" />
</head>
<body>
    <div id="header">
        <h1><!-- Page title --></h1>
        <ol id="navigation">
            <!-- Navigation items -->
        </ol>
        <div class="clearfix"></div>
    </div>
    <div id="sidebar">
        <!-- Sidebar content -->
    </div>
    <!-- Page content -->
    <p id="footer"><!-- Footer content --></p>
</body>
</html>

And here's that same code as a table based layout.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>{DYNAMIC(TITLE)}</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <link rel="stylesheet" type="text/css" href="./styles/base.css" />
</head>
<body>
    <table cellspacing="0">
        <tr>
            <td><!-- Page Title --></td>
            <td>
                <table>
                    <tr>
                        <td>Navitem</td>
                        <td>Navitem</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>

    <table>
        <tr>
            <td><!-- Page content --></td>
            <td><!-- Sidebar content --></td>
        </tr>
        <tr>
            <td colspan="2">Footer</td>
        </tr>
    </table>
</body>
</html>

The only cleanliness I see in that table based layout is the fact that I'm overzealous with my indentation. I'm sure that the content section would have a further two embedded tables.

Another thing to think about: filesizes. I've found that table-based layouts are twice the size of their CSS counterparts usually. On our hig-speed broadband that isn't a huge issue but it is on those with dial up modems.

How to find out what type of a Mat object is with Mat::type() in OpenCV

This was answered by a few others but I found a solution that worked really well for me.

System.out.println(CvType.typeToString(yourMat.type()));

How do I do pagination in ASP.NET MVC?

public ActionResult Paging(int? pageno,bool? fwd,bool? bwd)        
{
    if(pageno!=null)
     {
       Session["currentpage"] = pageno;
     }

    using (HatronEntities DB = new HatronEntities())
    {
        if(fwd!=null && (bool)fwd)
        {
            pageno = Convert.ToInt32(Session["currentpage"]) + 1;
            Session["currentpage"] = pageno;
        }
        if (bwd != null && (bool)bwd)
        {
            pageno = Convert.ToInt32(Session["currentpage"]) - 1;
            Session["currentpage"] = pageno;
        }
        if (pageno==null)
        {
            pageno = 1;
        }
        if(pageno<0)
        {
            pageno = 1;
        }
        int total = DB.EmployeePromotion(0, 0, 0).Count();
        int  totalPage = (int)Math.Ceiling((double)total / 20);
        ViewBag.pages = totalPage;
        if (pageno > totalPage)
        {
            pageno = totalPage;
        }
        return View (DB.EmployeePromotion(0,0,0).Skip(GetSkip((int)pageno,20)).Take(20).ToList());     
    }
}

private static int GetSkip(int pageIndex, int take)
{
    return (pageIndex - 1) * take;
}

@model IEnumerable<EmployeePromotion_Result>
@{
  Layout = null;
}

 <!DOCTYPE html>

 <html>
 <head>
    <meta name="viewport" content="width=device-width" />
    <title>Paging</title>
  </head>
  <body>
 <div> 
    <table border="1">
        @foreach (var itm in Model)
        {
 <tr>
   <td>@itm.District</td>
   <td>@itm.employee</td>
   <td>@itm.PromotionTo</td>
 </tr>
        }
    </table>
    <a href="@Url.Action("Paging", "Home",new { pageno=1 })">First  page</a> 
    <a href="@Url.Action("Paging", "Home", new { bwd =true })"><<</a> 
    @for(int itmp =1; itmp< Convert.ToInt32(ViewBag.pages)+1;itmp++)
   {
       <a href="@Url.Action("Paging", "Home",new { pageno=itmp   })">@itmp.ToString()</a>
   }
    <a href="@Url.Action("Paging", "Home", new { fwd = true })">>></a> 
    <a href="@Url.Action("Paging", "Home", new { pageno =                                                                               Convert.ToInt32(ViewBag.pages) })">Last page</a> 
</div>
   </body>
  </html>

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Find element in List<> that contains a value

You can use the Where to filter and Select to get the desired value.

MyList.Where(i=>i.name == yourName).Select(j=>j.value);

Screen width in React Native

If you have a Style component that you can require from your Component, then you could have something like this at the top of the file:

const Dimensions = require('Dimensions');

const window = Dimensions.get('window');

And then you could provide fulscreen: {width: window.width, height: window.height}, in your Style component. Hope this helps

What's the UIScrollView contentInset property for?

It sets the distance of the inset between the content view and the enclosing scroll view.

Obj-C

aScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 7.0);

Swift 5.0

aScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 7.0)

Here's a good iOS Reference Library article on scroll views that has an informative screenshot (fig 1-3) - I'll replicate it via text here:

  _|?_cW_?_|_?_
   |       | 
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
  _|_______|___ 
             ?


   (cH = contentSize.height; cW = contentSize.width)

The scroll view encloses the content view plus whatever padding is provided by the specified content insets.

c# regex matches example

So you're trying to grab numeric values that are preceded by the token "%download%#"?

Try this pattern:

(?<=%download%#)\d+

That should work. I don't think # or % are special characters in .NET Regex, but you'll have to either escape the backslash like \\ or use a verbatim string for the whole pattern:

var regex = new Regex(@"(?<=%download%#)\d+");
return regex.Matches(strInput);

Tested here: http://rextester.com/BLYCC16700

NOTE: The lookbehind assertion (?<=...) is important because you don't want to include %download%# in your results, only the numbers after it. However, your example appears to require it before each string you want to capture. The lookbehind group will make sure it's there in the input string, but won't include it in the returned results. More on lookaround assertions here.

jQuery convert line breaks to br (nl2br equivalent)

This JavaScript function considers whether to use insert or replace to handle the swap.

(Insert or replace HTML line breaks)

/**
 * This function is same as PHP's nl2br() with default parameters.
 *
 * @param {string} str Input text
 * @param {boolean} replaceMode Use replace instead of insert
 * @param {boolean} isXhtml Use XHTML 
 * @return {string} Filtered text
 */
function nl2br (str, replaceMode, isXhtml) {

  var breakTag = (isXhtml) ? '<br />' : '<br>';
  var replaceStr = (replaceMode) ? '$1'+ breakTag : '$1'+ breakTag +'$2';
  return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr);
}

Demo - JSFiddle

JavaScript nl2br & br2nl functions

Error: Local workspace file ('angular.json') could not be found

~/Desktop $ ng serve

Local workspace file ('angular.json') could not be found.

Error: Local workspace file ('angular.json') could not be found.

at WorkspaceLoader._getProjectWorkspaceFilePath (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:37:19)
at WorkspaceLoader.loadWorkspace (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:24:21)
at ServeCommand._loadWorkspaceAndArchitect (/usr/lib/node_modules/@angular/cli/models/architect-command.js:180:32)
at ServeCommand.<anonymous> (/usr/lib/node_modules/@angular/cli/models/architect-command.js:47:25)
at Generator.next (<anonymous>)
at /usr/lib/node_modules/@angular/cli/models/architect-command.js:7:71
at new Promise (<anonymous>)
at __awaiter (/usr/lib/node_modules/@angular/cli/models/architect-command.js:3:12)
at ServeCommand.initialize (/usr/lib/node_modules/@angular/cli/models/architect-command.js:46:16)
at Object.<anonymous> (/usr/lib/node_modules/@angular/cli/models/command-runner.js:87:23)

This is because I haven't choose the Angular project directory.

It should be like:

~/Desktop/angularproject $ ng serve

iPhone keyboard, Done button and resignFirstResponder

In Xcode 5.1

Enable Done Button

  • In Attributes Inspector for the UITextField in Storyboard find the field "Return Key" and select "Done"

Hide Keyboard when Done is pressed

  • In Storyboard make your ViewController the delegate for the UITextField
  • Add this method to your ViewController

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
        return YES;
    }
    

How can I invert color using CSS?

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

In which conda environment is Jupyter executing?

which environment is jupyter executing:

import sys
print(sys.executable)

create kernel for jupyter notebook

source activate myenv
python -m ipykernel install --user --name myenv --display-name "Python (myenv)"
source activate other-env
python -m ipykernel install --user --name other-env --display-name "Python (other-env)"

http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernel-install

If (Array.Length == 0)

This is the best way. Please note Array is an object in NET so you need to check for null before.

Convert DataTable to CSV stream

I don't know if this converted from VB to C# ok but if you don't want quotes around your numbers, you might compare the data type as follows..

public string DataTableToCSV(DataTable dt)
{
    StringBuilder sb = new StringBuilder();
    if (dt == null)
        return "";

    try {
        // Create the header row
        for (int i = 0; i <= dt.Columns.Count - 1; i++) {
            // Append column name in quotes
            sb.Append("\"" + dt.Columns[i].ColumnName + "\"");
            // Add carriage return and linefeed if last column, else add comma
            sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
        }


        foreach (DataRow row in dt.Rows) {
            for (int i = 0; i <= dt.Columns.Count - 1; i++) {
                // Append value in quotes
                //sb.Append("""" & row.Item(i) & """")

                // OR only quote items that that are equivilant to strings
                sb.Append(object.ReferenceEquals(dt.Columns[i].DataType, typeof(string)) || object.ReferenceEquals(dt.Columns[i].DataType, typeof(char)) ? "\"" + row[i] + "\"" : row[i]);

                // Append CR+LF if last field, else add Comma
                sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
            }
        }
        return sb.ToString;
    } catch (Exception ex) {
        // Handle the exception however you want
        return "";
    }

}

Adding the "Clear" Button to an iPhone UITextField

you can add custom clear button and control the size and every thing using this:

UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
[clearButton setImage:img forState:UIControlStateNormal];
[clearButton setFrame:frame];
[clearButton addTarget:self action:@selector(clearTextField:) forControlEvents:UIControlEventTouchUpInside];

textField.rightViewMode = UITextFieldViewModeAlways; //can be changed to UITextFieldViewModeNever,    UITextFieldViewModeWhileEditing,   UITextFieldViewModeUnlessEditing
[textField setRightView:clearButton];

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

How to conclude your merge of a file?

The easiest solution I found for this:

git commit -m "fixing merge conflicts"
git push

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I'm not sure if I am correct, but from the request header that you post:

Request headers

Accept: Application/json

Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36

Content-Type: application/x-www-form-urlencoded

Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

it seems like you didn't config your request body to JSON type.

<hr> tag in Twitter Bootstrap not functioning correctly?

I solved this by setting the HR background-color to black like so:

<hr style="width: 100%; color: black; height: 1px; background-color:black;" />

How do I get the position selected in a RecyclerView?

@Override
public void onClick(View v) {
     int pos = getAdapterPosition();
}

Simple as that, on ViewHolder

How to correctly link php-fpm and Nginx Docker containers?

As previous answers have solved for, but should be stated very explicitly: the php code needs to live in the php-fpm container, while the static files need to live in the nginx container. For simplicity, most people have just attached all the code to both, as I have also done below. If the future, I will likely separate out these different parts of the code in my own projects as to minimize which containers have access to which parts.

Updated my example files below with this latest revelation (thank you @alkaline )

This seems to be the minimum setup for docker 2.0 forward (because things got a lot easier in docker 2.0)

docker-compose.yml:

version: '2'
services:
  php:
    container_name: test-php
    image: php:fpm
    volumes:
      - ./code:/var/www/html/site
  nginx:
    container_name: test-nginx
    image: nginx:latest
    volumes:
      - ./code:/var/www/html/site
      - ./site.conf:/etc/nginx/conf.d/site.conf:ro
    ports:
      - 80:80

(UPDATED the docker-compose.yml above: For sites that have css, javascript, static files, etc, you will need those files accessible to the nginx container. While still having all the php code accessible to the fpm container. Again, because my base code is a messy mix of css, js, and php, this example just attaches all the code to both containers)

In the same folder:

site.conf:

server
{
    listen   80;
    server_name site.local.[YOUR URL].com;

    root /var/www/html/site;
    index index.php;

    location /
    {
        try_files $uri =404;
    }

    location ~ \.php$ {
        fastcgi_pass   test-php:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

In folder code:

./code/index.php:

<?php
phpinfo();

and don't forget to update your hosts file:

127.0.0.1 site.local.[YOUR URL].com

and run your docker-compose up

$docker-compose up -d

and try the URL from your favorite browser

site.local.[YOUR URL].com/index.php

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

An additional possible cause.

My HTML page had these starting tags:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

This was on a page that using the slick jquery slideshow.

I removed the tags and replaced with:

<html>

And everything is working again.

How to select only date from a DATETIME field in MySQL?

Simply You can do

SELECT DATE(date_field) AS date_field FROM table_name

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

There is a pure CSS solution I'm currently using.

Add a body ID (or class) identifying your pages and your menu items, then use something like:

HTML:

<html>
    <body id="body_questions">
        <ul class="menu">
            <li id="questions">Question</li>
            <li id="tags">Tags</li>
            <li id="users">Users</li>
        </ul>
        ...
    </body>
</html>

CSS:

.menu li:hover,
#body_questions #questions,
#body_tags      #tags,
#body_users     #users {
    background-color: #f90;
}

Strip all non-numeric characters from string in JavaScript

Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:

myString = myString.replace(/\D/g,'');

How do I find an element position in std::vector?

In this case, it is safe to cast away the unsigned portion unless your vector can get REALLY big.

I would pull out the where.size() to a local variable since it won't change during the call. Something like this:

int find( const vector<type>& where, int searchParameter ){
    int size = static_cast<int>(where.size());
    for( int i = 0; i < size; i++ ) {
       if( conditionMet( where[i], searchParameter ) ) {
           return i;
       }
    }
    return -1;
}

How to convert FileInputStream to InputStream?

If you wrap one stream into another, you don't close intermediate streams, and very important: You don't close them before finishing using the outer streams. Because you would close the outer stream too.

How to get current user in asp.net core

Taking IdentityUser would also work. This is a current user object and all values of user can be retrieved.

private readonly UserManager<IdentityUser> _userManager;
public yourController(UserManager<IdentityUser> userManager)
{
    _userManager = userManager;
}

var user = await _userManager.GetUserAsync(HttpContext.User);

How to iterate over a string in C?

Rather than use strlen as suggested above, you can just check for the NULL character:

#include <stdio.h>

int main(int argc, char *argv[])
{
    const char *const pszSource = "This is an example.";
    const char *pszChar = pszSource;

    while (pszChar != NULL && *pszChar != '\0')
    {
        printf("%s", *pszChar);
        ++pszChar;
    }

    getchar();

    return 0;
}

Can I delete data from the iOS DeviceSupport directory?

Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect

How do I access previous promise results in a .then() chain?

I think you can use hash of RSVP.

Something like as below :

    const mainPromise = () => {
        const promise1 = new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('first promise is completed');
                resolve({data: '123'});
            }, 2000);
        });

        const promise2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('second promise is completed');
                resolve({data: '456'});
            }, 2000);
        });

        return new RSVP.hash({
              prom1: promise1,
              prom2: promise2
          });

    };


   mainPromise()
    .then(data => {
        console.log(data.prom1);
        console.log(data.prom2);
    });

From milliseconds to hour, minutes, seconds and milliseconds

Here is how I would do it in Java:

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours   = (int) ((milliseconds / (1000*60*60)) % 24);

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

If disabling incremental linking doesn't work for you, and turning off "Embed Manifest" doesn't work either, then search your path for multiple versions of CVTRES.exe.

By debugging with the /VERBOSE linker option I found the linker was writing that error message when it tried to invoke cvtres and it failed.

It turned out that I had two versions of this utility in my path. One at C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\cvtres.exe and one at C:\Windows\Microsoft.NET\Framework\v4.0.30319\cvtres.exe. After VS2012 install, the VS2010 version of cvtres.exe will no longer work. If that's the first one in your path, and the linker decides it needs to convert a .res file to COFF object format, the link will fail with LNK1123.

(Really annoying that the error message has nothing to do with the actual problem, but that's not unusual for a Microsoft product.)

Just delete/rename the older version of the utility, or re-arrange your PATH variable, so that the version that works comes first.

Be aware that for x64 tooling builds you may also have to check C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 where there is another cvtres.exe.

How to Toggle a div's visibility by using a button click

To switch the display-style between block and none you can do something like this:

function toggleDiv(id) {
    var div = document.getElementById(id);
    div.style.display = div.style.display == "none" ? "block" : "none";
}

working demo: http://jsfiddle.net/BQUyT/2/

How to run .APK file on emulator

Start an Android Emulator (make sure that all supported APIs are included when you created the emulator, we needed to have the Google APIs for instance).

Then simply email yourself a link to the .apk file, and download it directly in the emulator, and click the downloaded file to install it.

find filenames NOT ending in specific extensions on Unix?

You could do something using the grep command:

find . | grep -v '(dll|exe)$'

The -v flag on grep specifically means "find things that don't match this expression."

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

open Command line and type lodctr /r The p. counter will be resotred\recreated.

There is no need to skip it. http://technet.microsoft.com/en-us/library/cc774958.aspx

How to access /storage/emulated/0/

Android recommends that you call Environment.getExternalStorageDirectory.getPath() instead of hardcoding /sdcard/ in path name. This returns the primary shared/external storage directory. So, if storage is emulated, this will return /storage/emulated/0. If you explore the device storage with a file explorer, the said directory will be /mnt/sdcard (confirmed on Xperia Z2 running Android 6).

how to initialize a char array?

The "most C++" way to do this would be to use std::fill.

std::fill(msg, msg + 65546, 0);

Python main call within class

Remember, you are NOT allowed to do this.

class foo():
    def print_hello(self):
        print("Hello")       # This next line will produce an ERROR!
    self.print_hello()       # <---- it calls a class function, inside a class,
                             # but outside a class function. Not allowed.

You must call a class function from either outside the class, or from within a function in that class.

Iterating over arrays in Python 3

While iterating over a list or array with this method:

ar = [10, 11, 12]
for i in ar:
    theSum = theSum + ar[i]

You are actually getting the values of list or array sequentially in i variable. If you print the variable i inside the for loop. You will get following output:

10
11
12

However, in your code you are confusing i variable with index value of array. Therefore, while doing ar[i] will mean ar[10] for the first iteration. Which is of course index out of range throwing IndexError

Edit You can read this for better understanding of different methods of iterating over array or list in Python

react-router go back a page how do you configure history?

Call the following component like so:

<BackButton history={this.props.history} />

And here is the component:

import React, { Component } from 'react'
import PropTypes from 'prop-types'
class BackButton extends Component {
  constructor() {
    super(...arguments)

    this.goBack = this.goBack.bind(this)
  }

  render() {
    return (
      <button
        onClick={this.goBack}>
          Back
      </button>
    )
  }

  goBack() {
    this.props.history.goBack()
  }
}

BackButton.propTypes = {
  history: PropTypes.object,
}

export default BackButton

I'm using:

"react": "15.6.1"
"react-router": "4.2.0"

How to change background and text colors in Sublime Text 3

  1. Go to the preferences
  2. Click on color scheme
  3. Choose your color scheme
  4. I chose plastic, for my case.

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html