Programs & Examples On #Toplink essentials

The Java Persistence API Implementation at GlassFish

Proper way to restrict text input values (e.g. only numbers)

I think a custom ControlValueAccessor is the best option.

Not tested but as far as I remember, this should work:

<input [(ngModel)]="value" pattern="[0-9]">

How to get a list of all files in Cloud Storage in a Firebase app?

I faced the same issue, mine is even more complicated.

Admin will upload audio and pdf files into storage:

  • audios/season1, season2.../class1, class 2/.mp3 files

  • books/.pdf files

Android app needs to get the list of sub folders and files.

The solution is catching the upload event on storage and create the same structure on firestore using cloud function.

Step 1: Create manually 'storage' collection and 'audios/books' doc on firestore

enter image description here

Step 2: Setup cloud function

Might take around 15 mins: https://www.youtube.com/watch?v=DYfP-UIKxH0&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=1

Step 3: Catch upload event using cloud function

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
const path = require('path');

export const onFileUpload = functions.storage.object().onFinalize(async (object) => {
        let filePath = object.name; // File path in the bucket.
        const contentType = object.contentType; // File content type.
        const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
        if (metageneration !== "1") return;

        // Get the file name.
        const fileName = path.basename(filePath);
        filePath = filePath.substring(0, filePath.length - 1);
        console.log('contentType ' + contentType);
        console.log('fileName ' + fileName);
        console.log('filePath ' + filePath);
        console.log('path.dirname(filePath) ' + path.dirname(filePath));
        filePath = path.dirname(filePath);
        const pathArray = filePath.split("/");
        let ref = '';
        for (const item of pathArray) {
            if (ref.length === 0) {
                ref = item;
            }
            else {
                ref = ref.concat('/sub/').concat(item);
            }
        }

        ref = 'storage/'.concat(ref).concat('/sub')
        admin.firestore().collection(ref).doc(fileName).create({})
                .then(result => {console.log('onFileUpload:updated')})
                .catch(error => {
                    console.log(error);
                });
    });

Step 4: Retrieve list of folders/files on Android app using firestore

private static final String STORAGE_DOC = "storage/";
    public static void getMediaCollection(String path, OnCompleteListener onCompleteListener) {
        String[] pathArray = path.split("/");
        String doc = null;
        for (String item : pathArray) {
            if (TextUtils.isEmpty(doc)) doc = STORAGE_DOC.concat(item);
            else doc = doc.concat("/sub/").concat(item);
        }
        doc = doc.concat("/sub");

        getFirestore().collection(doc).get().addOnCompleteListener(onCompleteListener);
    }

Step 5: Get download url

public static void downloadMediaFile(String path, OnCompleteListener<Uri> onCompleteListener) {
        getStorage().getReference().child(path).getDownloadUrl().addOnCompleteListener(onCompleteListener);
    }

Note

We have to put "sub" collection to each item since firestore doesn't support to retrieve the list of collection.

It took me 3 days to find out the solution, hopefully will take you 3 hours at most.

Cheers.

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

compile function -

  1. is called before the controller and link function.
  2. In compile function, you have the original template DOM so you can make changes on original DOM before AngularJS creates an instance of it and before a scope is created
  3. ng-repeat is perfect example - original syntax is template element, the repeated elements in HTML are instances
  4. There can be multiple element instances and only one template element
  5. Scope is not available yet
  6. Compile function can return function and object
  7. returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.
  8. returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

syntax

function compile(tElement, tAttrs, transclude) { ... }

controller

  1. called after the compile function
  2. scope is available here
  3. can be accessed by other directives (see require attribute)

pre - link

  1. The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.

  2. You can update the dom in the controller using angular.element but this is not recommended as the element is provided in the link function

  3. Pre-link function is used to implement logic that runs when angular js has already compiled the child elements but before any of the child element's post link have been called

post-link

  1. directive that only has link function, angular treats the function as a post link

  2. post will be executed after compile, controller and pre-link funciton, so that's why this is considered the safest and default place to add your directive logic

Unexpected token < in first line of HTML

Check your encoding, i got something similar once because of the BOM.

Make sure the core.js file is encoded in utf-8 without BOM

How to remove unused dependencies from composer?

The right way to do this is:

composer remove jenssegers/mongodb --update-with-dependencies

I must admit the flag here is not quite obvious as to what it will do.

Update

composer remove jenssegers/mongodb

As of v1.0.0-beta2 --update-with-dependencies is the default and is no longer required.

Autocompletion of @author in Intellij

Check Enable Live Templates and leave the cursor at the position desired and click Apply then OK

enter image description here

Converting a Pandas GroupBy output from Series to DataFrame

g1 here is a DataFrame. It has a hierarchical index, though:

In [19]: type(g1)
Out[19]: pandas.core.frame.DataFrame

In [20]: g1.index
Out[20]: 
MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'),
       ('Mallory', 'Seattle')], dtype=object)

Perhaps you want something like this?

In [21]: g1.add_suffix('_Count').reset_index()
Out[21]: 
      Name      City  City_Count  Name_Count
0    Alice   Seattle           1           1
1      Bob   Seattle           2           2
2  Mallory  Portland           2           2
3  Mallory   Seattle           1           1

Or something like:

In [36]: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index()
Out[36]: 
      Name      City  count
0    Alice   Seattle      1
1      Bob   Seattle      2
2  Mallory  Portland      2
3  Mallory   Seattle      1

Calculate execution time of a SQL query?

declare @sttime  datetime
set @sttime=getdate()
print @sttime
Select * from ProductMaster   
SELECT RTRIM(CAST(DATEDIFF(MS, @sttime, GETDATE()) AS CHAR(10))) AS 'TimeTaken'    

What is the difference between T(n) and O(n)?

Using limits

Let's consider f(n) > 0 and g(n) > 0 for all n. It's ok to consider this, because the fastest real algorithm has at least one operation and completes its execution after the start. This will simplify the calculus, because we can use the value (f(n)) instead of the absolute value (|f(n)|).

  1. f(n) = O(g(n))

    General:

              f(n)     
    0 = lim -------- < 8
        n?8   g(n)
    

    For g(n) = n:

              f(n)     
    0 = lim -------- < 8
        n?8    n
    

    Examples:

        Expression               Value of the limit
    ------------------------------------------------
    n        = O(n)                      1
    1/2*n    = O(n)                     1/2
    2*n      = O(n)                      2
    n+log(n) = O(n)                      1
    n        = O(n*log(n))               0
    n        = O(n²)                     0
    n        = O(nn)                     0
    

    Counterexamples:

        Expression                Value of the limit
    -------------------------------------------------
    n        ? O(log(n))                 8
    1/2*n    ? O(sqrt(n))                8
    2*n      ? O(1)                      8
    n+log(n) ? O(log(n))                 8
    
  2. f(n) = T(g(n))

    General:

              f(n)     
    0 < lim -------- < 8
        n?8   g(n)
    

    For g(n) = n:

              f(n)     
    0 < lim -------- < 8
        n?8    n
    

    Examples:

        Expression               Value of the limit
    ------------------------------------------------
    n        = T(n)                      1
    1/2*n    = T(n)                     1/2
    2*n      = T(n)                      2
    n+log(n) = T(n)                      1
    

    Counterexamples:

        Expression                Value of the limit
    -------------------------------------------------
    n        ? T(log(n))                 8
    1/2*n    ? T(sqrt(n))                8
    2*n      ? T(1)                      8
    n+log(n) ? T(log(n))                 8
    n        ? T(n*log(n))               0
    n        ? T(n²)                     0
    n        ? T(nn)                     0
    

Swift 3: Display Image from URL

Using Alamofire worked out for me on Swift 3:

Step 1:

Integrate using pods.

pod 'Alamofire', '~> 4.4'

pod 'AlamofireImage', '~> 3.3'

Step 2:

import AlamofireImage

import Alamofire

Step 3:

Alamofire.request("https://httpbin.org/image/png").responseImage { response in

if let image = response.result.value {
    print("image downloaded: \(image)")
self.myImageview.image = image
}
}

Drop multiple tables in one shot in MySQL

Example:

Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

How to determine a Python variable's type?

How to determine the variable type in Python?

So if you have a variable, for example:

one = 1

You want to know its type?

There are right ways and wrong ways to do just about everything in Python. Here's the right way:

Use type

>>> type(one)
<type 'int'>

You can use the __name__ attribute to get the name of the object. (This is one of the few special attributes that you need to use the __dunder__ name to get to - there's not even a method for it in the inspect module.)

>>> type(one).__name__
'int'

Don't use __class__

In Python, names that start with underscores are semantically not a part of the public API, and it's a best practice for users to avoid using them. (Except when absolutely necessary.)

Since type gives us the class of the object, we should avoid getting this directly. :

>>> one.__class__

This is usually the first idea people have when accessing the type of an object in a method - they're already looking for attributes, so type seems weird. For example:

class Foo(object):
    def foo(self):
        self.__class__

Don't. Instead, do type(self):

class Foo(object):
    def foo(self):
        type(self)

Implementation details of ints and floats

How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?

In Python, these specifics are implementation details. So, in general, we don't usually worry about this in Python. However, to sate your curiosity...

In Python 2, int is usually a signed integer equal to the implementation's word width (limited by the system). It's usually implemented as a long in C. When integers get bigger than this, we usually convert them to Python longs (with unlimited precision, not to be confused with C longs).

For example, in a 32 bit Python 2, we can deduce that int is a signed 32 bit integer:

>>> import sys

>>> format(sys.maxint, '032b')
'01111111111111111111111111111111'
>>> format(-sys.maxint - 1, '032b') # minimum value, see docs.
'-10000000000000000000000000000000'

In Python 3, the old int goes away, and we just use (Python's) long as int, which has unlimited precision.

We can also get some information about Python's floats, which are usually implemented as a double in C:

>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, 
min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, 
mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)

Conclusion

Don't use __class__, a semantically nonpublic API, to get the type of a variable. Use type instead.

And don't worry too much about the implementation details of Python. I've not had to deal with issues around this myself. You probably won't either, and if you really do, you should know enough not to be looking to this answer for what to do.

How do I force files to open in the browser instead of downloading (PDF)?

Either use

<embed src="file.pdf" />

if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff

Finding the length of an integer in C

C:

Why not just take the base-10 log of the absolute value of the number, round it down, and add one? This works for positive and negative numbers that aren't 0, and avoids having to use any string conversion functions.

The log10, abs, and floor functions are provided by math.h. For example:

int nDigits = floor(log10(abs(the_integer))) + 1;

You should wrap this in a clause ensuring that the_integer != 0, since log10(0) returns -HUGE_VAL according to man 3 log.

Additionally, you may want to add one to the final result if the input is negative, if you're interested in the length of the number including its negative sign.

Java:

int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;

N.B. The floating-point nature of the calculations involved in this method may cause it to be slower than a more direct approach. See the comments for Kangkan's answer for some discussion of efficiency.

Compile to a stand-alone executable (.exe) in Visual Studio

I've never had problems with deploying small console application made in C# as-is. The only problem you can bump into would be a dependency on the .NET framework, but even that shouldn't be a major problem. You could try using version 2.0 of the framework, which should already be on most PCs.

Using native, unmanaged C++, you should not have any dependencies on the .NET framework, so you really should be safe. Just grab the executable and any accompanying files (if there are any) and deploy them as they are; there's no need to install them if you don't want to.

How to get the range of occupied cells in excel sheet

These two lines on their own wasnt working for me:

xlWorkSheet.Columns.ClearFormats();
xlWorkSheet.Rows.ClearFormats();

You can test by hitting ctrl+end in the sheet and seeing which cell is selected.

I found that adding this line after the first two solved the problem in all instances I've encountered:

Excel.Range xlActiveRange = WorkSheet.UsedRange;

Apache2: 'AH01630: client denied by server configuration'

I got another one that may be useful to someone. Was receiving the same error message after upgrading from PHP 5.6 => 7.0. We had changed the PHP upload settings, and forgot to change once copied over. Even though i wasn't uploading images at the time, Silverstripe (our CMS) was refusing to save and throwing that error. Increased the image upload size and it worked straight away.

How to calculate difference in hours (decimal) between two dates in SQL Server?

DATEDIFF(minute,startdate,enddate)/60.0)

Or use this for 2 decimal places:

CAST(DATEDIFF(minute,startdate,enddate)/60.0 as decimal(18,2))

How to handle windows file upload using Selenium WebDriver?

Find the element (must be an input element with type="file" attribute) and send the path to the file.

WebElement fileInput = driver.findElement(By.id("uploadFile"));
fileInput.sendKeys("/path/to/file.jpg");

NOTE: If you're using a RemoteWebDriver, you will also have to set a file detector. The default is UselessFileDetector

WebElement fileInput = driver.findElement(By.id("uploadFile"));
driver.setFileDetector(new LocalFileDetector());
fileInput.sendKeys("/path/to/file.jpg");

Datatables warning(table id = 'example'): cannot reinitialise data table

When searching this topic I found the solution elsewhere but adding the answer here since I had the same problem as above together with the text "Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined". Cause was due to having one to many tags in the table body.

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

Boto3 to download all files from a S3 Bucket

I have the same needs and created the following function that download recursively the files.

The directories are created locally only if they contain files.

import boto3
import os

def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'):
    paginator = client.get_paginator('list_objects')
    for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
        if result.get('CommonPrefixes') is not None:
            for subdir in result.get('CommonPrefixes'):
                download_dir(client, resource, subdir.get('Prefix'), local, bucket)
        for file in result.get('Contents', []):
            dest_pathname = os.path.join(local, file.get('Key'))
            if not os.path.exists(os.path.dirname(dest_pathname)):
                os.makedirs(os.path.dirname(dest_pathname))
            resource.meta.client.download_file(bucket, file.get('Key'), dest_pathname)

The function is called that way:

def _start():
    client = boto3.client('s3')
    resource = boto3.resource('s3')
    download_dir(client, resource, 'clientconf/', '/tmp', bucket='my-bucket')

How to serve up a JSON response using Go?

Other users commenting that the Content-Type is plain/text when encoding. You have to set the Content-Type first w.Header().Set, then the HTTP response code w.WriteHeader.

If you call w.WriteHeader first then call w.Header().Set after you will get plain/text.

An example handler might look like this;

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := SomeStruct{}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(data)
}

Reference jars inside a jar

in eclipse, right click project, select RunAs -> Run Configuration and save your run configuration, this will be used when you next export as Runnable JARs

Reading images in python

import matplotlib.pyplot as plt
image = plt.imread('images/my_image4.jpg')
plt.imshow(image)

Using 'matplotlib.pyplot.imread' is recommended by warning messages in jupyter.

How to copy commits from one branch to another?

You could create a patch from the commits that you want to copy and apply the patch to the destination branch.

Set port for php artisan.php serve

as this example you can change ip and port this works with me

php artisan serve --host=0.0.0.0 --port=8000

Django CSRF check failing with an Ajax POST request

Easy ajax calls with Django

(26.10.2020)
This is in my opinion much cleaner and simpler than the correct answer.

The view

@login_required
def some_view(request):
    """Returns a json response to an ajax call. (request.user is available in view)"""
    # Fetch the attributes from the request body
    data_attribute = request.GET.get('some_attribute')  # Make sure to use POST/GET correctly
    # DO SOMETHING...
    return JsonResponse(data={}, status=200)

urls.py

urlpatterns = [
    path('some-view-does-something/', views.some_view, name='doing-something'),
]

The ajax call

The ajax call is quite simple, but is sufficient for most cases. You can fetch some values and put them in the data object, then in the view depicted above you can fetch their values again via their names.

You can find the csrftoken function in django's documentation. Basically just copy it and make sure it is rendered before your ajax call so that the csrftoken variable is defined.

$.ajax({
    url: "{% url 'doing-something' %}",
    headers: {'X-CSRFToken': csrftoken},
    data: {'some_attribute': some_value},
    type: "GET",
    dataType: 'json',
    success: function (data) {
        if (data) {
            console.log(data);
            // call function to do something with data
            process_data_function(data);
        }
    }
});

Add HTML to current page with ajax

This might be a bit off topic but I have rarely seen this used and it is a great way to minimize window relocations as well as manual html string creation in javascript.

This is very similar to the one above but this time we are rendering html from the response without reloading the current window.

If you intended to render some kind of html from the data you would receive as a response to the ajax call, it might be easier to send a HttpResponse back from the view instead of a JsonResponse. That allows you to create html easily which can then be inserted into an element.

The view

# The login required part is of course optional
@login_required
def create_some_html(request):
    """In this particular example we are filtering some model by a constraint sent in by 
    ajax and creating html to send back for those models who match the search"""
    # Fetch the attributes from the request body (sent in ajax data)
    search_input = request.GET.get('search_input')

    # Get some data that we want to render to the template
    if search_input:
        data = MyModel.objects.filter(name__contains=search_input) # Example
    else:
        data = []

    # Creating an html string using template and some data
    html_response = render_to_string('path/to/creation_template.html', context = {'models': data})

    return HttpResponse(html_response, status=200)

The html creation template for view

creation_template.html

{% for model in models %}
   <li class="xyz">{{ model.name }}</li>
{% endfor %}

urls.py

urlpatterns = [
    path('get-html/', views.create_some_html, name='get-html'),
]

The main template and ajax call

This is the template where we want to add the data to. In this example in particular we have a search input and a button that sends the search input's value to the view. The view then sends a HttpResponse back displaying data matching the search that we can render inside an element.

{% extends 'base.html' %}
{% load static %}
{% block content %}
    <input id="search-input" placeholder="Type something..." value="">
    <button id="add-html-button" class="btn btn-primary">Add Html</button>
    <ul id="add-html-here">
        <!-- This is where we want to render new html -->
    </ul>
{% end block %}

{% block extra_js %}
    <script>
        // When button is pressed fetch inner html of ul
        $("#add-html-button").on('click', function (e){
            e.preventDefault();
            let search_input = $('#search-input').val();
            let target_element = $('#add-html-here');
            $.ajax({
                url: "{% url 'get-html' %}",
                headers: {'X-CSRFToken': csrftoken},
                data: {'search_input': search_input},
                type: "GET",
                dataType: 'html',
                success: function (data) {
                    if (data) {
                        /* You could also use json here to get multiple html to
                        render in different places */
                        console.log(data);
                        // Add the http response to element
                        target_element.html(data);
                    }
                }
            });
        })
    </script>
{% endblock %}

Change Timezone in Lumen or Laravel 5

For me the app.php was here /vendor/laravel/lumen-framework/config/app.php but I also could change it from the .env file where it can be set to any of the values listed here (PHP original documentation here).

Move entire line up and down in Vim

Assuming the cursor is on the line you like to move.

Moving up and down: :m for move

:m +1 - moves down 1 line

:m -2 - move up 1 lines

(Note you can replace +1 with any numbers depending on how many lines you want to move it up or down, ie +2 would move it down 2 lines, -3 would move it up 2 lines)

To move to specific line

:set number - display number lines (easier to see where you are moving it to)

:m 3 - move the line after 3rd line (replace 3 to any line you'd like)

Moving multiple lines:

V (i.e. Shift-V) and move courser up and down to select multiple lines in VIM

once selected hit : and run the commands above, m +1 etc

How to use Object.values with typescript?

I just hit this exact issue with Angular 6 using the CLI and workspaces to create a library using ng g library foo.

In my case the issue was in the tsconfig.lib.json in the library folder which did not have es2017 included in the lib section.

Anyone stumbling across this issue with Angular 6 you just need to ensure that you update you tsconfig.lib.json as well as your application tsconfig.json

Clearing NSUserDefaults

Here is the answer in Swift:

let appDomain = NSBundle.mainBundle().bundleIdentifier!
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)

Printing integer variable and string on same line in SQL

Double check if you have set and initial value for int and decimal values to be printed.

This sample is printing an empty line

declare @Number INT
print 'The number is : ' + CONVERT(VARCHAR, @Number)

And this sample is printing -> The number is : 1

declare @Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, @Number)

How to generate classes from wsdl using Maven and wsimport?

The key here is keep option of wsimport. And it is configured using element in About keep from the wsimport documentation :

-keep                     keep generated files

How to make parent wait for all child processes to finish?

pid_t child_pid, wpid;
int status = 0;

//Father code (before child processes start)

for (int id=0; id<n; id++) {
    if ((child_pid = fork()) == 0) {
        //child code
        exit(0);
    }
}

while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes 

//Father code (After all child processes end)

wait waits for a child process to terminate, and returns that child process's pid. On error (eg when there are no child processes), -1 is returned. So, basically, the code keeps waiting for child processes to finish, until the waiting errors out, and then you know they are all finished.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.

Personally, I wouldn't bother; I'd just rename the column.

PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.

What does the Java assert keyword do, and when should it be used?

An assertion allows for detecting defects in the code. You can turn on assertions for testing and debugging while leaving them off when your program is in production.

Why assert something when you know it is true? It is only true when everything is working properly. If the program has a defect, it might not actually be true. Detecting this earlier in the process lets you know something is wrong.

An assert statement contains this statement along with an optional String message.

The syntax for an assert statement has two forms:

assert boolean_expression;
assert boolean_expression: error_message;

Here are some basic rules which govern where assertions should be used and where they should not be used. Assertions should be used for:

  1. Validating input parameters of a private method. NOT for public methods. public methods should throw regular exceptions when passed bad parameters.

  2. Anywhere in the program to ensure the validity of a fact which is almost certainly true.

For example, if you are sure that it will only be either 1 or 2, you can use an assertion like this:

...
if (i == 1)    {
    ...
}
else if (i == 2)    {
    ...
} else {
    assert false : "cannot happen. i is " + i;
}
...
  1. Validating post conditions at the end of any method. This means, after executing the business logic, you can use assertions to ensure that the internal state of your variables or results is consistent with what you expect. For example, a method that opens a socket or a file can use an assertion at the end to ensure that the socket or the file is indeed opened.

Assertions should not be used for:

  1. Validating input parameters of a public method. Since assertions may not always be executed, the regular exception mechanism should be used.

  2. Validating constraints on something that is input by the user. Same as above.

  3. Should not be used for side effects.

For example this is not a proper use because here the assertion is used for its side effect of calling of the doSomething() method.

public boolean doSomething() {
...    
}
public void someMethod() {       
assert doSomething(); 
}

The only case where this could be justified is when you are trying to find out whether or not assertions are enabled in your code:   

boolean enabled = false;    
assert enabled = true;    
if (enabled) {
    System.out.println("Assertions are enabled");
} else {
    System.out.println("Assertions are disabled");
}

How can I debug a Perl script?

If you want to do remote debugging (for CGI or if you don't want to mess output with debug command line), use this:

Given test:

use v5.14;
say 1;
say 2;
say 3;

Start a listener on whatever host and port on terminal 1 (here localhost:12345):

$ nc -v -l localhost -p 12345

For readline support use rlwrap (you can use on perl -d too):

$ rlwrap nc -v -l localhost -p 12345

And start the test on another terminal (say terminal 2):

$ PERLDB_OPTS="RemotePort=localhost:12345" perl -d test

Input/Output on terminal 1:

Connection from 127.0.0.1:42994

Loading DB routines from perl5db.pl version 1.49
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(test:2):    say 1;
  DB<1> n
main::(test:3):    say 2;
  DB<1> select $DB::OUT

  DB<2> n
2
main::(test:4):    say 3;
  DB<2> n
3
Debugged program terminated.  Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.
  DB<2>

Output on terminal 2:

1

Note the sentence if you want output on debug terminal

select $DB::OUT

If you are Vim user, install this plugin: dbg.vim which provides basic support for Perl.

How to convert a 3D point into 2D perspective projection?

Thanks to @Mads Elvenheim for a proper example code. I have fixed the minor syntax errors in the code (just a few const problems and obvious missing operators). Also, near and far have vastly different meanings in vs.

For your pleasure, here is the compileable (MSVC2013) version. Have fun. Mind that I have made NEAR_Z and FAR_Z constant. You probably dont want it like that.

#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>

#define M_PI 3.14159

#define NEAR_Z 0.5
#define FAR_Z 2.5

struct Vector
{
    float x;
    float y;
    float z;
    float w;

    Vector() : x( 0 ), y( 0 ), z( 0 ), w( 1 ) {}
    Vector( float a, float b, float c ) : x( a ), y( b ), z( c ), w( 1 ) {}

    /* Assume proper operator overloads here, with vectors and scalars */
    float Length() const
    {
        return std::sqrt( x*x + y*y + z*z );
    }
    Vector& operator*=(float fac) noexcept
    {
        x *= fac;
        y *= fac;
        z *= fac;
        return *this;
    }
    Vector  operator*(float fac) const noexcept
    {
        return Vector(*this)*=fac;
    }
    Vector& operator/=(float div) noexcept
    {
        return operator*=(1/div);   // avoid divisions: they are much
                                    // more costly than multiplications
    }

    Vector Unit() const
    {
        const float epsilon = 1e-6;
        float mag = Length();
        if (mag < epsilon) {
            std::out_of_range e( "" );
            throw e;
        }
        return Vector(*this)/=mag;
    }
};

inline float Dot( const Vector& v1, const Vector& v2 )
{
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

class Matrix
{
public:
    Matrix() : data( 16 )
    {
        Identity();
    }
    void Identity()
    {
        std::fill( data.begin(), data.end(), float( 0 ) );
        data[0] = data[5] = data[10] = data[15] = 1.0f;
    }
    float& operator[]( size_t index )
    {
        if (index >= 16) {
            std::out_of_range e( "" );
            throw e;
        }
        return data[index];
    }
    const float& operator[]( size_t index ) const
    {
        if (index >= 16) {
            std::out_of_range e( "" );
            throw e;
        }
        return data[index];
    }
    Matrix operator*( const Matrix& m ) const
    {
        Matrix dst;
        int col;
        for (int y = 0; y<4; ++y) {
            col = y * 4;
            for (int x = 0; x<4; ++x) {
                for (int i = 0; i<4; ++i) {
                    dst[x + col] += m[i + col] * data[x + i * 4];
                }
            }
        }
        return dst;
    }
    Matrix& operator*=( const Matrix& m )
    {
        *this = (*this) * m;
        return *this;
    }

    /* The interesting stuff */
    void SetupClipMatrix( float fov, float aspectRatio )
    {
        Identity();
        float f = 1.0f / std::tan( fov * 0.5f );
        data[0] = f*aspectRatio;
        data[5] = f;
        data[10] = (FAR_Z + NEAR_Z) / (FAR_Z- NEAR_Z);
        data[11] = 1.0f; /* this 'plugs' the old z into w */
        data[14] = (2.0f*NEAR_Z*FAR_Z) / (NEAR_Z - FAR_Z);
        data[15] = 0.0f;
    }

    std::vector<float> data;
};


inline Vector operator*( const Vector& v, Matrix& m )
{
    Vector dst;
    dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8] + v.w*m[12];
    dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9] + v.w*m[13];
    dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
    dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
    return dst;
}

typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip( int width, int height, const VecArr& vertex )
{
    float halfWidth = (float)width * 0.5f;
    float halfHeight = (float)height * 0.5f;
    float aspect = (float)width / (float)height;
    Vector v;
    Matrix clipMatrix;
    VecArr dst;
    clipMatrix.SetupClipMatrix( 60.0f * (M_PI / 180.0f), aspect);
    /*  Here, after the perspective divide, you perform Sutherland-Hodgeman clipping
    by checking if the x, y and z components are inside the range of [-w, w].
    One checks each vector component seperately against each plane. Per-vertex
    data like colours, normals and texture coordinates need to be linearly
    interpolated for clipped edges to reflect the change. If the edge (v0,v1)
    is tested against the positive x plane, and v1 is outside, the interpolant
    becomes: (v1.x - w) / (v1.x - v0.x)
    I skip this stage all together to be brief.
    */
    for (VecArr::const_iterator i = vertex.begin(); i != vertex.end(); ++i) {
        v = (*i) * clipMatrix;
        v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
        dst.push_back( v );
    }

    /* TODO: Clipping here */

    for (VecArr::iterator i = dst.begin(); i != dst.end(); ++i) {
        i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
        i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
    }
    return dst;
}
#pragma once

Populating a data frame in R in a loop

this works too.

df = NULL
for (k in 1:10)
    {
       x = 1
       y = 2
       z = 3
       df = rbind(df, data.frame(x,y,z))
     }

output will look like this

df #enter

x y z #col names
1 2 3

pop/remove items out of a python tuple

say you have a dict with tuples as keys, e.g: labels = {(1,2,0): 'label_1'} you can modify the elements of the tuple keys as follows:

formatted_labels = {(elem[0],elem[1]):labels[elem] for elem in labels}

Here, we ignore the last elements.

Get current date in milliseconds

- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strTime = [objDateformat stringFromDate:[NSDate date]];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);

        NSString *strTimeStamp = [NSString stringWithFormat:@"%lld",milliseconds];
        NSLog(@"The Timestamp is = %@",strTimeStamp);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

How to resolve ambiguous column names when retrieving results?

Here's an answer to the above, that's both simple and also works with JSON results being returned. While the SQL query will automatically prefix table names to each instance of identical field names when you use SELECT *, JSON encoding of the result to send back to the webpage, ignores the values of those fields with a duplicate name and instead returns a NULL value.

Precisely what it does is include the first instance of the duplicated field name, but makes its value NULL. And the second instance of the field name (in the other table) is omitted entirely, both field name and value. But, when you test the query directly on the database (such as using Navicat), all fields are returned in the result set. It's only when you next do JSON encoding of that result, do they have NULL values and subsequent duplicate names are omitted entirely.

So, an easy way to fix that problem is to first do a SELECT *, then follow with aliased fields for the duplicates. Here's an example, where both tables have identically named site_name fields.

SELECT *, w.site_name AS wo_site_name FROM ws_work_orders w JOIN ws_inspections i WHERE w.hma_num NOT IN(SELECT hma_number FROM ws_inspections) ORDER BY CAST(w.hma_num AS UNSIGNED);

Now in the decoded JSON, you can use the field wo_site_name and it has a value. In this case, site names have special characters such as apostrophes and single quotes, hence the encoding when originally saving, and the decoding when using the result from the database.

...decHTMLifEnc(decodeURIComponent( jsArrInspections[x]["wo_site_name"]))

You must always put the * first in the SELECT statement, but after it you can include as many named and aliased columns as you want, as repeatedly selecting a column causes no problem.

Controller not a function, got undefined, while defining controllers globally

I got this problem because I had wrapped a controller-definition file in a closure:

(function() {
   ...stuff...
});

But I had forgotten to actually invoke that closure to execute that definition code and actually tell Javascript my controller existed. I.e., the above needs to be:

(function() {
   ...stuff...
})();

Note the () at the end.

Setting Android Theme background color

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
        <item name="android:windowBackground">@android:color/black</item>
    </style>

</resources>

Spring MVC - HttpMediaTypeNotAcceptableException

In my case

 {"timestamp":1537542856089,"status":406,"error":"Not Acceptable","exception":"org.springframework.web.HttpMediaTypeNotAcceptableException","message":"Could not find acceptable representation","path":"/a/101.xml"}

was caused by:

path = "/path/{VariableName}" but I was passing in VariableName with a suffix, like "abc.xml" which makes it interpret the .xml as some kind of format request instead. See answers there.

How do I find the current directory of a batch file, and then use it for the path?

There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:

.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt

And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:

@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit

Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:

@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit

Node Version Manager install - nvm command not found

Quick answer

Figure out the following:

  1. Which shell is your terminal using, type in: echo $0 to find out (normally works)
  2. Which start-up file does that shell load when starting up (NOT login shell starting file, the normal shell starting file, there is a difference!)
  3. Add source ~/.nvm/nvm.sh to that file (assuming that file exists at that location, it is the default install location)
  4. Start a new terminal session
  5. Profit?

Example

As you can see it states zsh and not bash. enter image description here

To fix this I needed to add source ~/.nvm/nvm.sh to the ~/.zshrc file as when starting a new terminal my Deepin Terminal zsh reads ~/.zshrc and not bashs ~/.bashrc.

Why does this happen

This happens because when installing NVM it adds code to ~/.bashrc, as my terminal Deepin Terminal uses zsh and not bash it never reads ~/.bashrc and therefor never loads NVM.

In other words: this is NVMs fault.

More on zsh can be read on one of the answers here.

Node.js connect only works on localhost

Most probably your server socket is bound to the loopback IP address 127.0.0.1 instead of the "all IP addresses" symbolic IP 0.0.0.0 (note this is NOT a netmask). To confirm this, run sudo netstat -ntlp (If you are on linux) or netstat -an -f inet -p tcp | grep LISTEN (OSX) and check which IP your process is bound to (look for the line with ":3000"). If you see "127.0.0.1", that's the problem. Fix it by passing "0.0.0.0" to the listen call:

var app = connect().use(connect.static('public')).listen(3000, "0.0.0.0");

Exception from HRESULT: 0x800A03EC Error

Got the same error when tried to export a large Excel file (~150.000 rows) Fixed with the following code

Application xlApp = new Application();
xlApp.DefaultSaveFormat = XlFileFormat.xlOpenXMLWorkbook;

How do I create a slug in Django?

I'm using Django 1.7

Create a SlugField in your model like this:

slug = models.SlugField()

Then in admin.py define prepopulated_fields;

class ArticleAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}

Two Radio Buttons ASP.NET C#

     <asp:RadioButtonList id="RadioButtonList1" runat="server">
        <asp:ListItem Selected="True">Metric</asp:ListItem>
        <asp:ListItem>US</asp:ListItem>
     </asp:RadioButtonList>

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

Why are there extra spaces between my month and day? Why does't it just put them next to each other?

So your output will be aligned.

If you don't want padding use the format modifier FM:

SELECT TO_CHAR (date_field, 'fmMonth DD, YYYY') 
  FROM ...;

Reference: Format Model Modifiers

How do I make an http request using cookies on Android?

It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the HttpClient docs:

https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientFormLogin.java


import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform
 * form-based logon.
 */
public class ClientFormLogin {

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

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }
        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
                "org=self_registered_users&" +
                "goto=/portal/dt&" +
                "gotoOnFail=/portal/dt?error=true");

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("IDToken1", "username"));
        nvps.add(new BasicNameValuePair("IDToken2", "password"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpost);
        entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        // When HttpClient instance is no longer needed, 
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();        
    }
}

How can I set the 'backend' in matplotlib in Python?

I hit this when trying to compile python, numpy, scipy, matplotlib in my own VIRTUAL_ENV

Before installing matplotlib you have to build and install: pygobject pycairo pygtk

And then do it with matplotlib: Before building matplotlib check with 'python ./setup.py build --help' if 'gtkagg' backend is enabled. Then build and install

Before export PKG_CONFIG_PATH=$VIRTUAL_ENV/lib/pkgconfig

Saving timestamp in mysql table using php

$created_date = date("Y-m-d H:i:s");
$sql = "INSERT INTO $tbl_name(created_date)VALUES('$created_date')";
$result = mysql_query($sql);

is there something like isset of php in javascript/jQuery?

JavaScript isset() on PHP JS

function isset () {
    // discuss at: http://phpjs.org/functions/isset
    // +   original by: Kevin van     Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // +   improved by: Onno Marsman
    // +   improved by: Rafal Kukawski
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
    var a = arguments,
        l = a.length,
        i = 0,
        undef;

    if (l === 0) {
        throw new Error('Empty isset');
    }

    while (i !== l) {
        if (a[i] === undef || a[i] === null) {
            return false;
        }
        i++;
    }
    return true;
}

Why use a ReentrantLock if one can use synchronized(this)?

A ReentrantLock is unstructured, unlike synchronized constructs -- i.e. you don't need to use a block structure for locking and can even hold a lock across methods. An example:

private ReentrantLock lock;

public void foo() {
  ...
  lock.lock();
  ...
}

public void bar() {
  ...
  lock.unlock();
  ...
}

Such flow is impossible to represent via a single monitor in a synchronized construct.


Aside from that, ReentrantLock supports lock polling and interruptible lock waits that support time-out. ReentrantLock also has support for configurable fairness policy, allowing more flexible thread scheduling.

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.


ReentrantLock may also be more scalable, performing much better under higher contention. You can read more about this here.

This claim has been contested, however; see the following comment:

In the reentrant lock test, a new lock is created each time, thus there is no exclusive locking and the resulting data is invalid. Also, the IBM link offers no source code for the underlying benchmark so its impossible to characterize whether the test was even conducted correctly.


When should you use ReentrantLocks? According to that developerWorks article...

The answer is pretty simple -- use it when you actually need something it provides that synchronized doesn't, like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling. ReentrantLock also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention, but remember that the vast majority of synchronized blocks hardly ever exhibit any contention, let alone high contention. I would advise developing with synchronization until synchronization has proven to be inadequate, rather than simply assuming "the performance will be better" if you use ReentrantLock. Remember, these are advanced tools for advanced users. (And truly advanced users tend to prefer the simplest tools they can find until they're convinced the simple tools are inadequate.) As always, make it right first, and then worry about whether or not you have to make it faster.


One final aspect that's gonna become more relevant in the near future has to do with Java 15 and Project Loom. In the (new) world of virtual threads, the underlying scheduler would be able to work much better with ReentrantLock than it's able to do with synchronized, that's true at least in the initial Java 15 release but may be optimized later.

In the current Loom implementation, a virtual thread can be pinned in two situations: when there is a native frame on the stack — when Java code calls into native code (JNI) that then calls back into Java — and when inside a synchronized block or method. In those cases, blocking the virtual thread will block the physical thread that carries it. Once the native call completes or the monitor released (the synchronized block/method is exited) the thread is unpinned.

If you have a common I/O operation guarded by a synchronized, replace the monitor with a ReentrantLock to let your application benefit fully from Loom’s scalability boost even before we fix pinning by monitors (or, better yet, use the higher-performance StampedLock if you can).

Sum across multiple columns with dplyr

I encounter this problem often, and the easiest way to do this is to use the apply() function within a mutate command.

library(tidyverse)
df=data.frame(
  x1=c(1,0,0,NA,0,1,1,NA,0,1),
  x2=c(1,1,NA,1,1,0,NA,NA,0,1),
  x3=c(0,1,0,1,1,0,NA,NA,0,1),
  x4=c(1,0,NA,1,0,0,NA,0,0,1),
  x5=c(1,1,NA,1,1,1,NA,1,0,1))

df %>%
  mutate(sum = select(., x1:x5) %>% apply(1, sum, na.rm=TRUE))

Here you could use whatever you want to select the columns using the standard dplyr tricks (e.g. starts_with() or contains()). By doing all the work within a single mutate command, this action can occur anywhere within a dplyr stream of processing steps. Finally, by using the apply() function, you have the flexibility to use whatever summary you need, including your own purpose built summarization function.

Alternatively, if the idea of using a non-tidyverse function is unappealing, then you could gather up the columns, summarize them and finally join the result back to the original data frame.

df <- df %>% mutate( id = 1:n() )   # Need some ID column for this to work

df <- df %>%
  group_by(id) %>%
  gather('Key', 'value', starts_with('x')) %>%
  summarise( Key.Sum = sum(value) ) %>%
  left_join( df, . )

Here I used the starts_with() function to select the columns and calculated the sum and you can do whatever you want with NA values. The downside to this approach is that while it is pretty flexible, it doesn't really fit into a dplyr stream of data cleaning steps.

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

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

In standard SQL one would write:

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

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

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

Delete with "Join" in Oracle sql Query

Based on the answer I linked to in my comment above, this should work:

delete from
(
select pf.* From PRODUCTFILTERS pf 
where pf.id>=200 
And pf.rowid in 
  (
     Select rowid from PRODUCTFILTERS 
     inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID 
     And PRODUCTS.NAME= 'Mark'
  )
); 

or

delete from PRODUCTFILTERS where rowid in
(
select pf.rowid From PRODUCTFILTERS pf 
where pf.id>=200 
And pf.rowid in 
  (
     Select PRODUCTFILTERS.rowid from PRODUCTFILTERS 
     inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID 
     And PRODUCTS.NAME= 'Mark'
  )
); 

Installing specific package versions with pip

Sometimes, the previously installed version is cached.

~$ pip install pillow==5.2.0

It returns the followings:
Requirement already satisfied: pillow==5.2.0 in /home/ubuntu/anaconda3/lib/python3.6/site-packages (5.2.0)

We can use --no-cache-dir together with -I to overwrite this

~$ pip install --no-cache-dir -I pillow==5.2.0

The SQL OVER() clause - when and why is it useful?

So in simple words: Over clause can be used to select non aggregated values along with Aggregated ones.

Partition BY, ORDER BY inside, and ROWS or RANGE are part of OVER() by clause.

partition by is used to partition data and then perform these window, aggregated functions, and if we don't have partition by the then entire result set is considered as a single partition.

OVER clause can be used with Ranking Functions(Rank, Row_Number, Dense_Rank..), Aggregate Functions like (AVG, Max, Min, SUM...etc) and Analytics Functions like (First_Value, Last_Value, and few others).

Let's See basic syntax of OVER clause

OVER (   
       [ <PARTITION BY clause> ]  
       [ <ORDER BY clause> ]   
       [ <ROW or RANGE clause> ]  
      )  

PARTITION BY: It is used to partition data and perform operations on groups with the same data.

ORDER BY: It is used to define the logical order of data in Partitions. When we don't specify Partition, entire resultset is considered as a single partition

: This can be used to specify what rows are supposed to be considered in a partition when performing the operation.

Let's take an example:

Here is my dataset:

Id          Name                                               Gender     Salary
----------- -------------------------------------------------- ---------- -----------
1           Mark                                               Male       5000
2           John                                               Male       4500
3           Pavan                                              Male       5000
4           Pam                                                Female     5500
5           Sara                                               Female     4000
6           Aradhya                                            Female     3500
7           Tom                                                Male       5500
8           Mary                                               Female     5000
9           Ben                                                Male       6500
10          Jodi                                               Female     7000
11          Tom                                                Male       5500
12          Ron                                                Male       5000

So let me execute different scenarios and see how data is impacted and I'll come from difficult syntax to simple one

Select *,SUM(salary) Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6           Aradhya                                            Female     3500        3500
5           Sara                                               Female     4000        7500
2           John                                               Male       4500        12000
3           Pavan                                              Male       5000        32000
1           Mark                                               Male       5000        32000
8           Mary                                               Female     5000        32000
12          Ron                                                Male       5000        32000
11          Tom                                                Male       5500        48500
7           Tom                                                Male       5500        48500
4           Pam                                                Female     5500        48500
9           Ben                                                Male       6500        55000
10          Jodi                                               Female     7000        62000

Just observe the sum_sal part. Here I am using order by Salary and using "RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW". In this case, we are not using partition so entire data will be treated as one partition and we are ordering on salary. And the important thing here is UNBOUNDED PRECEDING AND CURRENT ROW. This means when we are calculating the sum, from starting row to the current row for each row. But if we see rows with salary 5000 and name="Pavan", ideally it should be 17000 and for salary=5000 and name=Mark, it should be 22000. But as we are using RANGE and in this case, if it finds any similar elements then it considers them as the same logical group and performs an operation on them and assigns value to each item in that group. That is the reason why we have the same value for salary=5000. The engine went up to salary=5000 and Name=Ron and calculated sum and then assigned it to all salary=5000.

Select *,SUM(salary) Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees


   Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6           Aradhya                                            Female     3500        3500
5           Sara                                               Female     4000        7500
2           John                                               Male       4500        12000
3           Pavan                                              Male       5000        17000
1           Mark                                               Male       5000        22000
8           Mary                                               Female     5000        27000
12          Ron                                                Male       5000        32000
11          Tom                                                Male       5500        37500
7           Tom                                                Male       5500        43000
4           Pam                                                Female     5500        48500
9           Ben                                                Male       6500        55000
10          Jodi                                               Female     7000        62000

So with ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW The difference is for same value items instead of grouping them together, It calculates SUM from starting row to current row and it doesn't treat items with same value differently like RANGE

Select *,SUM(salary) Over(order by salary) as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6           Aradhya                                            Female     3500        3500
5           Sara                                               Female     4000        7500
2           John                                               Male       4500        12000
3           Pavan                                              Male       5000        32000
1           Mark                                               Male       5000        32000
8           Mary                                               Female     5000        32000
12          Ron                                                Male       5000        32000
11          Tom                                                Male       5500        48500
7           Tom                                                Male       5500        48500
4           Pam                                                Female     5500        48500
9           Ben                                                Male       6500        55000
10          Jodi                                               Female     7000        62000

These results are the same as

Select *, SUM(salary) Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees

That is because Over(order by salary) is just a short cut of Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) So wherever we simply specify Order by without ROWS or RANGE it is taking RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW as default.

Note: This is applicable only to Functions that actually accept RANGE/ROW. For example, ROW_NUMBER and few others don't accept RANGE/ROW and in that case, this doesn't come into the picture.

Till now we saw that Over clause with an order by is taking Range/ROWS and syntax looks something like this RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW And it is actually calculating up to the current row from the first row. But what If it wants to calculate values for the entire partition of data and have it for each column (that is from 1st row to last row). Here is the query for that

Select *,sum(salary) Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
1           Mark                                               Male       5000        62000
2           John                                               Male       4500        62000
3           Pavan                                              Male       5000        62000
4           Pam                                                Female     5500        62000
5           Sara                                               Female     4000        62000
6           Aradhya                                            Female     3500        62000
7           Tom                                                Male       5500        62000
8           Mary                                               Female     5000        62000
9           Ben                                                Male       6500        62000
10          Jodi                                               Female     7000        62000
11          Tom                                                Male       5500        62000
12          Ron                                                Male       5000        62000

Instead of CURRENT ROW, I am specifying UNBOUNDED FOLLOWING which instructs the engine to calculate till the last record of partition for each row.

Now coming to your point on what is OVER() with empty braces?

It is just a short cut for Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

Here we are indirectly specifying to treat all my resultset as a single partition and then perform calculations from the first record to the last record of each partition.

Select *,Sum(salary) Over() as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
1           Mark                                               Male       5000        62000
2           John                                               Male       4500        62000
3           Pavan                                              Male       5000        62000
4           Pam                                                Female     5500        62000
5           Sara                                               Female     4000        62000
6           Aradhya                                            Female     3500        62000
7           Tom                                                Male       5500        62000
8           Mary                                               Female     5000        62000
9           Ben                                                Male       6500        62000
10          Jodi                                               Female     7000        62000
11          Tom                                                Male       5500        62000
12          Ron                                                Male       5000        62000

I did create a video on this and if you are interested you can visit it. https://www.youtube.com/watch?v=CvVenuVUqto&t=1177s

Thanks, Pavan Kumar Aryasomayajulu HTTP://xyzcoder.github.io

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

Recently I had same problem, but on Linux Server. Database was crashed, and I recovered it from backup, based on simply copying /var/lib/mysql/* (analog mysql DATA folder in wamp). After recovery I had to create new table and got mysql error #1146. I tried to restart mysql, and it said it could not start. I checked mysql logs, and found that mysql simply had no access rigths to its DB files. I checked owner info of /var/lib/mysql/*, and got 'myuser:myuser' (myuser is me). But it should be 'mysql:adm' (so is own developer machine), so I changed owner to 'mysql:adm'. And after this mysql started normally, and I could create tables, or do any other operations.

So after moving database files or restoring from backups check access rigths for mysql.

Hope this helps...

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

How to "grep" out specific line ranges of a file

Line numbers are OK if you can guarantee the position of what you want. Over the years, my favorite flavor of this has been something like this:

sed "/First Line of Text/,/Last Line of Text/d" filename

which deletes all lines from the first matched line to the last match, including those lines.

Use sed -n with "p" instead of "d" to print those lines instead. Way more useful for me, as I usually don't know where those lines are.

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

If you use version 26 then inside dependencies version should be 1.0.1 and 3.0.1 i.e., as follows

  androidTestImplementation 'com.android.support.test:runner:1.0.1'
  androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

If you use version 27 then inside dependencies version should be 1.0.2 and 3.0.2 i.e., as follows

  androidTestImplementation 'com.android.support.test:runner:1.0.2'
  androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

TypeError: $ is not a function WordPress

Just add this:

<script>
var $ = jQuery.noConflict();
</script>

to the head tag in header.php . Or in case you want to use the dollar sign in admin area (or somewhere, where header.php is not used), right before the place you want to use the it.

(There might be some conflicts that I'm not aware of, test it and if there are, use the other solutions offered here or at the link bellow.)

Source: http://www.wpdevsolutions.com/use-the-dollar-sign-in-wordpress-instead-of-jquery/

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

For Sublime Text 3:

defaults write com.apple.LaunchServices LSHandlers -array-add '{LSHandlerContentType=public.plain-text;LSHandlerRoleAll=com.sublimetext.3;}'

See Set TextMate as the default text editor on Mac OS X for details.

JQuery .hasClass for multiple values in an if statement

You could use is() instead of hasClass():

if ($('html').is('.m320, .m768')) { ... }

afxwin.h file is missing in VC++ Express Edition

I see the question is about Express Edition, but this topic is easy to pop up in Google Search, and doesn't have a solution for other editions.

So. If you run into this problem with any VS Edition except Express, you can rerun installation and include MFC files.

Bulk Insert Correctly Quoted CSV File in SQL Server

Unfortunately SQL Server interprets the quoted comma as a delimiter. This applies to both BCP and bulk insert .

From http://msdn.microsoft.com/en-us/library/ms191485%28v=sql.100%29.aspx

If a terminator character occurs within the data, it is interpreted as a terminator, not as data, and the data after that character is interpreted as belonging to the next field or record. Therefore, choose your terminators carefully to make sure that they never appear in your data.

Example use of "continue" statement in Python?

Here's a simple example:

for letter in 'Django':    
    if letter == 'D':
        continue
    print("Current Letter: " + letter)

Output will be:

Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o

It continues to the next iteration of the loop.

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

how to change namespace of entire project?

I imagine a simple Replace in Files (Ctrl+Shift+H) will just about do the trick; simply replace namespace DemoApp with namespace MyApp. After that, build the solution and look for compile errors for unknown identifiers. Anything that fully qualified DemoApp will need to be changed to MyApp.

How to read/write arbitrary bits in C/C++

You need to shift and mask the value, so for example...

If you want to read the first two bits, you just need to mask them off like so:

int value = input & 0x3;

If you want to offset it you need to shift right N bits and then mask off the bits you want:

int value = (intput >> 1) & 0x3;

To read three bits like you asked in your question.

int value = (input >> 1) & 0x7;

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

I had to move domain, username, password from

client.ClientCredentials.UserName.UserName = domain + "\\" + username; client.ClientCredentials.UserName.Password = password

to

client.ClientCredentials.Windows.ClientCredential.UserName = username; client.ClientCredentials.Windows.ClientCredential.Password = password; client.ClientCredentials.Windows.ClientCredential.Domain = domain;

How can I make a horizontal ListView in Android?

Have you looked into the ViewFlipper component? Maybe it can help you.

http://developer.android.com/reference/android/widget/ViewFlipper.html

With this component, you can attach two or more view childs. If you add some translate animation and capture Gesture detection, you can have a nicely horizontal scroll.

Dynamically create and submit form

Its My version without jQuery, simple function can be used on fly

Function:

function post_to_url(path, params, method) {
    method = method || "post";

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

Usage:

post_to_url('fullurlpath', {
    field1:'value1',
    field2:'value2'
}, 'post');

How to iterate over each string in a list of strings and operate on it's elements

for i,j in enumerate(words): # i---index of word----j
     #now you got index of your words (present in i)
     print(i) 

how to overwrite css style

Just add

.flex-control-thumbs li {
width: auto; 
}

How does Facebook disable the browser's integrated Developer Tools?

This is actually possible since Facebook was able to do it. Well, not the actual web developer tools but the execution of Javascript in console.

See this: How does Facebook disable the browser's integrated Developer Tools?

This really wont do much though since there are other ways to bypass this type of client-side security.

When you say it is client-side, it happens outside the control of the server, so there is not much you can do about it. If you are asking why Facebook still does this, this is not really for security but to protect normal users that do not know javascript from running code (that they don't know how to read) into the console. This is common for sites that promise auto-liker service or other Facebook functionality bots after you do what they ask you to do, where in most cases, they give you a snip of javascript to run in console.

If you don't have as much users as Facebook, then I don't think there's any need to do what Facebook is doing.

Even if you disable Javascript in console, running javascript via address bar is still possible.

enter image description here

enter image description here

and if the browser disables javascript at address bar, (When you paste code to the address bar in Google Chrome, it deletes the phrase 'javascript:') pasting javascript into one of the links via inspect element is still possible.

Inspect the anchor:

enter image description here

Paste code in href:

enter image description here

enter image description here

enter image description here

Bottom line is server-side validation and security should be first, then do client-side after.

How to remove all of the data in a table using Django

Use this syntax to delete the rows also to redirect to the homepage (To avoid page load errors) :

def delete_all(self):
  Reporter.objects.all().delete()
  return HttpResponseRedirect('/')

Setting Short Value Java

In Java, integer literals are of type int by default. For some other types, you may suffix the literal with a case-insensitive letter like L, D, F to specify a long, double, or float, respectively. Note it is common practice to use uppercase letters for better readability.

The Java Language Specification does not provide the same syntactic sugar for byte or short types. Instead, you may declare it as such using explicit casting:

byte foo = (byte)0;
short bar = (short)0;

In your setLongValue(100L) method call, you don't have to necessarily include the L suffix because in this case the int literal is automatically widened to a long. This is called widening primitive conversion in the Java Language Specification.

Reset IntelliJ UI to Default

From the main menu, select File | Manage IDE Settings | Restore Default Settings.

Alternatively, press Shift twice and type Restore default settings

HTML form with side by side input fields

The default display style for a div is "block." This means that each new div will be under the prior one.

You can:

Override the flow style by using float as @Sarfraz suggests.

or

Change your html to use something other than divs for elements you want on the same line. I suggest that you just leave out the divs for the "last_name" field

<form action="/users" method="post"><div style="margin:0;padding:0">
  <div>
    <label for="username">First Name</label>
    <input id="user_first_name" name="user[first_name]" size="30" type="text" />

    <label for="name">Last Name</label>
    <input id="user_last_name" name="user[last_name]" size="30" type="text" />
  </div>
  ... rest is same

How do I do a simple 'Find and Replace" in MsSQL?

The following will find and replace a string in every database (excluding system databases) on every table on the instance you are connected to:

Simply change 'Search String' to whatever you seek and 'Replace String' with whatever you want to replace it with.

--Getting all the databases and making a cursor
DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases

DECLARE @databaseName nvarchar(1000)
--opening the cursor to move over the databases in this instance
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @databaseName   

WHILE @@FETCH_STATUS = 0   
BEGIN
    PRINT @databaseName
    --Setting up temp table for the results of our search
    DECLARE @Results TABLE(TableName nvarchar(370), RealColumnName nvarchar(370), ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @SearchStr nvarchar(100), @ReplaceStr nvarchar(100), @SearchStr2 nvarchar(110)
    SET @SearchStr = 'Search String'
    SET @ReplaceStr = 'Replace String'
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128)
    SET  @TableName = ''

    --Looping over all the tables in the database
    WHILE @TableName IS NOT NULL
    BEGIN
        DECLARE @SQL nvarchar(2000)
        SET @ColumnName = ''
        DECLARE @result NVARCHAR(256)
        SET @SQL = 'USE ' + @databaseName + '
            SELECT @result = MIN(QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME))
            FROM    [' + @databaseName + '].INFORMATION_SCHEMA.TABLES
            WHERE       TABLE_TYPE = ''BASE TABLE'' AND TABLE_CATALOG = ''' + @databaseName + '''
                AND QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME) > ''' + @TableName + '''
                AND OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME)
                                ), ''IsMSShipped''
                                ) = 0'
        EXEC master..sp_executesql @SQL, N'@result nvarchar(256) out', @result out

        SET @TableName = @result
        PRINT @TableName

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            DECLARE @ColumnResult NVARCHAR(256)
            SET @SQL = '
                SELECT @ColumnResult = MIN(QUOTENAME(COLUMN_NAME))
                FROM    [' + @databaseName + '].INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 2)
                    AND TABLE_NAME  = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 1)
                    AND DATA_TYPE IN (''char'', ''varchar'', ''nchar'', ''nvarchar'')
                    AND TABLE_CATALOG = ''' + @databaseName + '''
                    AND QUOTENAME(COLUMN_NAME) > ''' + @ColumnName + ''''
            PRINT @SQL
            EXEC master..sp_executesql @SQL, N'@ColumnResult nvarchar(256) out', @ColumnResult out
            SET @ColumnName = @ColumnResult 

            PRINT @ColumnName

            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO @Results
                EXEC
                (
                    'USE ' + @databaseName + '
                    SELECT ''' + @TableName + ''',''' + @ColumnName + ''',''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END
    END

    --Declaring another temporary table
    DECLARE @time_to_update TABLE(TableName nvarchar(370), RealColumnName nvarchar(370))

    INSERT INTO @time_to_update
    SELECT TableName, RealColumnName FROM @Results GROUP BY TableName, RealColumnName

    DECLARE @MyCursor CURSOR;
    BEGIN
        DECLARE @t nvarchar(370)
        DECLARE @c nvarchar(370)
        --Looping over the search results   
        SET @MyCursor = CURSOR FOR
        SELECT TableName, RealColumnName FROM @time_to_update GROUP BY TableName, RealColumnName

        --Getting my variables from the first item
        OPEN @MyCursor 
        FETCH NEXT FROM @MyCursor 
        INTO @t, @c

        WHILE @@FETCH_STATUS = 0
        BEGIN
            -- Updating the old values with the new value
            DECLARE @sqlCommand varchar(1000)
            SET @sqlCommand = '
                USE ' + @databaseName + '
                UPDATE [' + @databaseName + '].' + @t + ' SET ' + @c + ' = REPLACE(' + @c + ', ''' + @SearchStr + ''', ''' + @ReplaceStr + ''') 
                WHERE ' + @c + ' LIKE ''' + @SearchStr2 + ''''
            PRINT @sqlCommand
            BEGIN TRY
                EXEC (@sqlCommand)
            END TRY
            BEGIN CATCH
                PRINT ERROR_MESSAGE()
            END CATCH

            --Getting next row values
            FETCH NEXT FROM @MyCursor 
            INTO @t, @c 
        END;

        CLOSE @MyCursor ;
        DEALLOCATE @MyCursor;
    END;

    DELETE FROM @time_to_update
    DELETE FROM @Results

    FETCH NEXT FROM db_cursor INTO @databaseName
END   

CLOSE db_cursor   
DEALLOCATE db_cursor

Note: this isn't ideal, nor is it optimized

Change class on mouseover in directive

I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.

.directive('hoverClass', function () {
    return {
        restrict: 'A',
        scope: {
            hoverClass: '@'
        },
        link: function (scope, element) {
            element.on('mouseenter', function() {
                element.addClass(scope.hoverClass);
            });
            element.on('mouseleave', function() {
                element.removeClass(scope.hoverClass);
            });
        }
    };
})

then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:

<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
                index="{{$index}}"><i class="{{item.icon}}"
                box="course-{{$index}}"></i></li>

This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work

<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
 data-ng-controller ="CourseItemController"
 data-ng-class="{ selected: isSelected }">

providing of course that the li's are infact children of the parent div

How to drop all tables in a SQL Server database?

Short and sweet:

USE YOUR_DATABASE_NAME
-- Disable all referential integrity constraints
EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

-- Drop all PKs and FKs
declare @sql nvarchar(max)
SELECT @sql = STUFF((SELECT '; ' + 'ALTER TABLE ' + Table_Name  +'  drop constraint ' + Constraint_Name  from Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
EXECUTE (@sql)
GO

-- Drop all tables
EXEC sp_MSforeachtable 'DROP TABLE ?'
GO

What is getattr() exactly and how do I use it?

I have tried in Python2.7.17

Some of the fellow folks already answered. However I have tried to call getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.

Example Code:

Example 1:

    class GETATT_VERIFY():
       name = "siva"
       def __init__(self):
           print "Ok"
       def set_value(self):
           self.value = "myself"
           print "oooh"
    obj = GETATT_VERIFY()
    print getattr(GETATT_VERIFY, 'name')
    getattr(obj, 'set_value')()
    print obj.value

Php artisan make:auth command is not defined

In the Laravel 6 application the make:auth command no longer exists.

Laravel UI is a new first-party package that extracts the UI portion of a Laravel project into a separate laravel/ui package. The separate package enables the Laravel team to iterate on the UI package separately from the main Laravel codebase.

You can install the laravel/ui package via composer:

composer require laravel/ui

The ui:auth Command

Besides the new ui command, the laravel/ui package comes with another command for generating the auth scaffolding:

php artisan ui:auth

If you run the ui:auth command, it will generate the auth routes, a HomeController, auth views, and a app.blade.php layout file.


If you want to generate the views alone, type the following command instead:

php artisan ui:auth --views

If you want to generate the auth scaffolding at the same time:

php artisan ui vue --auth
php artisan ui react --auth

php artisan ui vue --auth command will create all of the views you need for authentication and place them in the resources/views/auth directory

The ui command will also create a resources/views/layouts directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.

More detail follow. laravel-news & documentation

Simply you've to follow this two-step.

composer require laravel/ui
php artisan ui:auth

How do I keep Python print from adding newlines or spaces?

Greg is right-- you can use sys.stdout.write

Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then

lst = ['h', 'm']
print  "".join(lst)

Processing $http response in service

Related to this I went through a similar problem, but not with get or post made by Angular but with an extension made by a 3rd party (in my case Chrome Extension).
The problem that I faced is that the Chrome Extension won't return then() so I was unable to do it the way in the solution above but the result is still Asynchronous.
So my solution is to create a service and to proceed to a callback

app.service('cookieInfoService', function() {
    this.getInfo = function(callback) {
        var model = {};
        chrome.cookies.get({url:serverUrl, name:'userId'}, function (response) {
            model.response= response;
            callback(model);
        });
    };
});

Then in my controller

app.controller("MyCtrl", function ($scope, cookieInfoService) {
    cookieInfoService.getInfo(function (info) {
        console.log(info);
    });
});

Hope this can help others getting the same issue.

Is there a shortcut to make a block comment in Xcode?

Now with xCode 8 you can do:

? + ? + /

to auto-generate a doc comment.

Source: https://twitter.com/felix_schwarz/status/774166330161233920

How can you use optional parameters in C#?

For just in case if someone wants to pass a callback (or delegate) as an optional parameter, can do it this way.

Optional Callback parameter:

public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
{
    var isOnlyOne = lst.Count == 1;
    if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
    if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
    return isOnlyOne;
}

How do I center a Bootstrap div with a 'spanX' class?

Incidentally, if your span class is even-numbered (e.g. span8) you can add an offset class to center it – for span8 that would be offset2 (assuming the default 12-column grid), for span6 it would be offset3 and so on (basically, half the number of remaining columns if you subtract the span-number from the total number of columns in the grid).

UPDATE Bootstrap 3 renamed a lot of classes so all the span*classes should be col-md-* and the offset classes should be col-md-offset-*, assuming you're using the medium-sized responsive grid.

I created a quick demo here, hope it helps: http://codepen.io/anon/pen/BEyHd.

How can I check if a jQuery plugin is loaded?

This sort of approach should work.

var plugin_exists = true;

try {
  // some code that requires that plugin here
} catch(err) {
  plugin_exists = false;
}

Change multiple files

I'm using find for similar task. It is quite simple: you have to pass it as an argument for sed like this:

sed -i 's/EXPRESSION/REPLACEMENT/g' `find -name "FILE.REGEX"`

This way you don't have to write complex loops, and it is simple to see, which files you are going to change, just run find before you run sed.

iPhone X / 8 / 8 Plus CSS media queries

If your page is missing meta[@name="viewport"] element within its DOM, then the following could be used to detect a mobile device:

@media only screen and (width: 980px), (hover: none) { … }

If you want to avoid false-positives with desktops that just magically have their viewport set to 980px like all the mobile browsers do, then a device-width test could also be added into the mix:

@media only screen and (max-device-width: 800px) and (width: 980px), (hover: none) { … }

Per the list at https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries, the new hover property would appear to be the final new way to detect that you've got yourself a mobile device that doesn't really do proper hover; it's only been introduced in 2018 with Firefox 64 (2018), although it's been supported since 2016 with Android Chrome 50 (2016), or even since 2014 with Chrome 38 (2014):

MySQL config file location - redhat linux server

Just found it, it is /etc/my.cnf

How can I convert this foreach code to Parallel.ForEach?

For big file use the following code (you are less memory hungry)

Parallel.ForEach(File.ReadLines(txtProxyListPath.Text), line => {
    //Your stuff
});

Connect to SQL Server Database from PowerShell

I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.

Android ACTION_IMAGE_CAPTURE Intent

I had the same problem where the OK button in camera app did nothing, both on emulator and on nexus one.

The problem went away after specifying a safe filename that is without white spaces, without special characters, in MediaStore.EXTRA_OUTPUT Also, if you are specifying a file that resides in a directory that has not yet been created, you have to create it first. Camera app doesn't do mkdir for you.

Padding between ActionBar's home icon and title

Im using a custom image instead of the default title text to the right of my apps logo. This is set up programatically like

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayUseLogoEnabled(true);
    actionBar.setCustomView(R.layout.include_ab_txt_logo);
    actionBar.setDisplayShowCustomEnabled(true);

The issues with the above answers for me are @Cliffus's suggestion does not work for me due to the issues others have outlined in the comments and while @dushyanth programatic padding setting may have worked in the past I would think that the fact that the spacing is now set using android:layout_marginEnd="8dip" since API 17 manually setting the padding should have no effect. See the link he posted to git to verify its current state.

A simple solution for me is to set a negative margin on my custom view in the actionBar, like so android:layout_marginLeft="-14dp". A quick test shows it works for me on 2.3.3 and 4.3 using ActionBarCompat

Hope this helps someone!

Switch php versions on commandline ubuntu 16.04

Type given command in your terminal..

For disable the selected PHP version...

    • sudo a2dismod php5
    • sudo service apache2 restart
  1. For enable other PHP version....

    • sudo a2enmod php5.6
    • sudo service apache2 restart

It will upgrade Php version, same thing reverse if you want version downgrade, you can see it by PHP_INFO();

The CSRF token is invalid. Please try to resubmit the form

Before your </form> tag put:

{{ form_rest(form) }}

It will automatically insert other important (hidden) inputs.

Mocking HttpClient in unit tests

This is a common question, and I was heavily on the side wanting the ability to mock HttpClient, but I think I finally came to the realization that you shouldn't be mocking HttpClient. It seems logical to do so, but I think we've been brainwashed by things we see in open source libraries.

We often see "Clients" out there that we mock in our code so that we can test in isolation, so we automatically try to apply the same principle to HttpClient. HttpClient actually does a lot; you can think of it as a manager for HttpMessageHandler, so you don't wanna mock that, and that's why it still doesn't have an interface. The part that you're really interested in for unit testing, or designing your services, even, is the HttpMessageHandler since that is what returns the response, and you can mock that.

It's also worth pointing out that you should probably start treating HttpClient like a bigger deal. For example: Keep your instatiating of new HttpClients to a minimum. Reuse them, they're designed to be reused and use a crap ton less resources if you do. If you start treating it like a bigger deal, it'll feel much more wrong wanting to mock it and now the message handler will start to be the thing that you're injecting, not the client.

In other words, design your dependencies around the handler instead of the client. Even better, abstract "services" that use HttpClient which allow you to inject a handler, and use that as your injectable dependency instead. Then in your tests, you can fake the handler to control the response for setting up your tests.

Wrapping HttpClient is an insane waste of time.

Update: See Joshua Dooms's example. It's exactly what I'm recommending.

CSS, Images, JS not loading in IIS

I had the same problem, an unauthenticated page would not load the CSS, JS and Images when I installed my web application in ASP.Net 4.5 in IIS 8.5 on Windows Server 2012 R2.

  1. I had the static content role installed
  2. My Web Application was in the wwwroot folder of IIS and all the Windows Folder permissions were intact (the default ones, including IIS_IUSRS)
  3. I added authorization for all the folders that contained the CSS, JS and images.
  4. I had the web application folder on a windows share, so I removed the sharing as suggested by @imran-rashid

Yet, nothing seemed to solved the problem. Then finally I tried setting the identity of the anonymous user to the App Pool Identity and it started working.

Click on the Authentication Feature Edit the Anonymous Authentication Change to App Pool Identity

I banged my head for a few hours and hope that this response will save the agony for my fellow developers.

I would really like to know why this is working. Any thoughts?

Capture screenshot of active window?

A little tweak to method static void ImageSave() will grant you the option where to save it. Credit goes to Microsoft (http://msdn.microsoft.com/en-us/library/sfezx97z.aspx)

static void ImageSave(string filename, ImageFormat format, Image image, SaveFileDialog saveFileDialog1)
    { 
        saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
        saveFileDialog1.Title = "Enregistrer un image";
        saveFileDialog1.ShowDialog();

        // If the file name is not an empty string open it for saving.
        if (saveFileDialog1.FileName != "")
        {
            // Saves the Image via a FileStream created by the OpenFile method.
            System.IO.FileStream fs =
               (System.IO.FileStream)saveFileDialog1.OpenFile();
            // Saves the Image in the appropriate ImageFormat based upon the
            // File type selected in the dialog box.
            // NOTE that the FilterIndex property is one-based.
            switch (saveFileDialog1.FilterIndex)
            {
                case 1:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;

                case 2:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Bmp);
                    break;

                case 3:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Gif);
                    break;
            }

            fs.Close();
        }



    }

Your button_click event should be coded something like this...

private void btnScreenShot_Click(object sender, EventArgs e)
    {

        SaveFileDialog saveFileDialog1 = new SaveFileDialog();


        ScreenCapturer.CaptureAndSave(filename, mode, format, saveFileDialog1);

    }//

R: Select values from data table in range

One should also consider another intuitive way to do this using filter() from dplyr. Here are some examples:

set.seed(123)
df <- data.frame(name = sample(letters, 100, TRUE),
                 date = sample(1:500, 100, TRUE))
library(dplyr)
filter(df, date < 50) # date less than 50
filter(df, date %in% 50:100) # date between 50 and 100
filter(df, date %in% 1:50 & name == "r") # date between 1 and 50 AND name is "r"
filter(df, date %in% 1:50 | name == "r") # date between 1 and 50 OR name is "r"

# You can also use the pipe (%>%) operator
df %>% filter(date %in% 1:50 | name == "r")

How to Replace Multiple Characters in SQL?

declare @testVal varchar(20)

set @testVal = '?t/es?ti/n*g 1*2?3*'

select @testVal = REPLACE(@testVal, item, '') from (select '?' item union select '*' union select '/') list

select @testVal;

T-SQL: Opposite to string concatenation - how to split string into multiple records

SELECT substring(commaSeparatedTags,0,charindex(',',commaSeparatedTags))

will give you the first tag. You can proceed similarly to get the second one and so on by combining substring and charindex one layer deeper each time. That's an immediate solution but it works only with very few tags as the query grows very quickly in size and becomes unreadable. Move on to functions then, as outlined in other, more sophisticated answers to this post.

Converting map to struct

The simplest way would be to use https://github.com/mitchellh/mapstructure

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

If you want to do it yourself, you could do something like this:

http://play.golang.org/p/tN8mxT_V9h

func SetField(obj interface{}, name string, value interface{}) error {
    structValue := reflect.ValueOf(obj).Elem()
    structFieldValue := structValue.FieldByName(name)

    if !structFieldValue.IsValid() {
        return fmt.Errorf("No such field: %s in obj", name)
    }

    if !structFieldValue.CanSet() {
        return fmt.Errorf("Cannot set %s field value", name)
    }

    structFieldType := structFieldValue.Type()
    val := reflect.ValueOf(value)
    if structFieldType != val.Type() {
        return errors.New("Provided value type didn't match obj field type")
    }

    structFieldValue.Set(val)
    return nil
}

type MyStruct struct {
    Name string
    Age  int64
}

func (s *MyStruct) FillStruct(m map[string]interface{}) error {
    for k, v := range m {
        err := SetField(s, k, v)
        if err != nil {
            return err
        }
    }
    return nil
}

func main() {
    myData := make(map[string]interface{})
    myData["Name"] = "Tony"
    myData["Age"] = int64(23)

    result := &MyStruct{}
    err := result.FillStruct(myData)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(result)
}

SELECT last id, without INSERT

In MySQL, this does return the highest value from the id column:

SELECT MAX(id) FROM tablename;

However, this does not put that id into $n:

$n = mysql_query("SELECT max(id) FROM tablename");

To get the value, you need to do this:

$result = mysql_query("SELECT max(id) FROM tablename");

if (!$result) {
    die('Could not query:' . mysql_error());
}

$id = mysql_result($result, 0, 'id');

If you want to get the last insert ID from A, and insert it into B, you can do it with one command:

INSERT INTO B (col) SELECT MAX(id) FROM A;

Check if string begins with something?

A little more reusable function:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

Prevent div from moving while resizing the page

1 - remove the margin from your BODY CSS.

2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>

3 - Define the CSS for the wrapper:

This will hold everything together, centered on the page.

#wrapper {
    margin-left:auto;
    margin-right:auto;
    width:960px;
}

Angular 5 Button Submit On Enter Key Press

In addition to other answers which helped me, you can also add to surrounding div. In my case this was for sign on with user Name/Password fields.

<div (keyup.enter)="login()" class="container-fluid">

Leaflet changing Marker color

A cheap way to change the Leaflet marker colour is to use the CSS filter property. Give the icon an extra class and then change its colour in the stylesheet:

<style>
img.huechange { filter: hue-rotate(120deg); }
</style>
<script>
var marker = L.marker([y, x]).addTo(map);
marker._icon.classList.add("huechange");
</script>

and this will produce a red marker: alter the value given to hue-rotate to alter the colour.

enter image description here

ImportError: No module named xlsxwriter

I have the same issue. It seems that pip is the problem. Try

pip uninstall xlsxwriter
easy_install xlsxwriter

Django - filtering on foreign key properties

This has been possible since the queryset-refactor branch landed pre-1.0. Ticket 4088 exposed the problem. This should work:

Asset.objects.filter(
    desc__contains=filter,
    project__name__contains="Foo").order_by("desc")

The Django Many-to-one documentation has this and other examples of following Foreign Keys using the Model API.

Getting Textbox value in Javascript

This is because ASP.NET it changing the Id of your textbox, if you run your page, and do a view source, you will see the text box id is something like

ctl00_ContentColumn_txt_model_code

There are a few ways round this:

Use the actual control name:

var TestVar = document.getElementById('ctl00_ContentColumn_txt_model_code').value;

use the ClientID property within ASP script tags

document.getElementById('<%= txt_model_code.ClientID %>').value;

Or if you are running .NET 4 you can use the new ClientIdMode property, see this link for more details.

http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx1

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

How do you reindex an array in PHP but with indexes starting from 1?

Why reindexing? Just add 1 to the index:

foreach ($array as $key => $val) {
    echo $key + 1, '<br>';
}

Edit   After the question has been clarified: You could use the array_values to reset the index starting at 0. Then you could use the algorithm above if you just want printed elements to start at 1.

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

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

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

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

Text Progress Bar in the Console

https://pypi.python.org/pypi/progressbar2/3.30.2

Progressbar2 is a good library for ascii base progressbar for the command line import time import progressbar

bar = progressbar.ProgressBar()
for i in bar(range(100)):
    time.sleep(0.02)
bar.finish()

https://pypi.python.org/pypi/tqdm

tqdm is a alternative of progressbar2 and i think it use in pip3 but i am not sure of that

from tqdm import tqdm
for i in tqdm(range(10000)):
...

Remove part of a string

You can use a built-in for this, strsplit:

> s = "TGAS_1121"
> s1 = unlist(strsplit(s, split='_', fixed=TRUE))[2]
> s1    
 [1] "1121"

strsplit returns both pieces of the string parsed on the split parameter as a list. That's probably not what you want, so wrap the call in unlist, then index that array so that only the second of the two elements in the vector are returned.

Finally, the fixed parameter should be set to TRUE to indicate that the split parameter is not a regular expression, but a literal matching character.

How to get all Windows service names starting with a common word?

sc queryex type= service state= all | find /i "NATION"
  • use /i for case insensitive search
  • the white space after type=is deliberate and required

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

Answer for BigDecimal throws ArithmeticException

public static void main(String[] args) {
        int age = 30;
        BigDecimal retireMentFund = new BigDecimal("10000.00");
        retireMentFund.setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal yearsInRetirement = new BigDecimal("20.00");
        String name = " Dennis";
        for ( int i = age; i <=65; i++){
            recalculate(retireMentFund,new BigDecimal("0.10"));
        }
        BigDecimal monthlyPension =   retireMentFund.divide(
                yearsInRetirement.divide(new BigDecimal("12"), new MathContext(2, RoundingMode.CEILING)), new MathContext(2, RoundingMode.CEILING));      
        System.out.println(name+ " will have £" + monthlyPension +" per month for retirement");
    }
public static void recalculate (BigDecimal fundAmount, BigDecimal rate){
        fundAmount.multiply(rate.add(new BigDecimal("1.00")));
    }

Add MathContext object in your divide method call and adjust precision and rounding mode. This should fix your problem

Sorting HashMap by values

found a solution but not sure the performance if the map has large size, useful for normal case.

   /**
     * sort HashMap<String, CustomData> by value
     * CustomData needs to provide compareTo() for comparing CustomData
     * @param map
     */

    public void sortHashMapByValue(final HashMap<String, CustomData> map) {
        ArrayList<String> keys = new ArrayList<String>();
        keys.addAll(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String lhs, String rhs) {
                CustomData val1 = map.get(lhs);
                CustomData val2 = map.get(rhs);
                if (val1 == null) {
                    return (val2 != null) ? 1 : 0;
                } else if (val1 != null) && (val2 != null)) {
                    return = val1.compareTo(val2);
                }
                else {
                    return 0;
                }
            }
        });

        for (String key : keys) {
            CustomData c = map.get(key);
            if (c != null) {
                Log.e("key:"+key+", CustomData:"+c.toString());
            } 
        }
    }

String concatenation: concat() vs "+" operator

The + operator can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.

The concat operator can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.

Except this, the code you provided does the same stuff.

How to get first record in each group using Linq

The awnser of @Alireza is totally correct, but you must notice that when using this code

var res = from element in list
          group element by element.F1
              into groups
              select groups.OrderBy(p => p.F2).First();

which is simillar to this code because you ordering the list and then do the grouping so you are getting the first row of groups

var res = (from element in list)
          .OrderBy(x => x.F2)
          .GroupBy(x => x.F1)
          .Select()

Now if you want to do something more complex like take the same grouping result but take the first element of F2 and the last element of F3 or something more custom you can do it by studing the code bellow

 var res = (from element in list)
          .GroupBy(x => x.F1)
          .Select(y => new
           {
             F1 = y.FirstOrDefault().F1;
             F2 = y.First().F2;
             F3 = y.Last().F3;
           });

So you will get something like

   F1            F2             F3 
 -----------------------------------
   Nima          1990           12
   John          2001           2
   Sara          2010           4

How to use onBlur event on Angular2?

This is the proposed answer on the Github repo:

// example without validators
const c = new FormControl('', { updateOn: 'blur' });

// example with validators
const c= new FormControl('', {
   validators: Validators.required,
   updateOn: 'blur'
});

Github : feat(forms): add updateOn blur option to FormControls

JavaScript error: "is not a function"

For more generic advice on debugging this kind of problem MDN have a good article TypeError: "x" is not a function:

It was attempted to call a value like a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript objects have no map function, but JavaScript Array object do.

Basically the object (all functions in js are also objects) does not exist where you think it does. This could be for numerous reasons including(not an extensive list):

  • Missing script library
  • Typo
  • The function is within a scope that you currently do not have access to, e.g.:

_x000D_
_x000D_
var x = function(){_x000D_
   var y = function() {_x000D_
      alert('fired y');_x000D_
   }_x000D_
};_x000D_
    _x000D_
//the global scope can't access y because it is closed over in x and not exposed_x000D_
//y is not a function err triggered_x000D_
x.y();
_x000D_
_x000D_
_x000D_

  • Your object/function does not have the function your calling:

_x000D_
_x000D_
var x = function(){_x000D_
   var y = function() {_x000D_
      alert('fired y');_x000D_
   }_x000D_
};_x000D_
    _x000D_
//z is not a function error (as above) triggered_x000D_
x.z();
_x000D_
_x000D_
_x000D_

Git: copy all files in a directory from another branch

As you are not trying to move the files around in the tree, you should be able to just checkout the directory:

git checkout master -- dirname

Create a zip file and download it

but the file i am getting from server after download it gives the size of 226 bytes

This is the size of a ZIP header. Apparently there is no data in the downloaded ZIP file. So, can you verify that the files to be added into the ZIP file are, indeed, there (relative to the path of the download PHP script)?

Consider adding a check on addFile too:

foreach($file_names as $file)
{
    $inputFile = $file_path . $file;
    if (!file_exists($inputFile))
        trigger_error("The input file $inputFile does not exist", E_USER_ERROR);
    if (!is_readable($inputFile))
        trigger_error("The input file $inputFile exists, but has wrong permissions or ownership", E_USER_ERROR);
    if (!$zip->addFile($inputFile, $file))
        trigger_error("Could not add $inputFile to ZIP file", E_USER_ERROR);
}

The observed behaviour is consistent with some problem (path error, permission problems, ...) preventing the files from being added to the ZIP file. On receiving an "empty" ZIP file, the client issues an error referring to the ZIP central directory missing (the actual error being that there is no directory, and no files).

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

On my Mac r is installed in /usr/local/bin/r, add line below in .bash_profile solved the same problem:

alias r="LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 r"

php & mysql query not echoing in html with tags?

<td class="first"> <?php echo $proxy ?> </td> is inside a literal string that you are echoing. End the string, or concatenate it correctly:

<td class="first">' . $proxy . '</td>

How to simulate target="_blank" in JavaScript

<script>
    window.open('http://www.example.com?ReportID=1', '_blank');
</script>

The second parameter is optional and is the name of the target window.

jQuery ui datepicker with Angularjs

I finally was able to run datepicker directive in angular js , here are pointers

include following JS in order

  1. jquery.js
  2. jquery-ui.js
  3. angular-min.js

I added the following

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"> </script>      

in html code

<body ng-app="myApp" ng-controller="myController">
// some other html code 
<input type="text" ng-model="date" mydatepicker />
<br/>
 {{ date }}
 //some other html code
 </body>

in the js , make sure you code for the directive first and after that add the code for controller , else it will cause issues.

date picker directive :

var app = angular.module('myApp',[]);
app.directive('mydatepicker', function () {
return {
    restrict: 'A',
    require: 'ngModel',
     link: function (scope, element, attrs, ngModelCtrl) {
        element.datepicker({
            dateFormat: 'DD, d  MM, yy',
            onSelect: function (date) {
                scope.date = date;
                scope.$apply();
            }
        });
    }
  };
});

directive code referred from above answers.

After this directive , write the controller

app.controller('myController',function($scope){
//controller code
};

TRY THIS INSTEAD in angular js

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>  

along with jquery.js and jquery-ui.js

we can implement angular js datepicker as

<input type="date" ng-model="date" name="DOB">

This gives the built in datepicker and date is set in ng-model and can be used for further processing and validation.

Found this after lot of successful headbanging with previous approach. :)

How to pass value from <option><select> to form action

with jQuery :
html :

<form method="POST" name="myform" action="index.php?action=contact_agent&agent_id="  onsubmit="SetData()">
  <select name="agent" id="agent">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

jQuery :

$('form').submit(function(){
   $(this).attr('action',$(this).attr('action')+$('#agent').val());
   $(this).submit();
});

javascript :

function SetData(){
   var select = document.getElementById('agent');
   var agent_id = select.options[select.selectedIndex].value;
   document.myform.action = "index.php?action=contact_agent&agent_id="+agent_id ; # or .getAttribute('action')
   myform.submit();
}

How do you clear your Visual Studio cache on Windows Vista?

The accepted answer gave two locations:

here

C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache

and possibly here

C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache

Did you try those?

Edited to add

On my Windows Vista machine, it's located in

%Temp%\VWDWebCache

and in

%LocalAppData%\Microsoft\WebsiteCache

From your additional information (regarding team edition) this comes from Clear Client TFS Cache:

Clear Client TFS Cache

Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.

To solve it..

For Windows Vista delete contents of this folder

%LocalAppData%\Microsoft\Team Foundation\1.0\Cache

Action Image MVC3 Razor

To add to all the Awesome work started by Luke I am posting one more that takes a css class value and treats class and alt as optional parameters (valid under ASP.NET 3.5+). This will allow more functionality but reduct the number of overloaded methods needed.

// Extension method
    public static MvcHtmlString ActionImage(this HtmlHelper html, string action,
        string controllerName, object routeValues, string imagePath, string alt = null, string cssClass = null)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);

        // build the <img> tag
        var imgBuilder = new TagBuilder("img");
        imgBuilder.MergeAttribute("src", url.Content(imagePath));
        if(alt != null)
            imgBuilder.MergeAttribute("alt", alt);
        if (cssClass != null)
            imgBuilder.MergeAttribute("class", cssClass);

        string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

        // build the <a> tag
        var anchorBuilder = new TagBuilder("a");

        anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
        anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

        return MvcHtmlString.Create(anchorHtml);
    }

JAX-WS and BASIC authentication, when user names and passwords are in a database

I think you are looking for JAX-WS authentication in application level, not HTTP basic in server level. See following complete example :

Application Authentication with JAX-WS

On the web service client site, just put your “username” and “password” into request header.

Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);

Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Username", Collections.singletonList("someUser"));
headers.put("Password", Collections.singletonList("somePass"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

On the web service server site, get the request header parameters via WebServiceContext.

@Resource
WebServiceContext wsctx;

@WebMethod
public String method() {
    MessageContext mctx = wsctx.getMessageContext();

    Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
    List userList = (List) http_headers.get("Username");
    List passList = (List) http_headers.get("Password");
    //...

How do you get the footer to stay at the bottom of a Web page?

Use CSS vh units!

Probably the most obvious and non-hacky way to go about a sticky footer would be to make use of the new css viewport units.

Take for example the following simple markup:

<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>

If the header is say 80px high and the footer is 40px high, then we can make our sticky footer with one single rule on the content div:

.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
}

Which means: let the height of the content div be at least 100% of the viewport height minus the combined heights of the header and footer.

That's it.

_x000D_
_x000D_
* {_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
header {_x000D_
    background: yellow;_x000D_
    height: 80px;_x000D_
}_x000D_
.content {_x000D_
    min-height: calc(100vh - 120px);_x000D_
    /* 80px header + 40px footer = 120px  */_x000D_
    background: pink;_x000D_
}_x000D_
footer {_x000D_
    height: 40px;_x000D_
    background: aqua;_x000D_
}
_x000D_
<header>header goes here</header>_x000D_
<div class="content">This page has little content</div>_x000D_
<footer>This is my footer</footer>
_x000D_
_x000D_
_x000D_

... and here's how the same code works with lots of content in the content div:

_x000D_
_x000D_
* {_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
header {_x000D_
    background: yellow;_x000D_
    height: 80px;_x000D_
}_x000D_
.content {_x000D_
    min-height: calc(100vh - 120px);_x000D_
    /* 80px header + 40px footer = 120px  */_x000D_
    background: pink;_x000D_
}_x000D_
footer {_x000D_
    height: 40px;_x000D_
    background: aqua;_x000D_
}
_x000D_
<header>header goes here</header>_x000D_
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum._x000D_
</div>_x000D_
<footer>_x000D_
    This is my footer_x000D_
</footer>
_x000D_
_x000D_
_x000D_

NB:

1) The height of the header and footer must be known

2) Old versions of IE (IE8-) and Android (4.4-) don't support viewport units. (caniuse)

3) Once upon a time webkit had a problem with viewport units within a calc rule. This has indeed been fixed (see here) so there's no problem there. However if you're looking to avoid using calc for some reason you can get around that using negative margins and padding with box-sizing -

Like so:

_x000D_
_x000D_
* {_x000D_
    margin:0;padding:0;_x000D_
}_x000D_
header {_x000D_
    background: yellow;_x000D_
    height: 80px;_x000D_
    position:relative;_x000D_
}_x000D_
.content {_x000D_
    min-height: 100vh;_x000D_
    background: pink;_x000D_
    margin: -80px 0 -40px;_x000D_
    padding: 80px 0 40px;_x000D_
    box-sizing:border-box;_x000D_
}_x000D_
footer {_x000D_
    height: 40px;_x000D_
    background: aqua;_x000D_
}
_x000D_
<header>header goes here</header>_x000D_
<div class="content">Lorem ipsum _x000D_
</div>_x000D_
<footer>_x000D_
    This is my footer_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Create normal zip file programmatically

This can be done by adding a reference to System.IO.Compression and System.IO.Compression.Filesystem.

A sample createZipFile() method may look as following:

public static void createZipFile(string inputfile, string outputfile, CompressionLevel compressionlevel)
        {
            try
            {
                using (ZipArchive za = ZipFile.Open(outputfile, ZipArchiveMode.Update))
                {
                    //using the same file name as entry name
                    za.CreateEntryFromFile(inputfile, inputfile);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid input/output file.");
                Environment.Exit(-1);
            }
}

where

  • inputfile= string with the file name to be compressed (for this example, you have to add the extension)
  • outputfile= string with the destination zip file name

More details about ZipFile Class in MSDN

How can I run a html file from terminal?

For those like me, who have reached this thread because they want to serve an html file from linux terminal or want to view it using a terminal command, use these steps:-

1)If you want to view your html using a browser:-
Navigate to the directory containing the html file
If you have chrome installed, Use:-

google-chrome <filename>.html


                OR
Use:-

firefox <filename>.html

2)If you want to serve html file and view it using a browser
Navigate to the directory containing the html file
And Simply type the following on the Terminal:-

pushd <filename>.html; python3 -m http.server 9999; popd;


Then click the I.P. address 0.0.0.0:9999 OR localhost:9999 (Whatever is the result after executing the above commands). Or type on the terminal :-

firefox 0.0.0.0:9999


Using the second method, anyone else connected to the same network can also view your file by using the URL:- "0.0.0.0:9999"

PostgreSQL JOIN data from 3 tables

Maybe the following is what you are looking for:

SELECT name, pathfilename
  FROM table1
  NATURAL JOIN table2
  NATURAL JOIN table3
  WHERE name = 'John';

How to read existing text files without defining path

You could use Directory.GetCurrentDirectory:

var path = Path.Combine(Directory.GetCurrentDirectory(), "\\fileName.txt");

Which will look for the file fileName.txt in the current directory of the application.

How to compute the similarity between two text documents?

Here's a little app to get you started...

import difflib as dl

a = file('file').read()
b = file('file1').read()

sim = dl.get_close_matches

s = 0
wa = a.split()
wb = b.split()

for i in wa:
    if sim(i, wb):
        s += 1

n = float(s) / float(len(wa))
print '%d%% similarity' % int(n * 100)

Protractor : How to wait for page complete after click a button?

Depending on what you want to do, you can try:

browser.waitForAngular();

or

btnLoginEl.click().then(function() {
  // do some stuff 
}); 

to solve the promise. It would be better if you can do that in the beforeEach.

NB: I noticed that the expect() waits for the promise inside (i.e. getCurrentUrl) to be solved before comparing.

How do I get Bin Path?

You could do this

    Assembly asm = Assembly.GetExecutingAssembly();
    string path = System.IO.Path.GetDirectoryName(asm.Location);

Detect if a jQuery UI dialog box is open

jQuery dialog has an isOpen property that can be used to check if a jQuery dialog is open or not.

You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html

A warning - comparison between signed and unsigned integer expressions

At the extreme ranges, an unsigned int can become larger than an int.
Therefore, the compiler generates a warning. If you are sure that this is not a problem, feel free to cast the types to the same type so the warning disappears (use C++ cast so that they are easy to spot).

Alternatively, make the variables the same type to stop the compiler from complaining.
I mean, is it possible to have a negative padding? If so then keep it as an int. Otherwise you should probably use unsigned int and let the stream catch the situations where the user types in a negative number.

How to Display Selected Item in Bootstrap Button Dropdown Title

I had to put some the displayed javascripts above inside the "document.ready" code. Otherwise they didn't work. Probably obvious for many, but not for me. So if you're testing look at that option.

<script type="text/javascript">
$(document).ready(function(){
//rest of the javascript code here
});
</script>

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

If the problem persists probably Hyper-V on your system is corrupted, so

Go in Control Panel -> [Programs] -> [Windows Features] and completely uncheck all Hyper-V related components. Restart the system.

Enable Hyper-V again. Restart.

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

Assign a class name to <img> tag instead of write it in css file?

I think the Class on img tag is better when You use the same style in different structure on Your site. You have to decide when you write less line of CSS code and HTML is more readable.

Setting up maven dependency for SQL Server

Be careful with the answers above. sqljdbc4.jar is not distributed with under a public license which is why it is difficult to include it in a jar for runtime and distribution. See my answer below for more details and a much better solution. Your life will become much easier as mine did once I found this answer.

https://stackoverflow.com/a/30111956/3368958

Python: Differentiating between row and column vectors

row vectors are (1,0) tensor, vectors are (0, 1) tensor. if using v = np.array([[1,2,3]]), v become (0,2) tensor. Sorry, i am confused.

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

Reason for this error is that PHP does not have a list of trusted certificate authorities.

PHP 5.6 and later try to load the CAs trusted by the system automatically. Issues with that can be fixed. See http://php.net/manual/en/migration56.openssl.php for more information.

PHP 5.5 and earlier are really hard to setup correctly since you manually have to specify the CA bundle in each request context, a thing you do not want to sprinkle around your code. So I decided for my code that for PHP versions < 5.6, SSL verification simply gets disabled:

$req = new HTTP_Request2($url);
if (version_compare(PHP_VERSION, '5.6.0', '<')) {
    //correct ssl validation on php 5.5 is a pain, so disable
    $req->setConfig('ssl_verify_host', false);
    $req->setConfig('ssl_verify_peer', false);
}

Elasticsearch difference between MUST and SHOULD bool query

must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.

should means: At least one of these clauses must match, like logical OR.

Basically they are used like logical operators AND and OR. See this.

Now in a bool query:

must means: Clauses that must match for the document to be included.

should means: If these clauses match, they increase the _score; otherwise, they have no effect. They are simply used to refine the relevance score for each document.


Yes you can use multiple filters inside must.

removing html element styles via javascript

In jQuery, you can use

$(".className").attr("style","");

Take a screenshot via a Python script on Linux

From this thread:

 import os
 os.system("import -window root temp.png")

Error Message: Type or namespace definition, or end-of-file expected

This line:

public  object Hours { get; set; }}

Your have a redundand } at the end

Create a jTDS connection string

As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:

jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]

So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC, you may end up with something like this:

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t

Or, if you prefer to use getConnection(url, "sa", "s3cr3t"):

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS

EDIT: Regarding your Connection refused error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.

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

For me save_queries option was turned off so,

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

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

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

How can I print a circular structure in a JSON-like format?

function myStringify(obj, maxDeepLevel = 2) {
  if (obj === null) {
    return 'null';
  }
  if (obj === undefined) {
    return 'undefined';
  }
  if (maxDeepLevel < 0 || typeof obj !== 'object') {
    return obj.toString();
  }
  return Object
    .entries(obj)
    .map(x => x[0] + ': ' + myStringify(x[1], maxDeepLevel - 1))
    .join('\r\n');
}

Best way to select random rows PostgreSQL

Given your specifications (plus additional info in the comments),

  • You have a numeric ID column (integer numbers) with only few (or moderately few) gaps.
  • Obviously no or few write operations.
  • Your ID column has to be indexed! A primary key serves nicely.

The query below does not need a sequential scan of the big table, only an index scan.

First, get estimates for the main query:

SELECT count(*) AS ct              -- optional
     , min(id)  AS min_id
     , max(id)  AS max_id
     , max(id) - min(id) AS id_span
FROM   big;

The only possibly expensive part is the count(*) (for huge tables). Given above specifications, you don't need it. An estimate will do just fine, available at almost no cost (detailed explanation here):

SELECT reltuples AS ct FROM pg_class WHERE oid = 'schema_name.big'::regclass;

As long as ct isn't much smaller than id_span, the query will outperform other approaches.

WITH params AS (
    SELECT 1       AS min_id           -- minimum id <= current min id
         , 5100000 AS id_span          -- rounded up. (max_id - min_id + buffer)
    )
SELECT *
FROM  (
    SELECT p.min_id + trunc(random() * p.id_span)::integer AS id
    FROM   params p
          ,generate_series(1, 1100) g  -- 1000 + buffer
    GROUP  BY 1                        -- trim duplicates
    ) r
JOIN   big USING (id)
LIMIT  1000;                           -- trim surplus
  • Generate random numbers in the id space. You have "few gaps", so add 10 % (enough to easily cover the blanks) to the number of rows to retrieve.

  • Each id can be picked multiple times by chance (though very unlikely with a big id space), so group the generated numbers (or use DISTINCT).

  • Join the ids to the big table. This should be very fast with the index in place.

  • Finally trim surplus ids that have not been eaten by dupes and gaps. Every row has a completely equal chance to be picked.

Short version

You can simplify this query. The CTE in the query above is just for educational purposes:

SELECT *
FROM  (
    SELECT DISTINCT 1 + trunc(random() * 5100000)::integer AS id
    FROM   generate_series(1, 1100) g
    ) r
JOIN   big USING (id)
LIMIT  1000;

Refine with rCTE

Especially if you are not so sure about gaps and estimates.

WITH RECURSIVE random_pick AS (
   SELECT *
   FROM  (
      SELECT 1 + trunc(random() * 5100000)::int AS id
      FROM   generate_series(1, 1030)  -- 1000 + few percent - adapt to your needs
      LIMIT  1030                      -- hint for query planner
      ) r
   JOIN   big b USING (id)             -- eliminate miss

   UNION                               -- eliminate dupe
   SELECT b.*
   FROM  (
      SELECT 1 + trunc(random() * 5100000)::int AS id
      FROM   random_pick r             -- plus 3 percent - adapt to your needs
      LIMIT  999                       -- less than 1000, hint for query planner
      ) r
   JOIN   big b USING (id)             -- eliminate miss
   )
SELECT *
FROM   random_pick
LIMIT  1000;  -- actual limit

We can work with a smaller surplus in the base query. If there are too many gaps so we don't find enough rows in the first iteration, the rCTE continues to iterate with the recursive term. We still need relatively few gaps in the ID space or the recursion may run dry before the limit is reached - or we have to start with a large enough buffer which defies the purpose of optimizing performance.

Duplicates are eliminated by the UNION in the rCTE.

The outer LIMIT makes the CTE stop as soon as we have enough rows.

This query is carefully drafted to use the available index, generate actually random rows and not stop until we fulfill the limit (unless the recursion runs dry). There are a number of pitfalls here if you are going to rewrite it.

Wrap into function

For repeated use with varying parameters:

CREATE OR REPLACE FUNCTION f_random_sample(_limit int = 1000, _gaps real = 1.03)
  RETURNS SETOF big AS
$func$
DECLARE
   _surplus  int := _limit * _gaps;
   _estimate int := (           -- get current estimate from system
      SELECT c.reltuples * _gaps
      FROM   pg_class c
      WHERE  c.oid = 'big'::regclass);
BEGIN

   RETURN QUERY
   WITH RECURSIVE random_pick AS (
      SELECT *
      FROM  (
         SELECT 1 + trunc(random() * _estimate)::int
         FROM   generate_series(1, _surplus) g
         LIMIT  _surplus           -- hint for query planner
         ) r (id)
      JOIN   big USING (id)        -- eliminate misses

      UNION                        -- eliminate dupes
      SELECT *
      FROM  (
         SELECT 1 + trunc(random() * _estimate)::int
         FROM   random_pick        -- just to make it recursive
         LIMIT  _limit             -- hint for query planner
         ) r (id)
      JOIN   big USING (id)        -- eliminate misses
   )
   SELECT *
   FROM   random_pick
   LIMIT  _limit;
END
$func$  LANGUAGE plpgsql VOLATILE ROWS 1000;

Call:

SELECT * FROM f_random_sample();
SELECT * FROM f_random_sample(500, 1.05);

You could even make this generic to work for any table: Take the name of the PK column and the table as polymorphic type and use EXECUTE ... But that's beyond the scope of this question. See:

Possible alternative

IF your requirements allow identical sets for repeated calls (and we are talking about repeated calls) I would consider a materialized view. Execute above query once and write the result to a table. Users get a quasi random selection at lightening speed. Refresh your random pick at intervals or events of your choosing.

Postgres 9.5 introduces TABLESAMPLE SYSTEM (n)

Where n is a percentage. The manual:

The BERNOULLI and SYSTEM sampling methods each accept a single argument which is the fraction of the table to sample, expressed as a percentage between 0 and 100. This argument can be any real-valued expression.

Bold emphasis mine. It's very fast, but the result is not exactly random. The manual again:

The SYSTEM method is significantly faster than the BERNOULLI method when small sampling percentages are specified, but it may return a less-random sample of the table as a result of clustering effects.

The number of rows returned can vary wildly. For our example, to get roughly 1000 rows:

SELECT * FROM big TABLESAMPLE SYSTEM ((1000 * 100) / 5100000.0);

Related:

Or install the additional module tsm_system_rows to get the number of requested rows exactly (if there are enough) and allow for the more convenient syntax:

SELECT * FROM big TABLESAMPLE SYSTEM_ROWS(1000);

See Evan's answer for details.

But that's still not exactly random.

Store images in a MongoDB database

install below libraries

var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');

connect ur mongo db :

mongoose.connect(‘url_here’);

Define database Schema

var Item = new ItemSchema({ 
    img: { 
       data: Buffer, 
       contentType: String 
    }
 }
);
var Item = mongoose.model('Clothes',ItemSchema);

using the middleware Multer to upload the photo on the server side.

app.use(multer({ dest: ‘./uploads/’,
  rename: function (fieldname, filename) {
    return filename;
  },
}));

post req to our db

app.post(‘/api/photo’,function(req,res){
  var newItem = new Item();
  newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
  newItem.img.contentType = ‘image/png’;
  newItem.save();
});

Eclipse Optimize Imports to Include Static Imports

From Content assist for static imports

To get content assist proposals for static members configure your list of favorite static members on the Opens the Favorites preference page Java > Editor > Content Assist > Favorites preference page.
For example, if you have added java.util.Arrays.* or org.junit.Assert.* to this list, then all static methods of this type matching the completion prefix will be added to the proposals list.

Open Window » Preferences » Java » Editor » Content Assist » Favorites

enter image description here

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.

We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.

Have a ViewModel for the User

public class UserViewModel
{
  public int UserID { set;get;}
  public string FirstName { set;get;}
   //add remaining properties as per your requirement

}

and in your controller have a method to get a list of Users

public class UserController : Controller
{

   [HttpGet]
   public ActionResult List()
   {
     List<UserViewModel> objList=UserService.GetUsers();  // this method should returns list of  Users
     return View("users",objList)        
   }
}

Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)

and in your users.cshtml ( which is under Views/User folder),

 @model List<UserViewModel>

 <table>

 @foreach(UserViewModel objUser in Model)
 {
   <tr>
      <td>@objUser.UserId.ToString()</td>
      <td>@objUser.FirstName</td>
   </tr>
 }
 </table>

All Set now you can access the url like yourdomain/User/List and it will give you a list of users in an HTML table.

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

How to select distinct rows in a datatable and store into an array

You can use like that:

data is DataTable

data.DefaultView.ToTable(true, "Id", "Name", "Role", "DC1", "DC2", "DC3", "DC4", "DC5", "DC6", "DC7");  

but performance will be down. try to use below code:

data.AsEnumerable().Distinct(System.Data.DataRowComparer.Default).ToList();  

For Performance ; http://onerkaya.blogspot.com/2013/01/distinct-dataviewtotable-vs-linq.html

header location not working in my php code

Try adding ob_start(); at the top of the code i.e. before the include statement.

How to update RecyclerView Adapter Data?

I strongly recommend you to use [DiffUtil.ItemCallback][1] to handle the change in RecyclerView.Adapter


 fun setData(data: List<T>) {
        val calculateDiff = DiffUtil.calculateDiff(DiffUtilCallback(items, data))
        items.clear()
        items += data
        calculateDiff.dispatchUpdatesTo(this)
    }

under the hood it handles most of the things with AdapterListUpdateCallback:

/**
 * ListUpdateCallback that dispatches update events to the given adapter.
 *
 * @see DiffUtil.DiffResult#dispatchUpdatesTo(RecyclerView.Adapter)
 */
public final class AdapterListUpdateCallback implements ListUpdateCallback {
    @NonNull
    private final RecyclerView.Adapter mAdapter;

    /**
     * Creates an AdapterListUpdateCallback that will dispatch update events to the given adapter.
     *
     * @param adapter The Adapter to send updates to.
     */
    public AdapterListUpdateCallback(@NonNull RecyclerView.Adapter adapter) {
        mAdapter = adapter;
    }

    /** {@inheritDoc} */
    @Override
    public void onInserted(int position, int count) {
        mAdapter.notifyItemRangeInserted(position, count);
    }

    /** {@inheritDoc} */
    @Override
    public void onRemoved(int position, int count) {
        mAdapter.notifyItemRangeRemoved(position, count);
    }

    /** {@inheritDoc} */
    @Override
    public void onMoved(int fromPosition, int toPosition) {
        mAdapter.notifyItemMoved(fromPosition, toPosition);
    }

    /** {@inheritDoc} */
    @Override
    public void onChanged(int position, int count, Object payload) {
        mAdapter.notifyItemRangeChanged(position, count, payload);
    }
}

Wampserver icon not going green fully, mysql services not starting up?

I was running Wamp Server for more than a year,
Now I faced a problem that I couldn't start Wamp server (The icon just stay red and the error message appear)

I managed to uninstall Wamp and reinstall it again, and so I did, but before that I copied the folder from mysql/data to my desktop then when I reinstall it I copied that files to the original location.

Then mysql just got confused... And phpmyadmin is not working so I fixed that by restoring the fresh install folder contents..
But I couldn't start mysql (the wamp servers icon still on yellow)

So after I googled a lot, I deleted every thing in the mysql/data except for:-

mysql
test
performance_schema

And my problem solved :)

How to fix error Base table or view not found: 1146 Table laravel relationship table?

The simplest thing to do is, change the default table name assigned for the model. Simply put following code, protected $table = 'category_posts'; instead of protected $table = 'posts'; then it'll do the trick.

However, if you refer Laravel documentation you'll find the answer. Here what it says,

By convention, the "snake case", plural name of the class(model) will be used as the table name unless another name is explicitly specified

Better to you use artisan command to make model and the migration file at the same time, use the following command,

php artisan make:model Test --migration

This will create a model class and a migration class in your Laravel project. Let's say it created following files,

Test.php

2018_06_22_142912_create_tests_table.php

If you look at the code in those two files you'll see,

2018_06_22_142912_create_tests_table.php files' up function,

 public function up()
 {
      Schema::create('tests', function (Blueprint $table) {
      $table->increments('id');
      $table->timestamps();
      });
 }

Here it automatically generated code with the table name of 'tests' which is the plural name of that class which is in Test.php file.

Check if a user has scrolled to the bottom

i used this test to detect the scroll reached the bottom: event.target.scrollTop === event.target.scrollHeight - event.target.offsetHeight

How to Install Sublime Text 3 using Homebrew

An update

Turns out now brew cask install sublime-text installs the most up to date version (e.g. 3) by default and brew cask is now part of the standard brew-installation.

Angular, content type is not being sent with $http

$http({
    url: 'http://localhost:8080/example/teste',
    dataType: 'json',
    method: 'POST',
    data: '',
    headers: {
        "Content-Type": "application/json"
    }

}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

Try like this.

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

The idea is that the response body gives you a page that links you to the thing:

201 Created

The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.

This means that you would include a Location in the response header that gives the URL of where you can find the newly created thing:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597

Response body

They then go on to mention what you should include in the response body:

The 201 response payload typically describes and links to the resource(s) created.

For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: text/html

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

If the page will only be used by a robot, the it makes sense to have the response be computer readable:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/xml

<createdResources>
   <questionID>1860645</questionID>
   <answerID>36373586</answerID>
   <primary>/a/36373586/12597</primary>
   <additional>
      <resource>http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586</resource>
      <resource>http://stackoverflow.com/a/1962757/12597</resource>
   </additional>
</createdResource>

Or, if you prefer:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/json

{ 
   "questionID": 1860645, 
   "answerID": 36373586,
   "primary": "/a/36373586/12597",
   "additional": [
      "http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586",
      "http://stackoverflow.com/a/36373586/12597"
   ]
}

The response is entirely up to you; it's arbitrarily what you'd like.

Cache friendly

Finally there's the optimization that I can pre-cache the created resource (because I already have the content; I just uploaded it). The server can return a date or ETag which I can store with the content I just uploaded:

See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/23704283/12597
Content-Type: text/html
ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4
Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT 

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

And ETag s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The ETag is usually a hash (e.g. SHA2). But it can be a database rowversion, or an incrementing revision number. Anything that will change when the thing changes.

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

Finding square root without using sqrt function?

After looking at the previous responses, I hope this will help resolve any ambiguities. In case the similarities in the previous solutions and my solution are illusive, or this method of solving for roots is unclear, I've also made a graph which can be found here.

This is a working root function capable of solving for any nth-root

(default is square root for the sake of this question)

#include <cmath> 
// for "pow" function

double sqrt(double A, double root = 2) {
    const double e = 2.71828182846;
    return pow(e,(pow(10.0,9.0)/root)*(1.0-(pow(A,-pow(10.0,-9.0)))));
}

Explanation:

click here for graph

This works via Taylor series, logarithmic properties, and a bit of algebra.

Take, for example:

log A = N
   x

*Note: for square-root, N = 2; for any other root you only need to change the one variable, N.

1) Change the base, convert the base 'x' log function to natural log,

log A   =>   ln(A)/ln(x) = N
   x

2) Rearrange to isolate ln(x), and eventually just 'x',

ln(A)/N = ln(x)

3) Set both sides as exponents of 'e',

e^(ln(A)/N) = e^(ln(x))  >~{ e^ln(x) == x }~>  e^(ln(A)/N) = x

4) Taylor series represents "ln" as an infinite series,

ln(x) = (k=1)Sigma: (1/k)(-1^(k+1))(k-1)^n

           <~~~ expanded ~~~>

[(x-1)] - [(1/2)(x-1)^2] + [(1/3)(x-1)^3] - [(1/4)(x-1)^4] + . . .

*Note: Continue the series for increased accuracy. For brevity, 10^9 is used in my function which expresses the series convergence for the natural log with about 7 digits, or the 10-millionths place, for precision,

ln(x) = 10^9(1-x^(-10^(-9)))

5) Now, just plug in this equation for natural log into the simplified equation obtained in step 3.

e^[((10^9)/N)(1-A^(-10^-9)] = nth-root of (A)

6) This implementation might seem like overkill; however, its purpose is to demonstrate how you can solve for roots without having to guess and check. Also, it would enable you to replace the pow function from the cmath library with your own pow function:

double power(double base, double exponent) {
    if (exponent == 0) return 1;
    int wholeInt = (int)exponent;
    double decimal = exponent - (double)wholeInt;
    if (decimal) {
        int powerInv = 1/decimal;
        if (!wholeInt) return root(base,powerInv);
        else return power(root(base,powerInv),wholeInt,true);
    }
    return power(base, exponent, true);
}

double power(double base, int exponent, bool flag) {
    if (exponent < 0) return 1/power(base,-exponent,true);
    if (exponent > 0) return base * power(base,exponent-1,true);
    else return 1;
}

int root(int A, int root) {
    return power(E,(1000000000000/root)*(1-(power(A,-0.000000000001))));
}

Python loop counter in a for loop

enumerate is what you are looking for.

You might also be interested in unpacking:

# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

Also, there is itertools.count() so you could do something like

import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

"Have you tried turning it off and on again?" (Roy of The IT crowd)

This happened to me today, which is why I ended up to this page. Seeing that error was weird since, recently, I have not made any changes in my Python environment. Interestingly, I observed that if I open a new notebook and import pandas I would not get the same error message. So, I did shutdown the troublesome notebook and started it again and voila it is working again!

Even though this solved the problem (at least for me), I cannot readily come up with an explanation as to why it happened in the first place!

What good are SQL Server schemas?

They can also provide a kind of naming collision protection for plugin data. For example, the new Change Data Capture feature in SQL Server 2008 puts the tables it uses in a separate cdc schema. This way, they don't have to worry about a naming conflict between a CDC table and a real table used in the database, and for that matter can deliberately shadow the names of the real tables.

Include CSS,javascript file in Yii Framework

To include JS and CSS files in a specific view you can do it via controller by passing the parameters false, true, which will include the CSS and JS for, e.g.:

$this->renderPartial(
    'yourviewname',
    array(
        'model' => $model,
        false,
        true
    )
);

jQuery: select an element's class and id at the same time?

How about this code?

$("a.save#country")

How to merge specific files from Git branches

Are all the modifications to file.py in branch2 in their own commits, separate from modifications to other files? If so, you can simply cherry-pick the changes over:

git checkout branch1
git cherry-pick <commit-with-changes-to-file.py>

Otherwise, merge does not operate over individual paths...you might as well just create a git diff patch of file.py changes from branch2 and git apply them to branch1:

git checkout branch2
git diff <base-commit-before-changes-to-file.py> -- file.py > my.patch
git checkout branch1
git apply my.patch

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

try to call jQuery library before bootstrap.js

<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>

How to insert multiple rows from array using CodeIgniter framework?

Multiple insert/ batch insert is now supported by CodeIgniter.

$data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name' ,
      'date' => 'My date'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name' ,
      'date' => 'Another date'
   )
);

$this->db->insert_batch('mytable', $data);

// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

'Invalid update: invalid number of rows in section 0

Swift Version --> Remove the object from your data array before you call

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        currentCart.remove(at: indexPath.row) //Remove element from your array 
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}