Programs & Examples On #Django generic views

Questions about Django’s built-in generic views, which helps you to avoid repeating common code patterns in every project.

Swift - Remove " character from string

Here is the swift 3 updated answer

var editedText = myLabel.text?.replacingOccurrences(of: "\"", with: "")
Null Character (\0)
Backslash (\\)
Horizontal Tab (\t)
Line Feed (\n)
Carriage Return (\r)
Double Quote (\")
Single Quote (\')
Unicode scalar (\u{n})

React Native: How to select the next TextInput after pressing the "next" keyboard button?

For me on RN 0.50.3 it's possible with this way:

<TextInput 
  autoFocus={true} 
  onSubmitEditing={() => {this.PasswordInputRef._root.focus()}} 
/>

<TextInput ref={input => {this.PasswordInputRef = input}} />

You must see this.PasswordInputRef._root.focus()

Namespace for [DataContract]

[DataContract] and [DataMember] attribute are found in System.ServiceModel namespace which is in System.ServiceModel.dll .

System.ServiceModel uses the System and System.Runtime.Serialization namespaces to serialize the datamembers.

Convert JSON array to an HTML table in jQuery

Converting a 2D JavaScript array to an HTML table

To turn a 2D JavaScript array into an HTML table, you really need but a little bit of code :

_x000D_
_x000D_
function arrayToTable(tableData) {_x000D_
    var table = $('<table></table>');_x000D_
    $(tableData).each(function (i, rowData) {_x000D_
        var row = $('<tr></tr>');_x000D_
        $(rowData).each(function (j, cellData) {_x000D_
            row.append($('<td>'+cellData+'</td>'));_x000D_
        });_x000D_
        table.append(row);_x000D_
    });_x000D_
    return table;_x000D_
}_x000D_
_x000D_
$('body').append(arrayToTable([_x000D_
    ["John","Slegers",34],_x000D_
    ["Tom","Stevens",25],_x000D_
    ["An","Davies",28],_x000D_
    ["Miet","Hansen",42],_x000D_
    ["Eli","Morris",18]_x000D_
]));
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


Loading a JSON file

If you want to load your 2D array from a JSON file, you'll also need a little bit of Ajax code :

$.ajax({
    type: "GET",
    url: "data.json",
    dataType: 'json',
    success: function (data) {
        $('body').append(arrayToTable(data));
    }
});

How to do tag wrapping in VS code?

Embedded Emmet could do the trick:

  1. Select text (optional)
  2. Open command palette (usually Ctrl+Shift+P)
  3. Execute Emmet: Wrap with Abbreviation
  4. Enter a tag div (or an abbreviation .wrapper>p)
  5. Hit Enter

Command can be assigned to a keybinding.

enter image description here


This thing even supports passing arguments:

{
    "key": "ctrl+shift+9",
    "command": "editor.emmet.action.wrapWithAbbreviation",
    "when": "editorHasSelection",
    "args": {
        "abbreviation": "span"
    }
},

Use it like this:

  • span.myCssClass
  • span#myCssId
  • b
  • b.myCssClass

Strtotime() doesn't work with dd/mm/YYYY format

fastest should probably be

false!== ($date !== $date=preg_replace(';[0-2]{2}/[0-2]{2}/[0-2]{2};','$3-$2-$1',$date))

this will return false if the format does not look like the proper one, but it wont-check wether the date is valid

Force “landscape” orientation mode

screen.orientation.lock('landscape');

Will force it to change to and stay in landscape mode. Tested on Nexus 5.

http://www.w3.org/TR/screen-orientation/#examples

Swift UIView background color opacity

The question is old, but it seems that there are people who have the same concerns.

What do you think of the opinion that 'the alpha property of UIColor and the opacity property of Interface Builder are applied differently in code'?


The two views created in Interface Builder were initially different colors, but had to be the same color when the conditions changed. So, I had to set the background color of one view in code, and set a different value to make the background color of both views the same.

As an actual example, the background color of Interface Builder was 0x121212 and the Opacity value was 80%(in Amani Elsaed's image :: Red: 18, Green: 18, Blue: 18, Hex Color #: [121212], Opacity: 80), In the code, I set the other view a background color of 0x121212 with an alpha value of 0.8.

self.myFuncView.backgroundColor = UIColor(red: 18, green: 18, blue: 18, alpha: 0.8)

extension is

extension UIColor {
    convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
        self.init(red: CGFloat(red) / 255.0,
                  green: CGFloat(green) / 255.0,
                  blue: CGFloat(blue) / 255.0,
                  alpha: alpha)
    }
}

However, the actual view was

  • 'View with background color specified in Interface Builder': R 0.09 G 0.09 B 0.09 alpha 0.8.
  • 'View with background color by code': R 0.07 G 0.07 B 0.07 alpha 0.8

Calculating it,

  • 0x12 = 18(decimal)
  • 18/255 = 0.07058...
  • 255 * 0.09 = 22.95
  • 23(decimal) = 0x17

So, I was able to match the colors similarly by setting the UIColor values ??to 17, 17, 17 and alpha 0.8.

self.myFuncView.backgroundColor = UIColor(red: 17, green: 17, blue: 17, alpha: 0.8)

Or can anyone tell me what I'm missing?

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

How to save password when using Subversion from the console

Please note the following paragraph from the ~/.subversion/servers file:

Both 'store-passwords' and 'store-auth-creds' can now be specified in the 'servers' file in your config directory. Anything specified in this section is overridden by settings specified in the 'servers' file.

It is at least for SVN version 1.6.12. So keep in mind to edit the servers file also as it overrides ~/.subversion/config.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

I think this is the simple answer you are looking for. It's from Shawn Wildermuth's blog:

// Add MVC services to the services container.
services.AddMvc()
  .AddJsonOptions(opts =>
  {
    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });

How can I undo a `git commit` locally and on a remote after `git push`

First of all, Relax.

"Nothing is under our control. Our control is mere illusion.", "To err is human"

I get that you've unintentionally pushed your code to remote-master. THIS is going to be alright.

1. At first, get the SHA-1 value of the commit you are trying to return, e.g. commit to master branch. run this:

git log

you'll see bunch of 'f650a9e398ad9ca606b25513bd4af9fe...' like strings along with each of the commits. copy that number from the commit that you want to return back.

2. Now, type in below command:

git reset --hard your_that_copied_string_but_without_quote_mark

you should see message like "HEAD is now at ". you are on clear. What it just have done is to reflect that change locally.

3. Now, type in below command:

git push -f

you should see like

"warning: push.default is unset; its implicit value has changed in..... ... Total 0 (delta 0), reused 0 (delta 0) ... ...your_branch_name -> master (forced update)."

Now, you are all clear. Check the master with "git log" again, your fixed_destination_commit should be on top of the list.

You are welcome (in advance ;))

UPDATE:

Now, the changes you had made before all these began, are now gone. If you want to bring those hard-works back again, it's possible. Thanks to git reflog, and git cherry-pick commands.

For that, i would suggest to please follow this blog or this post.

How to escape a single quote inside awk

For small scripts an optional way to make it readable is to use a variable like this:

awk -v fmt="'%s'\n" '{printf fmt, $1}'

I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable

Indirectly referenced from required .class file

Add spring-tx jar file and it should settle it.

Best practice to call ConfigureAwait for all server-side code

The biggest draw back I've found with using ConfigureAwait(false) is that the thread culture is reverted to the system default. If you've configured a culture e.g ...

<system.web>
    <globalization culture="en-AU" uiCulture="en-AU" />    
    ...

and you're hosting on a server whose culture is set to en-US, then you will find before ConfigureAwait(false) is called CultureInfo.CurrentCulture will return en-AU and after you will get en-US. i.e.

// CultureInfo.CurrentCulture ~ {en-AU}
await xxxx.ConfigureAwait(false);
// CultureInfo.CurrentCulture ~ {en-US}

If your application is doing anything which requires culture specific formatting of data, then you'll need to be mindful of this when using ConfigureAwait(false).

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

Am I trying to connect to a TLS-enabled daemon without TLS?

I had the same issue and tried various things to fix this, amending the .bash_profile file, logging in and out, without any luck. In the end, restarting my machine fixed it.

Getting started with Haskell

These are my favorite

Haskell: Functional Programming with Types

Joeri van Eekelen, et al. | Wikibooks
       Published in 2012, 597 pages

Real World Haskell

   B. O'Sullivan, J. Goerzen, D. Stewart | OReilly Media, Inc.
   Published in 2008, 710 pages

Create a new line in Java's FileWriter

Since 1.8, I thought this might be an additional solution worth adding to the responses:

Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException

StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());

If appending to the same file, perhaps use an Append flag with Files.write()

Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);

Extract images from PDF without resampling, in python?

I prefer minecart as it is extremely easy to use. The below snippet show how to extract images from a pdf:

#pip install minecart
import minecart

pdffile = open('Invoices.pdf', 'rb')
doc = minecart.Document(pdffile)

page = doc.get_page(0) # getting a single page

#iterating through all pages
for page in doc.iter_pages():
    im = page.images[0].as_pil()  # requires pillow
    display(im)

How to loop through an array containing objects and access their properties

_x000D_
_x000D_
const jobs = [_x000D_
    {_x000D_
        name: "sipher",_x000D_
        family: "sipherplus",_x000D_
        job: "Devops"_x000D_
    },_x000D_
    {_x000D_
        name: "john",_x000D_
        family: "Doe",_x000D_
        job: "Devops"_x000D_
    },_x000D_
    {_x000D_
        name: "jim",_x000D_
        family: "smith",_x000D_
        job: "Devops"_x000D_
    }_x000D_
];_x000D_
_x000D_
const txt = _x000D_
   ` <ul>_x000D_
        ${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}_x000D_
    </ul>`_x000D_
;_x000D_
_x000D_
document.body.innerHTML = txt;
_x000D_
_x000D_
_x000D_

Be careful about the back Ticks (`)

How to set a header for a HTTP GET request, and trigger file download?

There are two ways to download a file where the HTTP request requires that a header be set.

The credit for the first goes to @guest271314, and credit for the second goes to @dandavis.

The first method is to use the HTML5 File API to create a temporary local file, and the second is to use base64 encoding in conjunction with a data URI.

The solution I used in my project uses the base64 encoding approach for small files, or when the File API is not available, otherwise using the the File API approach.

Solution:

        var id = 123;

        var req = ic.ajax.raw({
            type: 'GET',
            url: '/api/dowloads/'+id,
            beforeSend: function (request) {
                request.setRequestHeader('token', 'token for '+id);
            },
            processData: false
        });

        var maxSizeForBase64 = 1048576; //1024 * 1024

        req.then(
            function resolve(result) {
                var str = result.response;

                var anchor = $('.vcard-hyperlink');
                var windowUrl = window.URL || window.webkitURL;
                if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
                    var blob = new Blob([result.response], { type: 'text/bin' });
                    var url = windowUrl.createObjectURL(blob);
                    anchor.prop('href', url);
                    anchor.prop('download', id+'.bin');
                    anchor.get(0).click();
                    windowUrl.revokeObjectURL(url);
                }
                else {
                    //use base64 encoding when less than set limit or file API is not available
                    anchor.attr({
                        href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
                        download: id+'.bin',
                    });
                    anchor.get(0).click();
                }

            }.bind(this),
            function reject(err) {
                console.log(err);
            }
        );

Note that I'm not using a raw XMLHttpRequest, and instead using ic-ajax, and should be quite similar to a jQuery.ajax solution.

Note also that you should substitute text/bin and .bin with whatever corresponds to the file type being downloaded.

The implementation of FormatUtils.utf8toBase64 can be found here

Process to convert simple Python script into Windows executable

You could create an installer for you EXE file by:
1. Press WinKey + R
2. Type "iexpress" (without quotes) into the run window
3. Complete the wizard for creating the installation program.
4. Distribute the completed EXE.

Download a file with Android, and showing the progress in a ProgressDialog

Important

AsyncTask is deprecated in Android 11.

For more information please checkout following posts

Probably should move to concorency Framework as suggested by google

How to return a specific status code and no contents from Controller?

If anyone wants to do this with a IHttpActionResult may be in a Web API project, Below might be helpful.

// GET: api/Default/
public IHttpActionResult Get()
{
    //return Ok();//200
    //return StatusCode(HttpStatusCode.Accepted);//202
    //return BadRequest();//400
    //return InternalServerError();//500
    //return Unauthorized();//401
    return Ok();
}

How can I take an UIImage and give it a black border?

This function will return you image with black border try this.. hope this will help you

- (UIImage *)addBorderToImage:(UIImage *)image frameImage:(UIImage *)blackBorderImage
{
    CGSize size = CGSizeMake(image.size.width,image.size.height);
    UIGraphicsBeginImageContext(size);

    CGPoint thumbPoint = CGPointMake(0,0);

    [image drawAtPoint:thumbPoint];


    UIGraphicsBeginImageContext(size);
    CGImageRef imgRef = blackBorderImage.CGImage;
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width,size.height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGPoint starredPoint = CGPointMake(0, 0);
    [imageCopy drawAtPoint:starredPoint];
    UIImage *imageC = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageC;
}

getResourceAsStream() vs FileInputStream

classname.getResourceAsStream() loads a file via the classloader of classname. If the class came from a jar file, that is where the resource will be loaded from.

FileInputStream is used to read a file from the filesystem.

How to get function parameter names/values dynamically?

How I typically do it:

function name(arg1, arg2){
    var args = arguments; // array: [arg1, arg2]
    var objecArgOne = args[0].one;
}
name({one: "1", two: "2"}, "string");

You can even ref the args by the functions name like:

name.arguments;

Hope this helps!

How to get min, seconds and milliseconds from datetime.now() in python?

import datetime from datetime

now = datetime.now()

print "%0.2d:%0.2d:%0.2d" % (now.hour, now.minute, now.second)

You can do the same with day & month etc.

Source file not compiled Dev C++

Install new version of Dev c++. It works fine in Windows 8. It also supports 64 bit version.

Download link is http://sourceforge.net/projects/orwelldevcpp/ .

Automapper missing type map configuration or unsupported mapping - Error

Where have you specified the mapping code (CreateMap)? Reference: Where do I configure AutoMapper?

If you're using the static Mapper method, configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.asax file for ASP.NET applications.

If the configuration isn't registered before calling the Map method, you will receive Missing type map configuration or unsupported mapping.

Live Video Streaming with PHP

PHP will let you build the pages of your site that make up your video conferencing and chat applications, but it won't deliver or stream video for you - PHP runs on the server only and renders out HTML to a client browser.

For the video, the first thing you'll need is a live streaming account with someone like akamai or the numerous others in the field. Using this account gives you an ingress point for your video - ie: the server that you will stream your live video up to.

Next, you want to get your video out to the browsers - windows media player, flash or silverlight will let you achieve this - embedding the appropriate control for your chosen technology into your page (using PHP or whatever) and given the address of your live video feed.

PHP (or other scripting language) would be used to build the chat part of the application and bring the whole thing together (the chat and the embedded video player).

Hope this helps.

Font-awesome, input type 'submit'

use button type="submit" instead of input

<button type="submit" class="btn btn-success">
    <i class="fa fa-arrow-circle-right fa-lg"></i> Next
</button>

for Font Awesome 3.2.0 use

<button type="submit" class="btn btn-success">
    <i class="icon-circle-arrow-right icon-large"></i> Next
</button>

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

How to auto-indent code in the Atom editor?

You could also try to add a key mapping witch auto select all the code in file and indent it:

'atom-text-editor':
  'ctrl-alt-l': 'auto-indent:apply'

Adding rows to dataset

 DataSet ds = new DataSet();

 DataTable dt = new DataTable("MyTable");
 dt.Columns.Add(new DataColumn("id",typeof(int)));
 dt.Columns.Add(new DataColumn("name", typeof(string)));

 DataRow dr = dt.NewRow();
 dr["id"] = 123;
 dr["name"] = "John";
 dt.Rows.Add(dr);
 ds.Tables.Add(dt);

Visual Studio popup: "the operation could not be completed"

Go to Run and type "inetmgr", i.e IIS is opened and in the right corner Action window, select option change ".NET Framework version". Change it.

After that, reinstall your Visual studio 2010. It works on my computer, and that's why sharing.

Extract substring from a string

substring():

str.substring(startIndex, endIndex); 

Django - Static file not found

I confused STATIC_ROOT and STATICFILES_DIRS

Actually I was not really understanding the utility of STATIC_ROOT. I thought that it was the directory on which I have to put my common files. This directory is used for the production, this is the directory on which static files will be put (collected) by collectstatic.

STATICFILES_DIRS is the one that I need.

Since I'm in a development environment, the solution for me is to not use STATIC_ROOT (or to specify another path) and set my common files directory in STATICFILES_DIRS:

#STATIC_ROOT = (os.path.join(SITE_ROOT, 'static_files/'))
import os
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATICFILES_DIRS = (
  os.path.join(SITE_ROOT, 'static/'),
)

Also don't forget to from django.conf import settings

Check if inputs form are empty jQuery

You could do it like this :

bool areFieldEmpty = YES;
//Label to leave the loops
outer_loop;

//For each input (except of submit) in your form
$('form input[type!=submit]').each(function(){
   //If the field's empty
   if($(this).val() != '')
   {
      //Mark it
      areFieldEmpty = NO;
      //Then leave all the loops
      break outer_loop;
   }
});

//Then test your bool 

How to check if a Ruby object is a Boolean

An object that is a boolean will either have a class of TrueClass or FalseClass so the following one-liner should do the trick

mybool = true
mybool.class == TrueClass || mybool.class == FalseClass
=> true

The following would also give you true/false boolean type check result

mybool = true    
[TrueClass, FalseClass].include?(mybool.class)
=> true

$(document).ready not Working

Instead of using this:

$(document).ready(function() { /* your code */ });

Use this:

jQuery(function($) { /* your code */ })(jQuery);

It is more concise and does the same thing, it also doesn't depend on the $ variable to be the jQuery object.

Save base64 string as PDF at client side with JavaScript

You will do not need any library for this. JavaScript support this already. Here is my end-to-end solution.

const xhr = new XMLHttpRequest();
xhr.open('GET', 'your-end-point', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       if (window.navigator.msSaveOrOpenBlob) {
           window.navigator.msSaveBlob(this.response, "fileName.pdf");
        } else {
           const downloadLink = window.document.createElement('a');
           const contentTypeHeader = xhr.getResponseHeader("Content-Type");
           downloadLink.href = window.URL.createObjectURL(new Blob([this.response], { type: contentTypeHeader }));
           downloadLink.download = "fileName.pdf";
           document.body.appendChild(downloadLink);
           downloadLink.click();
           document.body.removeChild(downloadLink);
        }
    }
};
xhr.send(null);

This also work for .xls or .zip file. You just need to change file name to fileName.xls or fileName.zip. This depends on your case.

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

You might want to try the full login command:

mysql -h host -u root -p 

where host would be 127.0.0.1.

Do this just to make sure cooperation exists.

Using mysql -u root -p allows me to do a a lot of database searching, but refuses any database creation due to a path setting.

Set timeout for webClient.DownloadFile()

Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:

using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
     if (stream != null)
     {
          stream.ReadTimeout = Timeout.Infinite;
          using (var reader = new StreamReader(stream, Encoding.UTF8, false))
          {
               string line;
               while ((line = reader.ReadLine()) != null)
               {
                    if (line != String.Empty)
                    {
                        Console.WriteLine("Count {0}", count++);
                    }
                    Console.WriteLine(line);
               }
          }
     }
}

Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.

Difference between / and /* in servlet mapping url pattern

The essential difference between /* and / is that a servlet with mapping /* will be selected before any servlet with an extension mapping (like *.html), while a servlet with mapping / will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").

In particular, a /* mapping will always be selected before a / mapping. Having either prevents any requests from reaching the container's own default servlet.

Either will be selected only after servlet mappings which are exact matches (like /foo/bar) and those which are path mappings longer than /* (like /foo/*). Note that the empty string mapping is an exact match for the context root (http://host:port/context/).

See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.

Android Device not recognized by adb

Go to prompt command and type "adb devices". If it is empty, then make sure you allowed for "MTP Transfer" or similar and you enabled debugging on your phone.

To enable debugging, follow this tutorial: https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm

Then type "adb devices" again. If a device is listed in there, then it should work now.

How can I get the last day of the month in C#?

Something like:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);

Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.

Passing a variable from node.js to html

I figured it out I was able to pass a variable like this

<script>var name = "<%= name %>";</script>
console.log(name);

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

what about just store the output to the static table ? Like

-- SubProcedure: subProcedureName
---------------------------------
-- Save the value
DELETE lastValue_subProcedureName
INSERT INTO lastValue_subProcedureName (Value)
SELECT @Value
-- Return the value
SELECT @Value

-- Procedure
--------------------------------------------
-- get last value of subProcedureName
SELECT Value FROM lastValue_subProcedureName

its not ideal, but its so simple and you don't need to rewrite everything.

UPDATE: the previous solution does not work well with parallel queries (async and multiuser accessing) therefore now Iam using temp tables

-- A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. 
-- The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. 
-- The table cannot be referenced by the process that called the stored procedure that created the table.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NULL
CREATE TABLE #lastValue_spGetData (Value INT)

-- trigger stored procedure with special silent parameter
EXEC dbo.spGetData 1 --silent mode parameter

nested spGetData stored procedure content

-- Save the output if temporary table exists.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NOT NULL
BEGIN
    DELETE #lastValue_spGetData
    INSERT INTO #lastValue_spGetData(Value)
    SELECT Col1 FROM dbo.Table1
END

 -- stored procedure return
 IF @silentMode = 0
 SELECT Col1 FROM dbo.Table1

A simple explanation of Naive Bayes Classification

Naive Bayes: Naive Bayes comes under supervising machine learning which used to make classifications of data sets. It is used to predict things based on its prior knowledge and independence assumptions.

They call it naive because it’s assumptions (it assumes that all of the features in the dataset are equally important and independent) are really optimistic and rarely true in most real-world applications.

It is classification algorithm which makes the decision for the unknown data set. It is based on Bayes Theorem which describe the probability of an event based on its prior knowledge.

Below diagram shows how naive Bayes works

enter image description here

Formula to predict NB:

enter image description here

How to use Naive Bayes Algorithm ?

Let's take an example of how N.B woks

Step 1: First we find out Likelihood of table which shows the probability of yes or no in below diagram. Step 2: Find the posterior probability of each class.

enter image description here

Problem: Find out the possibility of whether the player plays in Rainy condition?

P(Yes|Rainy) = P(Rainy|Yes) * P(Yes) / P(Rainy)

P(Rainy|Yes) = 2/9 = 0.222
P(Yes) = 9/14 = 0.64
P(Rainy) = 5/14 = 0.36

Now, P(Yes|Rainy) = 0.222*0.64/0.36 = 0.39 which is lower probability which means chances of the match played is low.

For more reference refer these blog.

Refer GitHub Repository Naive-Bayes-Examples

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

What is the scope of variables in JavaScript?

The key, as I understand it, is that Javascript has function level scoping vs the more common C block scoping.

Here is a good article on the subject.

How do I make a newline after a twitter bootstrap element?

Using br elements is fine, and as long as you don't need a lot of space between elements, is actually a logical thing to do as anyone can read your code and understand what spacing logic you are using.

The alternative is to create a custom class for white space. In bootstrap 4 you can use

<div class="w-100"></div>

to make a blank row across the page, but this is no different to using the <br> tag. The downside to creating a custom class for white space is that it can be a pain to read for others who view your code. A custom class would also apply the same amount of white space each time you used it, so if you wanted different amounts of white space on the same page, then you would need to create several white space classes.

In most cases, it is just easier to use <br> or <div class="w-100"></div> for the sake of ease and readability. it doesn't look pretty, but it works.

When to use RabbitMQ over Kafka?

Apache Kafka is a popular choice for powering data pipelines. Apache kafka added kafka stream to support popular etl use cases. KSQL makes it simple to transform data within the pipeline, readying messages to cleanly land in another system. KSQL is the streaming SQL engine for Apache Kafka. It provides an easy-to-use yet powerful interactive SQL interface for stream processing on Kafka, without the need to write code in a programming language such as Java or Python. KSQL is scalable, elastic, fault-tolerant, and real-time. It supports a wide range of streaming operations, including data filtering, transformations, aggregations, joins, windowing, and sessionization.

https://docs.confluent.io/current/ksql/docs/index.html

Rabbitmq is not a popular choice for etl systems rather for those systems where it requires simple messaging systems with less throughput.

LD_LIBRARY_PATH vs LIBRARY_PATH

Since I link with gcc why ld is being called, as the error message suggests?

gcc calls ld internally when it is in linking mode.

Duplicate symbols for architecture x86_64 under Xcode

Following steps solved the issue for me.

  1. Go to Build Phases in Target settings.
  2. Go to “Link Binary With Libraries”.
  3. Check if any of the libraries exist twice.
  4. Build again.

How to change Label Value using javascript

Based off your code, i created this Fiddle
You need to use

var cb = document.getElementsByName('field206451')[0];
var label = document.getElementsByName('label206451')[0];


if you want to use name attributes then you have to take the index since it is a list of items, not just a single one. Everything else worked good.

Assert a function/method was not called using Mock

Judging from other answers, no one except @rob-kennedy talked about the call_args_list.

It's a powerful tool for that you can implement the exact contrary of MagicMock.assert_called_with()

call_args_list is a list of call objects. Each call object represents a call made on a mocked callable.

>>> from unittest.mock import MagicMock
>>> m = MagicMock()
>>> m.call_args_list
[]
>>> m(42)
<MagicMock name='mock()' id='139675158423872'>
>>> m.call_args_list
[call(42)]
>>> m(42, 30)
<MagicMock name='mock()' id='139675158423872'>
>>> m.call_args_list
[call(42), call(42, 30)]

Consuming a call object is easy, since you can compare it with a tuple of length 2 where the first component is a tuple containing all the positional arguments of the related call, while the second component is a dictionary of the keyword arguments.

>>> ((42,),) in m.call_args_list
True
>>> m(42, foo='bar')
<MagicMock name='mock()' id='139675158423872'>
>>> ((42,), {'foo': 'bar'}) in m.call_args_list
True
>>> m(foo='bar')
<MagicMock name='mock()' id='139675158423872'>
>>> ((), {'foo': 'bar'}) in m.call_args_list
True

So, a way to address the specific problem of the OP is

def test_something():
    with patch('something') as my_var:
        assert ((some, args),) not in my_var.call_args_list

Note that this way, instead of just checking if a mocked callable has been called, via MagicMock.called, you can now check if it has been called with a specific set of arguments.

That's useful. Say you want to test a function that takes a list and call another function, compute(), for each of the value of the list only if they satisfy a specific condition.

You can now mock compute, and test if it has been called on some value but not on others.

C++ catching all exceptions

Well this really depends on the compiler environment. gcc does not catch these. Visual Studio and the last Borland that I used did.

So the conclusion about crashes is that it depends on the quality of your development environment.

The C++ specification says that catch(...) must catch any exceptions, but it doesn't in all cases.

At least from what I tried.

How do you run a command as an administrator from the Windows command line?

A batch/WSH hybrid is able to call ShellExecute to display the UAC elevation dialog...

@if (1==1) @if(1==0) @ELSE
@echo off&SETLOCAL ENABLEEXTENSIONS
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"||(
    cscript //E:JScript //nologo "%~f0"
    @goto :EOF
)
echo.Performing admin tasks...
REM call foo.exe
@goto :EOF
@end @ELSE
ShA=new ActiveXObject("Shell.Application")
ShA.ShellExecute("cmd.exe","/c \""+WScript.ScriptFullName+"\"","","runas",5);
@end

htaccess redirect if URL contains a certain string

RewriteCond %{REQUEST_URI} foobar
RewriteRule .* index.php

or some variant thereof.

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

Here is what you do in Excel 2003:

  1. In your sheet of interest, go to Format -> Sheet -> Hide and hide your sheet.
  2. Go to Tools -> Protection -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Here is what you do in Excel 2007:

  1. In your sheet of interest, go to Home ribbon -> Format -> Hide & Unhide -> Hide Sheet and hide your sheet.
  2. Go to Review ribbon -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?


If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.

How do I run a terminal inside of Vim?

This question is rather old, but for those finding it, there's a new possible solution: Neovim contains a full-fledged, first-class terminal emulator, which does exactly what ConqueTerm tried to. Simply run :term <your command here>.

<C-\><C-n> will exit term mode back to normal-mode. If you're like me and prefer that escape still exit term mode, you can add this to your nvimrc:

tnoremap <ESC><ESC> <C-\><C-N>

And then hitting ESC twice will exit terminal mode back to normal-mode, so you can manipulate the buffer that the still-running command is writing to.

Though keep in mind, as nvim is under heavy development at the time I'm posting this answer, another way to exit terminal mode may be added. As Ctrl+\Ctrl+n switches to normal mode from almost any mode, I don't expect that this answer will become wrong, but be aware that if it doesn't work, this answer might be out of date.

https://github.com/neovim/neovim

How to unapply a migration in ASP.NET Core with EF Core

Note: It might be troublesome later on, I used it as a last resort since non of the solutions provided above and others did not work in my case:

  1. Copy the code from the body of previous successful migration's down() method.
  2. Add a new migration using Add-Migration "migration-name"
  3. Paste the copied code from the down() method of previous migration to the new migration's Up() method:
    Up(){ //paste here }
  4. Run Update-Database
  5. Done, your changes from the previous migration should now have been reverted!

Disabling browser caching for all browsers from ASP.NET

There are two approaches that I know of. The first is to tell the browser not to cache the page. Setting the Response to no cache takes care of that, however as you suspect the browser will often ignore this directive. The other approach is to set the date time of your response to a point in the future. I believe all browsers will correct this to the current time when they add the page to the cache, but it will show the page as newer when the comparison is made. I believe there may be some cases where a comparison is not made. I am not sure of the details and they change with each new browser release. Final note I have had better luck with pages that "refresh" themselves (another response directive). The refresh seems less likely to come from the cache.

Hope that helps.

Sublime Text 2 Code Formatting

A similar option in Sublime Text is the built in Edit->Line->Reindent. You can put this code in Preferences -> Key Bindings User:

{ "keys": ["alt+shift+f"], "command": "reindent"} 

I use alt+shift+f because I'm a Netbeans user.

To format your code, select all by pressing ctrl+a and "your key combination". Excuse me for my bad english.


Or if you don't want to select all before formatting, add an argument to the command instead:

{ "keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false} }

(as per comment by @Supr below)

How to show row number in Access query like ROW_NUMBER in SQL

One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:

SELECT a.ID, 
       a.AText, 
       (SELECT Count(ID) 
        FROM table1 b WHERE b.ID <= a.ID 
        AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;

How to execute .sql file using powershell?

Here is a function that I have in my PowerShell profile for loading SQL snapins:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

Resize jqGrid when browser is resized?

this seems to be working nicely for me

$(window).bind('resize', function() {
    jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I had this issue and I realized that .gitignore file is changed. So, I changed .gitignore and I could pull the changes.

Search for a string in all tables, rows and columns of a DB

/*
This procedure is for finding any string or date in all tables
if search string is date, its format should be yyyy-MM-dd
eg. 2011-07-05
*/

-- ================================================
-- Exec SearchInTables 'f6f56934-a5d4-4967-80a1-1a2223b9c7b1'

-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Joshy,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE SearchInTables
@myValue nvarchar(1000)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
        DECLARE @searchsql nvarchar(max)
        DECLARE @table_name nvarchar(1000)
        DECLARE @Schema_name nvarchar(1000)
        DECLARE @ParmDefinition nvarchar(500)
        DECLARE @XMLIn nvarchar(max)
        SET @ParmDefinition = N'@XMLOut varchar(max) OUTPUT'

        SELECT A.name,b.name 
        FROM sys.tables A 
            INNER JOIN sys.schemas B ON A.schema_id=B.schema_id
        WHERE A.name like 'tbl_Tax_Sections' 

        DECLARE tables_cur CURSOR FOR 
                            SELECT A.name,b.name FOM sys.tables A 
                            INNER JOIN sys.schemas B ON A.schema_id=B.schema_id
                            WHERE A.type = 'U'  
        OPEN tables_cur  
        FETCH NEXT FROM tables_cur INTO @table_name , @Schema_name 
            WHILE (@@FETCH_STATUS = 0) 
            BEGIN
                SET @searchsql ='SELECT @XMLOut=(SELECT PATINDEX(''%'+ @myValue+ '%'''
                SET @searchsql =@searchsql  + ', (SELECT * FROM '+@Schema_name+'.'+@table_name+' FOR XML AUTO) ))'
                --print @searchsql 
                EXEC sp_executesql @searchsql, @ParmDefinition, @XMLOut=@XMLIn OUTPUT
                --print @XMLIn 

                IF @XMLIn <> 0 PRINT @Schema_name+'.'+@table_name

                FETCH NEXT FROM tables_cur INTO @table_name , @Schema_name 

            END
        CLOSE tables_cur 
        DEALLOCATE tables_cur 
    RETURN
END
GO

ActivityCompat.requestPermissions not showing dialog box

Here's an example of using requestPermissions():

First, define the permission (as you did in your post) in the manifest, otherwise, your request will automatically be denied:

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

Next, define a value to handle the permission callback, in onRequestPermissionsResult():

private final int REQUEST_PERMISSION_PHONE_STATE=1;

Here's the code to call requestPermissions():

private void showPhoneStatePermission() {
    int permissionCheck = ContextCompat.checkSelfPermission(
            this, Manifest.permission.READ_PHONE_STATE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {
            showExplanation("Permission Needed", "Rationale", Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_PHONE_STATE);
        } else {
            requestPermission(Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_PHONE_STATE);
        }
    } else {
        Toast.makeText(MainActivity.this, "Permission (already) Granted!", Toast.LENGTH_SHORT).show();
    }
}

First, you check if you already have permission (remember, even after being granted permission, the user can later revoke the permission in the App Settings.)

And finally, this is how you check if you received permission or not:

@Override
public void onRequestPermissionsResult(
        int requestCode,
        String permissions[],
        int[] grantResults) {
    switch (requestCode) {
        case REQUEST_PERMISSION_PHONE_STATE:
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Permission Denied!", Toast.LENGTH_SHORT).show();
            }
    }
}

private void showExplanation(String title,
                             String message,
                             final String permission,
                             final int permissionRequestCode) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    requestPermission(permission, permissionRequestCode);
                }
            });
    builder.create().show();
}

private void requestPermission(String permissionName, int permissionRequestCode) {
    ActivityCompat.requestPermissions(this,
            new String[]{permissionName}, permissionRequestCode);
}

How to insert default values in SQL table?

To insert the default values you should omit them something like this :

Insert into Table (Field2) values(5)

All other fields will have null or their default values if it has defined.

How to make layout with View fill the remaining space?

In case if < TEXT VIEW > is placed in LinearLayout, set the Layout_weight proprty of < and > to 0 and 1 for TextView.
In case of RelativeLayout align < and > to left and right and set "Layout to left of" and "Layout to right of" property of TextView to ids of < and >

How to list all tags along with the full message in git?

I prefer doing this on the command line, but if you don't mind a web interface and you use GitHub, you can visit https://github.com/user/repo/tags and click on the "..." next to each tag to display its annotation.

What's a good, free serial port monitor for reverse-engineering?

Oops, can't comment yet (!) but re: Nick and logic analyser, beware: RS232 signal levels not typically Logic Analyser compatible unless you get/make a special serial probe. A 'proper' RS232/Serial port can use +/-12v swings (on all signals) and sometimes more. A laptop sometimes uses 0-5v swings (and often won't work with real serial interfaces) so could work with a vbasic 'ttl-level' LA interface.

How do I use su to execute the rest of the bash script as that user?

Inspired by the idea from @MarSoft but I changed the lines like the following:

USERNAME='desireduser'
COMMAND=$0
COMMANDARGS="$(printf " %q" "${@}")"
if [ $(whoami) != "$USERNAME" ]; then
  exec sudo -E su $USERNAME -c "/usr/bin/bash -l $COMMAND $COMMANDARGS"
  exit
fi

I have used sudo to allow a password less execution of the script. If you want to enter a password for the user, remove the sudo. If you do not need the environment variables, remove -E from sudo.

The /usr/bin/bash -l ensures, that the profile.d scripts are executed for an initialized environment.

How can I join on a stored procedure?

I hope your stored procedure is not doing a cursor loop!

If not, take the query from your stored procedure and integrate that query within the query you are posting here:

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
        u.UnitNumber,
        p.PropertyName
        ,dt.TenantBalance
FROM tblTenant t
    LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
    LEFT JOIN tblProperty   p ON u.PropertyID = p.ID
    LEFT JOIN (SELECT ID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance
                   FROM tblTransaction
                   GROUP BY tenant.ID
              ) dt ON t.ID=dt.ID
ORDER BY p.PropertyName, t.CarPlateNumber

If you are doing something more than a query in your stored procedure, create a temp table and execute the stored procedure into this temp table and then join to that in your query.

create procedure test_proc
as
  select 1 as x, 2 as y
  union select 3,4 
  union select 5,6 
  union select 7,8 
  union select 9,10
  return 0
go 

create table #testing
(
  value1   int
  ,value2  int
)

INSERT INTO #testing
exec test_proc


select
  *
  FROM #testing

Python variables as keys to dict

Try:

to_dict = lambda **k: k
apple = 1
banana = 'f'
carrot = 3
to_dict(apple=apple, banana=banana, carrot=carrot)
#{'apple': 1, 'banana': 'f', 'carrot': 3}

Multiplying across in a numpy array

Normal multiplication like you showed:

>>> import numpy as np
>>> m = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> c = np.array([0,1,2])
>>> m * c
array([[ 0,  2,  6],
       [ 0,  5, 12],
       [ 0,  8, 18]])

If you add an axis, it will multiply the way you want:

>>> m * c[:, np.newaxis]
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [14, 16, 18]])

You could also transpose twice:

>>> (m.T * c).T
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [14, 16, 18]])

C - gettimeofday for computing time?

If you want to measure code efficiency, or in any other way measure time intervals, the following will be easier:

#include <time.h>

int main()
{
   clock_t start = clock();
   //... do work here
   clock_t end = clock();
   double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
   return 0;
}

hth

How can I find the latitude and longitude from address?

Ud_an's solution with updated API's

Note: LatLng class is part of Google Play Services.

Mandatory:

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

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

Update: If you have target SDK 23 and above, make sure you take care of runtime permission for location.

public LatLng getLocationFromAddress(Context context,String strAddress) {

    Geocoder coder = new Geocoder(context);
    List<Address> address;
    LatLng p1 = null;

    try {
        // May throw an IOException
        address = coder.getFromLocationName(strAddress, 5);
        if (address == null) {
            return null;
        }

        Address location = address.get(0);
        p1 = new LatLng(location.getLatitude(), location.getLongitude() );

    } catch (IOException ex) {

        ex.printStackTrace();
    }

    return p1;
}

Removing single-quote from a string in php

$replace_str = array('"', "'", ",");
$FileName = str_replace($replace_str, "", $UserInput);

ReadFile in Base64 Nodejs

Latest and greatest way to do this:

Node supports file and buffer operations with the base64 encoding:

const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});

Or using the new promises API:

const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});

Set the table column width constant regardless of the amount of text in its cells?

It also helps, to put in the last "filler cell", with width:auto. This will occupy remaining space, and will leave all other dimensions as specified.

converting CSV/XLS to JSON?

If you can't find an existing solution it's pretty easy to build a basic one in Java. I just wrote one for a client and it took only a couple hours including researching tools.

Apache POI will read the Excel binary. http://poi.apache.org/

JSONObject will build the JSON

After that it's just a matter of iterating through the rows in the Excel data and building a JSON structure. Here's some pseudo code for the basic usage.

FileInputStream inp = new FileInputStream( file );
Workbook workbook = WorkbookFactory.create( inp );

// Get the first Sheet.
Sheet sheet = workbook.getSheetAt( 0 );

    // Start constructing JSON.
    JSONObject json = new JSONObject();

    // Iterate through the rows.
    JSONArray rows = new JSONArray();
    for ( Iterator<Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext(); )
    {
        Row row = rowsIT.next();
        JSONObject jRow = new JSONObject();

        // Iterate through the cells.
        JSONArray cells = new JSONArray();
        for ( Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext(); )
        {
            Cell cell = cellsIT.next();
            cells.put( cell.getStringCellValue() );
        }
        jRow.put( "cell", cells );
        rows.put( jRow );
    }

    // Create the JSON.
    json.put( "rows", rows );

// Get the JSON text.
return json.toString();

Is it possible to have placeholders in strings.xml for runtime values?

However, you should also read Elias Mårtenson's answer on Android plurals treatment of “zero”. There is a problem with the interpretation of certain values such as "zero".

CSS:Defining Styles for input elements inside a div

You can define style rules which only apply to specific elements inside your div with id divContainer like this:

#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */

Getting String value from enum in Java

Use default method name() as given bellows

public enum Category {
        ONE("one"),
        TWO ("two"),
        THREE("three");

        private final String name;

        Category(String s) {
            name = s;
        }

    }

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Category.ONE.name());
    }
}

What is the use of ByteBuffer in Java?

This is a good description of its uses and shortcomings. You essentially use it whenever you need to do fast low-level I/O. If you were going to implement a TCP/IP protocol or if you were writing a database (DBMS) this class would come in handy.

Restoring Nuget References?

Try re-installing the packages.

In the NuGet Package Manager Console enter the following command:

Update-Package -Reinstall -ProjectName Your.Project.Name

If you want to re-install packages and restore references for the whole solution omit the -ProjectName parameter.

download csv file from web api in angular js

In Angular 1.5, use the $window service to download a file.

angular.module('app.csv').factory('csvService', csvService);

csvService.$inject = ['$window'];

function csvService($window) {
    function downloadCSV(urlToCSV) {
        $window.location = urlToCSV;
    }
}

Find a line in a file and remove it

Here you go. This solution uses a DataInputStream to scan for the position of the string you want replaced and uses a FileChannel to replace the text at that exact position. It only replaces the first occurrence of the string that it finds. This solution doesn't store a copy of the entire file somewhere, (either the RAM or a temp file), it just edits the portion of the file that it finds.

public static long scanForString(String text, File file) throws IOException {
    if (text.isEmpty())
        return file.exists() ? 0 : -1;
    // First of all, get a byte array off of this string:
    byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);

    // Next, search the file for the byte array.
    try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {

        List<Integer> matches = new LinkedList<>();

        for (long pos = 0; pos < file.length(); pos++) {
            byte bite = dis.readByte();

            for (int i = 0; i < matches.size(); i++) {
                Integer m = matches.get(i);
                if (bytes[m] != bite)
                    matches.remove(i--);
                else if (++m == bytes.length)
                    return pos - m + 1;
                else
                    matches.set(i, m);
            }

            if (bytes[0] == bite)
                matches.add(1);
        }
    }
    return -1;
}

public static void replaceText(String text, String replacement, File file) throws IOException {
    // Open a FileChannel with writing ability. You don't really need the read
    // ability for this specific case, but there it is in case you need it for
    // something else.
    try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ)) {
        long scanForString = scanForString(text, file);
        if (scanForString == -1) {
            System.out.println("String not found.");
            return;
        }
        channel.position(scanForString);
        channel.write(ByteBuffer.wrap(replacement.getBytes(/* StandardCharsets.your_charset */)));
    }
}

Example

Input: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Method Call:

replaceText("QRS", "000", new File("path/to/file");

Resulting File: ABCDEFGHIJKLMNOP000TUVWXYZ

iPhone hide Navigation Bar only on first page

Give my credit to @chad-m 's answer.

Here is the Swift version:

  1. Create a new file MyNavigationController.swift

import UIKit

class MyNavigationController: UINavigationController, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.delegate = self
    }

    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        if viewController == self.viewControllers.first {
            self.setNavigationBarHidden(true, animated: animated)
        } else {
            self.setNavigationBarHidden(false, animated: animated)
        }
    }

}
  1. Set your UINavigationController's class in StoryBoard to MyNavigationController MyNavigationController That's it!

Difference between chad-m's answer and mine:

  1. Inherit from UINavigationController, so you won't pollute your rootViewController.

  2. use self.viewControllers.first rather than homeViewController, so you won't do this 100 times for your 100 UINavigationControllers in 1 StoryBoard.

what is difference between success and .done() method of $.ajax

In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).

Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

If you're USING a date then I strongly advise that you use jodatime, http://joda-time.sourceforge.net/. Using System.currentTimeMillis() for fields that are dates sounds like a very bad idea because you'll end up with a lot of useless code.

Both date and calendar are seriously borked, and Calendar is definitely the worst performer of them all.

I'd advise you to use System.currentTimeMillis() when you are actually operating with milliseconds, for instance like this

 long start = System.currentTimeMillis();
    .... do something ...
 long elapsed = System.currentTimeMillis() -start;

How to convert JSON to CSV format and store in a variable

An adaption from praneybehl answer to work with nested objects and tab separator

function ConvertToCSV(objArray) {
  let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
  if(!Array.isArray(array))
      array = [array];

  let str = '';

  for (let i = 0; i < array.length; i++) {
    let line = '';
    for (let index in array[i]) {
      if (line != '') line += ','

      const item = array[i][index];
      line += (typeof item === 'object' && item !== null ? ConvertToCSV(item) : item);
    }
    str += line + '\r\n';
  }

  do{
      str = str.replace(',','\t').replace('\t\t', '\t');
  }while(str.includes(',') || str.includes('\t\t'));

  return str.replace(/(\r\n|\n|\r)/gm, ""); //removing line breaks: https://stackoverflow.com/a/10805198/4508758
}

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A far more clear solution is to use the command netsh to change the IP (or setting it back to DHCP)

netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0

Where "Local Area Connection" is the name of the network adapter. You could find it in the windows Network Connections, sometimes it is simply named "Ethernet".

Here are two methods to set the IP and also to set the IP back to DHCP "Obtain an IP address automatically"

public bool SetIP(string networkInterfaceName, string ipAddress, string subnetMask, string gateway = null)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var ipInfo = ipProperties.UnicastAddresses.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork);
    var currentIPaddress = ipInfo.Address.ToString();
    var currentSubnetMask = ipInfo.IPv4Mask.ToString();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (!isDHCPenabled && currentIPaddress == ipAddress && currentSubnetMask == subnetMask)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" static {ipAddress} {subnetMask}" + (string.IsNullOrWhiteSpace(gateway) ? "" : $"{gateway} 1")) { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

public bool SetDHCP(string networkInterfaceName)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (isDHCPenabled)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" dhcp") { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

How do I overload the square-bracket operator in C#?

If you're using C# 6 or later, you can use expression-bodied syntax for get-only indexer:

public object this[int i] => this.InnerList[i];

Maximum number of records in a MySQL database table

In InnoDB, with a limit on table size of 64 terabytes and a MySQL row-size limit of 65,535 there can be 1,073,741,824 rows. That would be minimum number of records utilizing maximum row-size limit. However, more records can be added if the row size is smaller .

Inserting a value into all possible locations in a list

You could do this with the following list comprehension:

[mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)]

With your example:

>>> mylist=['A','B']
>>> newelement='X'
>>> [mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)]
[['X', 'A', 'B'], ['B', 'X', 'A'], ['A', 'B', 'X']]

Counting array elements in Perl

sub uniq {
    return keys %{{ map { $_ => 1 } @_ }};
}
my @my_array = ("a","a","b","b","c");
#print join(" ", @my_array), "\n";
my $a = join(" ", uniq(@my_array));
my @b = split(/ /,$a);
my $count = $#b;

Remove first Item of the array (like popping from stack)

Just use arr.slice(startingIndex, endingIndex).

If you do not specify the endingIndex, it returns all the items starting from the index provided.

In your case arr=arr.slice(1).

Import/Index a JSON file into Elasticsearch

just get postman from https://www.getpostman.com/docs/environments give it the file location with /test/test/1/_bulk?pretty command. enter image description here

python xlrd unsupported format, or corrupt file.

I just downloaded xlrd, created an excel document (excel 2007) for testing and got the same error (message says 'found PK\x03\x04\x14\x00\x06\x00'). Extension is a xlsx. Tried saving it to an older .xls format and error disappears .....

How to set python variables to true or false?

Python boolean keywords are True and False, notice the capital letters. So like this:

a = True;
b = True;
match_var = True if a == b else False
print match_var;

When compiled and run, this prints:

True

Can't get value of input type="file"?

Solution

document.getElementById("uploadPicture").attributes.value.textContent

How to kill a thread instantly in C#?

You should first have some agreed method of ending the thread. For example a running_ valiable that the thread can check and comply with.

Your main thread code should be wrapped in an exception block that catches both ThreadInterruptException and ThreadAbortException that will cleanly tidy up the thread on exit.

In the case of ThreadInterruptException you can check the running_ variable to see if you should continue. In the case of the ThreadAbortException you should tidy up immediately and exit the thread procedure.

The code that tries to stop the thread should do the following:

running_ = false;
threadInstance_.Interrupt();
if(!threadInstance_.Join(2000)) { // or an agreed resonable time
   threadInstance_.Abort();
}

How to add a progress bar to a shell script?

This lets you visualize that a command is still executing:

while :;do echo -n .;sleep 1;done &
trap "kill $!" EXIT  #Die with parent if we die prematurely
tar zxf packages.tar.gz; # or any other command here
kill $! && trap " " EXIT #Kill the loop and unset the trap or else the pid might get reassigned and we might end up killing a completely different process

This will create an infinite while loop that executes in the background and echoes a "." every second. This will display . in the shell. Run the tar command or any a command you want. When that command finishes executing then kill the last job running in the background - which is the infinite while loop.

Angular 2 router no base href set

Since 2.0 beta :)

import { APP_BASE_HREF } from 'angular2/platform/common';

How to preview a part of a large pandas DataFrame, in iPython notebook?

This line will allow you to see all rows (up to the number that you set as 'max_rows') without any rows being hidden by the dots ('.....') that normally appear between head and tail in the print output.

pd.options.display.max_rows = 500

How to force link from iframe to be opened in the parent window

Try target="_top"

<a href="http://example.com" target="_top">
   This link will open in same but parent window of iframe.
</a>

Jquery If radio button is checked

Try this:

if ( jQuery('#postageyes').is(':checked') ){ ... }

adding line break

The correct answer is to use Environment.NewLine, as you've noted. It is environment specific and provides clarity over "\r\n" (but in reality makes no difference).

foreach (var item in FirmNameList) 
{
    if (FirmNames != "")
    {
        FirmNames += ", " + Environment.NewLine;
    }
    FirmNames += item; 
} 

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

Chart won't update in Excel (2007)

I had this problem while generating 1000+ graphs through VBA. I generated the graphs and assigned a range to their series. However, when the sheet recalculated the graphs wouldn't update as the data ranges changed values.

Solution --> I turned WrapText off before the For...Next Loop that generates the graphs and then turned it on again after the loop.

Workbooks(x).Worksheets(x).Cells.WrapText=False 

and after...

Workbooks(x).Worksheets(x).Cells.WrapText=True

This a great solution because it updates 1000+ graphs at once without looping through them all and changing something individually.

Also, I'm not really sure why this works; I suppose when WrapText changes one property of the data range it makes the graph update, although I have no documentation on this.

Get current batchfile directory

Very simple:

setlocal
cd /d %~dp0
File.exe

GSON - Date format

As M.L. pointed out, JsonSerializer works here. However, if you are formatting database entities, use java.sql.Date to register you serializer. Deserializer is not needed.

Gson gson = new GsonBuilder()
   .registerTypeAdapter(java.sql.Date.class, ser).create();

This bug report might be related: http://code.google.com/p/google-gson/issues/detail?id=230. I use version 1.7.2 though.

Getting an "ambiguous redirect" error

put quotes around your variable. If it happens to have spaces, it will give you "ambiguous redirect" as well. also check your spelling

echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  "${OUPUT_RESULTS}"

eg of ambiguous redirect

$ var="file with spaces"
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> "${var}"
$ cat file\ with\ spaces
aaaa     dddd         mol_tag

How to change the playing speed of videos in HTML5?

(Tested in Chrome while playing videos on YouTube, but should work anywhere--especially useful for speeding up online training videos).

For anyone wanting to add these as "bookmarklets" (bookmarks) to your browser, use these browser bookmark names and URLs, and add each of the following bookmarks to the top of your browser:

enter image description here

Name: 0.5x
URL:

javascript:

document.querySelector('video').playbackRate = 0.5;

Name: 1.0x
URL:

javascript:

document.querySelector('video').playbackRate = 1.0;

Name: 1.5x
URL:

javascript:

document.querySelector('video').playbackRate = 1.5;

Name: 2.0x
URL:

javascript:

document.querySelector('video').playbackRate = 2.0;

References:

  1. The main answer by Jeremy Visser
  2. Copied from my GitHub gist here: https://gist.github.com/ElectricRCAircraftGuy/0a788876da1386ca0daecbe78b4feb44#other-bookmarklets
    1. Get other bookmarklets here too, such as for aiding you on GitHub.

'console' is undefined error for Internet Explorer

In my scripts, I either use the shorthand:

window.console && console.log(...) // only log if the function exists

or, if it's not possible or feasible to edit every console.log line, I create a fake console:

// check to see if console exists. If not, create an empty object for it,
// then create and empty logging function which does nothing. 
//
// REMEMBER: put this before any other console.log calls
!window.console && (window.console = {} && window.console.log = function () {});

Clicking a button within a form causes page refresh

You should declare the attribute ng-submit={expression} in your <form> tag.

From the ngSubmit docs http://docs.angularjs.org/api/ng.directive:ngSubmit

Enables binding angular expressions to onsubmit events.

Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page).

Align button to the right

Bootstrap 4 uses .float-right as opposed to .pull-right in Bootstrap 3. Also, don't forget to properly nest your rows with columns.

<div class="row">
    <div class="col-lg-12">
        <h3 class="one">Text</h3>
        <button class="btn btn-secondary float-right">Button</button>
    </div>
</div>

CSS Box Shadow Bottom Only

Do this:

box-shadow: 0 4px 2px -2px gray;

It's actually much simpler, whatever you set the blur to (3rd value), set the spread (4th value) to the negative of it.

How do I resolve `The following packages have unmet dependencies`

First of all try this

sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove

If error still persists then do this

sudo apt --fix-broken install
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f

Afterwards try this again:

sudo apt-get install npm

But if it still couldn't resolve issues check for the dependencies using sudo dpkg --configure -a and remove them one-by-one . Let's say dependencies are on npm then go for this ,

sudo apt-get remove nodejs
sudo apt-get remove npm

Then go to /etc/apt/sources.list.d and remove any node list if you have. Then do a

sudo apt-get update

Then check for the dependencies problem again using sudo dpkg --configure -a and if it's all clear then you are done . Later on install npm again using this

v=8   # set to 4, 5, 6, ... as needed
curl -sL https://deb.nodesource.com/setup_$v.x | sudo -E bash -

Then install the Node.js package.

sudo apt-get install -y nodejs

The answer above will work for general cases also(for dependencies on other packages like django ,etc) just after first two processes use the same process for the package you are facing dependency with.

Function pointer as a member of a C struct

Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?

PString * initializeString() {
    PString *str;
    str = (PString *) malloc(sizeof(PString));
    str->length = &length;
    return str;
}

Change background image opacity

Nowadays, it is possible to do it simply with CSS property "background-blend-mode".

<div id="content">Only one div needed</div>

div#content {
    background-image: url(my_image.png);
    background-color: rgba(255,255,255,0.6);
    background-blend-mode: lighten;
    /* You may add things like width, height, background-size... */
}

It will blend the background-color (which is white, 0.6 opacity) into the background image. Learn more here (W3S).

How do I divide so I get a decimal value?

int a = 3;
int b = 2;
float c = ((float)a)/b

encapsulation vs abstraction real world example

Abstraction

We use many abstractions in our day-to-day lives.Consider a car.Most of us have an abstract view of how a car works.We know how to interact with it to get it to do what we want it to do: we put in gas, turn a key, press some pedals, and so on. But we don't necessarily understand what is going on inside the car to make it move and we don't need to. Millions of us use cars everyday without understanding the details of how they work.Abstraction helps us get to school or work!

A program can be designed as a set of interacting abstractions. In Java, these abstractions are captured in classes. The creator of a class obviusly has to know its interface, just as the driver of a car can use the vehicle without knowing how the engine works.

Encapsulation

Consider a Banking system.Banking system have properties like account no,account type,balance ..etc. If someone is trying to change the balance of the account,attempt can be successful if there is no encapsulation. Therefore encapsulation allows class to have complete control over their properties.

Using Razor within JavaScript

What specific errors are you seeing?

Something like this could work better:

<script type="text/javascript">

//now add markers
 @foreach (var item in Model) {
    <text>
      var markerlatLng = new google.maps.LatLng(@Model.Latitude, @Model.Longitude);
      var title = '@(Model.Title)';
      var description = '@(Model.Description)';
      var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>'
    </text>
}
</script>

Note that you need the magical <text> tag after the foreach to indicate that Razor should switch into markup mode.

How to draw text using only OpenGL methods?

Theory

Why it is hard

Popular font formats like TrueType and OpenType are vector outline formats: they use Bezier curves to define the boundary of the letter.

Image source.

Transforming those formats into arrays of pixels (rasterization) is too specific and out of OpenGL's scope, specially because OpenGl does not have non-straight primitives (e.g. see Why is there no circle or ellipse primitive in OpenGL?)

The easiest approach is to first raster fonts ourselves on the CPU, and then give the array of pixels to OpenGL as a texture.

OpenGL then knows how to deal with arrays of pixels through textures very well.

Texture atlas

We could raster characters for every frame and re-create the textures, but that is not very efficient, specially if characters have a fixed size.

The more efficient approach is to raster all characters you plan on using and cram them on a single texture.

And then transfer that to the GPU once, and use it texture with custom uv coordinates to choose the right character.

This approach is called a texture atlas and it can be used not only for textures but also other repeatedly used textures, like tiles in a 2D game or web UI icons.

The Wikipedia picture of the full texture, which is itself taken from freetype-gl, illustrates this well:

I suspect that optimizing character placement to the smallest texture problem is an NP-hard problem, see: What algorithm can be used for packing rectangles of different sizes into the smallest rectangle possible in a fairly optimal way?

The same technique is used in web development to transmit several small images (like icons) at once, but there it is called "CSS Sprites": https://css-tricks.com/css-sprites/ and are used to hide the latency of the network instead of that of the CPU / GPU communication.

Non-CPU raster methods

There also exist methods which don't use the CPU raster to textures.

CPU rastering is simple because it uses the GPU as little as possible, but we also start thinking if it would be possible to use the GPU efficiency further.

This FOSDEM 2014 video explains other existing techniques:

Fonts inside of the 3D geometry with perspective

Rendering fonts inside of the 3D geometry with perspective (compared to an orthogonal HUD) is much more complicated, because perspective could make one part of the character much closer to the screen and larger than the other, making an uniform CPU discretization (e.g. raster, tesselation) look bad on the close part. This is actually an active research topic:

enter image description here

Distance fields are one of the popular techniques now.

Implementations

The examples that follow were all tested on Ubuntu 15.10.

Because this is a complex problem as discussed previously, most examples are large, and would blow up the 30k char limit of this answer, so just clone the respective Git repositories to compile.

They are all fully open source however, so you can just RTFS.

FreeType solutions

FreeType looks like the dominant open source font rasterization library, so it would allow us to use TrueType and OpenType fonts, making it the most elegant solution.

Examples / tutorials:

Other font rasterizers

Those seem less good than FreeType, but may be more lightweight:

Anton's OpenGL 4 Tutorials example 26 "Bitmap fonts"

The font was created by the author manually and stored in a single .png file. Letters are stored in an array form inside the image.

This method is of course not very general, and you would have difficulties with internationalization.

Build with:

make -f Makefile.linux64

Output preview:

enter image description here

opengl-tutorial chapter 11 "2D fonts"

Textures are generated from DDS files.

The tutorial explains how the DDS files were created, using CBFG and Paint.Net.

Output preview:

enter image description here

For some reason Suzanne is missing for me, but the time counter works fine: https://github.com/opengl-tutorials/ogl/issues/15

FreeGLUT

GLUT has glutStrokeCharacter and FreeGLUT is open source... https://github.com/dcnieho/FreeGLUT/blob/FG_3_0_0/src/fg_font.c#L255

OpenGLText

https://github.com/tlorach/OpenGLText

TrueType raster. By NVIDIA employee. Aims for reusability. Haven't tried it yet.

ARM Mali GLES SDK Sample

http://malideveloper.arm.com/resources/sample-code/simple-text-rendering/ seems to encode all characters on a PNG, and cut them from there.

SDL_ttf

enter image description here

Source: https://github.com/cirosantilli/cpp-cheat/blob/d36527fe4977bb9ef4b885b1ec92bd0cd3444a98/sdl/ttf.c

Lives in a separate tree to SDL, and integrates easily.

Does not provide a texture atlas implementation however, so performance will be limited: How to render fonts and text with SDL2 efficiently?

Related threads

CASE statement in SQLite query

Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END

OpenCV error: the function is not implemented

If it's giving you errors with gtk, try qt.

sudo apt-get install libqt4-dev
cmake -D WITH_QT=ON ..
make
sudo make install

If this doesn't work, there's an easy way out.

sudo apt-get install libopencv-*

This will download all the required dependencies(although it seems that you have all the required libraries installed, but still you could try it once). This will probably install OpenCV 2.3.1 (Ubuntu 12.04). But since you have OpenCV 2.4.3 in /usr/local/lib include this path in /etc/ld.so.conf and do ldconfig. So now whenever you use OpenCV, you'd use the latest version. This is not the best way to do it but if you're still having problems with qt or gtk, try this once. This should work.

Update - 18th Jun 2019

I got this error on my Ubuntu(18.04.1 LTS) system for openCV 3.4.2, as the method call to cv2.imshow was failing (e.g., at the line of cv2.namedWindow(name) with error: cv2.error: OpenCV(3.4.2). The function is not implemented.). I am using anaconda. Just the below 2 steps helped me resolve:

conda remove opencv
conda install -c conda-forge opencv=4.1.0

If you are using pip, you can try

pip install opencv-contrib-python

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

How to add days to the current date?

select dateadd(dd,360,getdate()) will give you correct date as shown below:

2017-09-30 15:40:37.260

I just ran the query and checked:
Please check the attached image

Automatic vertical scroll bar in WPF TextBlock?

You can use

ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollBarVisibility="Visible"

These are attached property of wpf. For more information

http://wpfbugs.blogspot.in/2014/02/wpf-layout-controls-scrollviewer.html

ImportError: cannot import name NUMPY_MKL

yes,Just reinstall numpy,it works.

sudo: npm: command not found

WARNING (edit)

Doing a chmod 777 is a fairly radical solution. Try these first, one at a time, and stop when one works:

  • $ sudo chmod -R 777 /usr/local/lib/node_modules/npm
  • $ sudo chmod -R 777 /usr/local/lib/node_modules
  • $ sudo chmod g+w /usr/local/lib
  • $ sudo chmod g+rwx /usr/local/lib

$ brew postinstall node is the only install part where I would get a problem

Permission denied - /usr/local/lib/node_modules/npm/.github

So I

// !! READ EDIT ABOVE BEFORE RUNNING THIS CODE !!
$ sudo chmod -R 777 /usr/local/lib
$ brew postinstall node

and viola, npm is now linked

$ npm -v
3.10.10

Extra

If you used -R 777 on lib my recommendation would be to set nested files and directories to a default setting:

  • $ find /usr/local/lib -type f -print -exec chmod 644 {} \;
  • $ find /usr/local/lib -type d -print -exec chmod 755 {} \;
  • $ chmod /usr/local/lib 755

Disable text input history

<input type="text" autocomplete="off" />

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

In WPF we have a couple of options by using the Show() and ShowDialog() methods.

Well, if you want to close the opened window when a new window gets open then you can use the Show() method:

Window1 win1 = new Window1();
win1.Show();
win1.Close();

ShowDialog() also opens a window, but in this case you can not close your previously opened window.

SQL order string as number

It might help who is looking for the same solution.

select * from tablename ORDER BY ABS(column_name)

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

What should I use to open a url instead of urlopen in urllib3

You should use urllib.reuqest, not urllib3.

import urllib.request   # not urllib - important!
urllib.request.urlopen('https://...')

How to make a div have a fixed size?

<div>
  <img src="whatever it is" class="image-crop">
</div>

 /*mobile code*/
    .image-crop{
      width:100%;
      max-height: auto;
     }
    /*desktop code*/

  @media screen and (min-width: 640px) {
    .image-crop{
       width:100%;
       max-height: 140px;
      }

Parse HTML in Android

String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

General guidelines to avoid memory leaks in C++

One technique that has become popular with memory management in C++ is RAII. Basically you use constructors/destructors to handle resource allocation. Of course there are some other obnoxious details in C++ due to exception safety, but the basic idea is pretty simple.

The issue generally comes down to one of ownership. I highly recommend reading the Effective C++ series by Scott Meyers and Modern C++ Design by Andrei Alexandrescu.

best way to get folder and file list in Javascript

fs/promises and fs.Dirent

Here's an efficient, non-blocking ls program using Node's fast fs.Dirent objects and fs/promises module. This approach allows you to skip wasteful fs.exist or fs.stat calls on every path -

// main.js
import { readdir } from "fs/promises"
import { join } from "path"

async function* ls (path = ".")
{ yield path
  for (const dirent of await readdir(path, { withFileTypes: true }))
    if (dirent.isDirectory())
      yield* ls(join(path, dirent.name))
    else
      yield join(path, dirent.name)
}

async function* empty () {}

async function toArray (iter = empty())
{ let r = []
  for await (const x of iter)
    r.push(x)
  return r
}

toArray(ls(".")).then(console.log, console.error)

Let's get some sample files so we can see ls working -

$ yarn add immutable     # (just some example package)
$ node main.js
[
  '.',
  'main.js',
  'node_modules',
  'node_modules/.yarn-integrity',
  'node_modules/immutable',
  'node_modules/immutable/LICENSE',
  'node_modules/immutable/README.md',
  'node_modules/immutable/contrib',
  'node_modules/immutable/contrib/cursor',
  'node_modules/immutable/contrib/cursor/README.md',
  'node_modules/immutable/contrib/cursor/__tests__',
  'node_modules/immutable/contrib/cursor/__tests__/Cursor.ts.skip',
  'node_modules/immutable/contrib/cursor/index.d.ts',
  'node_modules/immutable/contrib/cursor/index.js',
  'node_modules/immutable/dist',
  'node_modules/immutable/dist/immutable-nonambient.d.ts',
  'node_modules/immutable/dist/immutable.d.ts',
  'node_modules/immutable/dist/immutable.es.js',
  'node_modules/immutable/dist/immutable.js',
  'node_modules/immutable/dist/immutable.js.flow',
  'node_modules/immutable/dist/immutable.min.js',
  'node_modules/immutable/package.json',
  'package.json',
  'yarn.lock'
]

For added explanation and other ways to leverage async generators, see this Q&A.

Get a worksheet name using Excel VBA

Function MySheet()

  ' uncomment the below line to make it Volatile
  'Application.Volatile
   MySheet = Application.Caller.Worksheet.Name

End Function

This should be the function you are looking for

Typescript: How to extend two classes?

I think there is a much better approach, that allows for solid type-safety and scalability.

First declare interfaces that you want to implement on your target class:

interface IBar {
  doBarThings(): void;
}

interface IBazz {
  doBazzThings(): void;
}

class Foo implements IBar, IBazz {}

Now we have to add the implementation to the Foo class. We can use class mixins that also implements these interfaces:

class Base {}

type Constructor<I = Base> = new (...args: any[]) => I;

function Bar<T extends Constructor>(constructor: T = Base as any) {
  return class extends constructor implements IBar {
    public doBarThings() {
      console.log("Do bar!");
    }
  };
}

function Bazz<T extends Constructor>(constructor: T = Base as any) {
  return class extends constructor implements IBazz {
    public doBazzThings() {
      console.log("Do bazz!");
    }
  };
}

Extend the Foo class with the class mixins:

class Foo extends Bar(Bazz()) implements IBar, IBazz {
  public doBarThings() {
    super.doBarThings();
    console.log("Override mixin");
  }
}

const foo = new Foo();
foo.doBazzThings(); // Do bazz!
foo.doBarThings(); // Do bar! // Override mixin

How do I grant myself admin access to a local SQL Server instance?

Open a command prompt window. If you have a default instance of SQL Server already running, run the following command on the command prompt to stop the SQL Server service:

net stop mssqlserver

Now go to the directory where SQL server is installed. The directory can for instance be one of these:

C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn
C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn

Figure out your MSSQL directory and CD into it as such:

CD C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn

Now run the following command to start SQL Server in single user mode. As SQLCMD is being specified, only one SQLCMD connection can be made (from another command prompt window).

sqlservr -m"SQLCMD"

Now, open another command prompt window as the same user as the one that started SQL Server in single user mode above, and in it, run:

sqlcmd

And press enter. Now you can execute SQL statements against the SQL Server instance running in single user mode:

create login [<<DOMAIN\USERNAME>>] from windows;

-- For older versions of SQL Server:
EXEC sys.sp_addsrvrolemember @loginame = N'<<DOMAIN\USERNAME>>', @rolename = N'sysadmin';

-- For newer versions of SQL Server:
ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>];

GO

Source.

UPDATED Do not forget a semicolon after ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>]; and do not add extra semicolon after GO or the command never executes.

Graphviz's executables are not found (Python 3.4)

In my case (Win10, Anaconda3, Jupyter notebook) after "conda install graphviz" I have to add to the PATH: C:\Users\username\Anaconda3\Library\bin\graphviz

To modify PATH goto Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit > New

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

Sometimes a BEFORE trigger can be replaced with an AFTER one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF trigger one, as @marc_s has suggested in his comment.

Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE trigger and an INSTEAD OF one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.

But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.

So, it's really two things to solve then:

  • replace the BEFORE functionality;

  • replace the FOR EACH ROW functionality.

My attempt at solving these is below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  INSERT INTO sub (super_id)
  SELECT super_id FROM @new_super;
END;

This is how the above works:

  1. The same number of rows as being inserted into sub1 is first added to super. The generated super_id values are stored in a temporary storage (a table variable called @new_super).

  2. The newly inserted super_ids are now inserted into sub1.

Nothing too difficult really, but the above will only work if you have no other columns in sub1 than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.

The problem is to assign the new super_ids to every inserted row individually. One way to implement the mapping could be like below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    rownum   int IDENTITY (1, 1),
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  WITH enumerated AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
    FROM inserted
  )
  INSERT INTO sub1 (super_id, other columns)
  SELECT n.super_id, i.other columns
  FROM enumerated AS i
  INNER JOIN @new_super AS n
  ON i.rownum = n.rownum;
END;

As you can see, an IDENTIY(1,1) column is added to @new_user, so the temporarily inserted super_id values will additionally be enumerated starting from 1. To provide the mapping between the new super_ids and the new data rows, the ROW_NUMBER function is used to enumerate the INSERTED rows as well. As a result, every row in the INSERTED set can now be linked to a single super_id and thus complemented to a full data row to be inserted into sub1.

Note that the order in which the new super_ids are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super rows generated are identical save for the IDs. So, all you need here is just to take one new super_id per new sub1 row.

If, however, the logic of inserting into super is more complex and for some reason you need to remember precisely which new super_id has been generated for which new sub row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:

Refreshing all the pivot tables in my excel workbook with a macro

Yes.

ThisWorkbook.RefreshAll

Or, if your Excel version is old enough,

Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next

Creating a script for a Telnet session?

It may not sound a good idea but i used java and used simple TCP/IP socket programming to connect to a telnet server and exchange communication. ANd it works perfectly if you know the protocol implemented. For SSH etc, it might be tough unless you know how to do the handshake etc, but simple telnet works like a treat.

Another way i tried, was using external process in java System.exec() etc, and then let the windows built in telnet do the job for you and you just send and receive data to the local system process.

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

Shutting down "some system process" may be tricky... you should rather edit the [Apache folder]/conf/httpd.conf as mentioned by @Sergey Maksimenko and if you want to configure virtual host, use the new port in [Apache folder]/conf/extra/httpd-vhosts.conf (I used 4900 instead of 80 and 4901 instead of 443 in [Apache folder]/conf/httpd-ssl.conf). And remember to use the port when accessing page on localhost (or your virtualhost), for example: localhost:4900/index.html

How to pass table value parameters to stored procedure from .net code

Generic

   public static DataTable ToTableValuedParameter<T, TProperty>(this IEnumerable<T> list, Func<T, TProperty> selector)
    {
        var tbl = new DataTable();
        tbl.Columns.Add("Id", typeof(T));

        foreach (var item in list)
        {
            tbl.Rows.Add(selector.Invoke(item));

        }

        return tbl;

    }

Cannot GET / Nodejs Error

I think you're missing your routes, you need to define at least one route for example '/' to index.

e.g.

app.get('/', function (req, res) {
  res.render('index', {});
});

How to write multiple conditions in Makefile.am with "else if"

ifdef $(HAVE_CLIENT)
libtest_LIBS = \
    $(top_builddir)/libclient.la
else
ifdef $(HAVE_SERVER)
libtest_LIBS = \
    $(top_builddir)/libserver.la
else
libtest_LIBS = 
endif
endif

NOTE: DO NOT indent the if then it don't work!

How to reshape data from long to wide format

Using base R aggregate function:

aggregate(value ~ name, dat1, I)

# name           value.1  value.2  value.3  value.4
#1 firstName      0.4145  -0.4747   0.0659   -0.5024
#2 secondName    -0.8259   0.1669  -0.8962    0.1681

How to find when a web page was last updated

This is a Pythonic way to do it:

import httplib
import yaml
c = httplib.HTTPConnection(address)
c.request('GET', url_path)
r = c.getresponse()
# get the date into a datetime object
lmd = r.getheader('last-modified')
if lmd != None:
   cur_data = { url: datetime.strptime(lmd, '%a, %d %b %Y %H:%M:%S %Z') }
else:
   print "Hmmm, no last-modified data was returned from the URL."
   print "Returned header:"
   print yaml.dump(dict(r.getheaders()), default_flow_style=False)

The rest of the script includes an example of archiving a page and checking for changes against the new version, and alerting someone by email.

How to draw in JPanel? (Swing/graphics Java)

Variation of the code by Bijaya Bidari that is accepted by Java 8 without warnings in regard with overridable method calls in constructor:

public class Graph extends JFrame {
    JPanel jp;

    public Graph() {
        super("Simple Drawing");
        super.setSize(300, 300);
        super.setDefaultCloseOperation(EXIT_ON_CLOSE);

        jp = new GPanel();
        super.add(jp);
    }

    public static void main(String[] args) {
        Graph g1 = new Graph();
        g1.setVisible(true);
    }

    class GPanel extends JPanel {
        public GPanel() {
            super.setPreferredSize(new Dimension(300, 300));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            //rectangle originated at 10,10 and end at 240,240
            g.drawRect(10, 10, 240, 240);
                    //filled Rectangle with rounded corners.    
            g.fillRoundRect(50, 50, 100, 100, 80, 80);
        }
    }
}

TypeError: 'str' does not support the buffer interface

If you use Python3x then string is not the same type as for Python 2.x, you must cast it to bytes (encode it).

plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
    outfile.write(bytes(plaintext, 'UTF-8'))

Also do not use variable names like string or file while those are names of module or function.

EDIT @Tom

Yes, non-ASCII text is also compressed/decompressed. I use Polish letters with UTF-8 encoding:

plaintext = 'Polish text: acelnószzACELNÓSZZ'
filename = 'foo.gz'
with gzip.open(filename, 'wb') as outfile:
    outfile.write(bytes(plaintext, 'UTF-8'))
with gzip.open(filename, 'r') as infile:
    outfile_content = infile.read().decode('UTF-8')
print(outfile_content)

Form/JavaScript not working on IE 11 with error DOM7011

This error occurred for me when using window.location.reload(). Replacing with window.location = window.location.href solved the problem.

Get year, month or day from numpy datetime64

Use dates.tolist() to convert to native datetime objects, then simply access year. Example:

>>> dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype='datetime64')
>>> [x.year for x in dates.tolist()]
[2010, 2011, 2012]

This is basically the same idea exposed in https://stackoverflow.com/a/35281829/2192272, but using simpler syntax.

Tested with python 3.6 / numpy 1.18.

R numbers from 1 to 100

If you need the construct for a quick example to play with, use the : operator.

But if you are creating a vector/range of numbers dynamically, then use seq() instead.

Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.

In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,

seq(a, b, -1)

will raise an error for a=2, b=6, because the coder expected a decreasing sequence.

Center a DIV horizontally and vertically

After trying a lot of things I find a way that works. I share it here if it is useful to anyone. You can see it here working: http://jsbin.com/iquviq/30/edit

.content {
        width: 200px;
        height: 600px;
        background-color: blue;
        position: absolute; /*Can also be `fixed`*/
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        /*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
        max-width: 100%;
        max-height: 100%;
        overflow: auto;
}

How to count the number of observations in R like Stata command count

You can also use the filter function from the dplyr package which returns rows with matching conditions.

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2

Can't push to remote branch, cannot be resolved to branch

For me, the issue was I had git and my macOS filesystem set to two different case sensitivities. My Mac was formatted APFS/Is Case-Sensitive: NO but I had flipped my git settings at some point trying to get over a weird issue with Xcode image asset naming so git config --global core.ignorecase false. By flipping it back aligned the settings and recreating the branch and pushing got me back on track.

git config --global core.ignorecase true

Credit: https://www.hanselman.com/blog/GitIsCasesensitiveAndYourFilesystemMayNotBeWeirdFolderMergingOnWindows.aspx

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

numpy max vs amax vs maximum

For completeness, in Numpy there are four maximum related functions. They fall into two different categories:

  • np.amax/np.max, np.nanmax: for single array order statistics
  • and np.maximum, np.fmax: for element-wise comparison of two arrays

I. For single array order statistics

NaNs propagator np.amax/np.max and its NaN ignorant counterpart np.nanmax.

  • np.max is just an alias of np.amax, so they are considered as one function.

    >>> np.max.__name__
    'amax'
    >>> np.max is np.amax
    True
    
  • np.max propagates NaNs while np.nanmax ignores NaNs.

    >>> np.max([np.nan, 3.14, -1])
    nan
    >>> np.nanmax([np.nan, 3.14, -1])
    3.14
    

II. For element-wise comparison of two arrays

NaNs propagator np.maximum and its NaNs ignorant counterpart np.fmax.

  • Both functions require two arrays as the first two positional args to compare with.

    # x1 and x2 must be the same shape or can be broadcast
    np.maximum(x1, x2, /, ...);
    np.fmax(x1, x2, /, ...)
    
  • np.maximum propagates NaNs while np.fmax ignores NaNs.

    >>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([ nan,  nan, 2.72])
    >>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([-inf, 3.14, 2.72])
    
  • The element-wise functions are np.ufunc(Universal Function), which means they have some special properties that normal Numpy function don't have.

    >>> type(np.maximum)
    <class 'numpy.ufunc'>
    >>> type(np.fmax)
    <class 'numpy.ufunc'>
    >>> #---------------#
    >>> type(np.max)
    <class 'function'>
    >>> type(np.nanmax)
    <class 'function'>
    

And finally, the same rules apply to the four minimum related functions:

  • np.amin/np.min, np.nanmin;
  • and np.minimum, np.fmin.

How to ignore user's time zone and force Date() use specific time zone

My solutions is to determine timezone adjustment the browser applies, and reverse it:

var timestamp = 1600913205;  //retrieved from unix, that is why it is in seconds

//uncomment below line if you want to apply Pacific timezone
//timestamp += -25200;

//determine the timezone offset the browser applies to Date()
var offset = (new Date()).getTimezoneOffset() * 60;   

//re-initialize the Date function to reverse the timezone adjustment
var date = new Date((timestamp + offset) * 1000);

//here continue using date functions.

This point the date will be timezone free and always UTC, You can apply your own offset to timestamp to produce any timezone.

How can I set the default value for an HTML <select> element?

I came across this question, but the accepted and highly upvoted answer didn't work for me. It turns out that if you are using React, then setting selected doesn't work.

Instead you have to set a value in the <select> tag directly as shown below:

<select value="B">
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

Read more about why here on the React page.

Loop through files in a directory using PowerShell

To get the content of a directory you can use

$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"

Then you can loop over this variable as well:

for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].FullName + "out" 
    Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}

An even easier way to put this is the foreach loop (thanks to @Soapy and @MarkSchultheiss):

foreach ($f in $files){
    $outfile = $f.FullName + "out" 
    Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}

How to increase Bootstrap Modal Width?

.your_modal {
    width: 800px;
    margin-left: -400px; 
 }

margin left's value is half of modal's width. I'm using this with Maruti Admin theme since it doesn't has class .modal-lg .modal-sm

Taking screenshot on Emulator from Android Studio

Starting with Android Studio 2.0 you can do it with the new emulator:

New Android Emulator from Android Studio 2.0

Just click 3 "Take Screenshot". Standard location is the desktop.

Or

  1. Select "More"
  2. Under "Settings", specify the location for your screenshot
  3. Take your screenshot

UPDATE 22/07/2020

If you keep the emulator in Android Studio as possible since Android Studio 4.1 click here to save the screenshot in your standard location:

enter image description here

What generates the "text file busy" message in Unix?

One of my experience:

I always change the default keyboard shortcut of Chrome through reverse engineering. After modification, I forgot to close Chrome and ran the following:

sudo cp chrome /opt/google/chrome/chrome
cp: cannot create regular file '/opt/google/chrome/chrome': Text file busy

Using strace, you can find the more details:

sudo strace cp ./chrome /opt/google/chrome/chrome 2>&1 |grep 'Text file busy'
open("/opt/google/chrome/chrome", O_WRONLY|O_TRUNC) = -1 ETXTBSY (Text file busy)

Addition for BigDecimal

You can also do it like this:

BigDecimal A = new BigDecimal("10000000000");
BigDecimal B = new BigDecimal("20000000000");
BigDecimal C = new BigDecimal("30000000000");
BigDecimal resultSum = (A).add(B).add(C);
System.out.println("A+B+C= " + resultSum);

Prints:

A+B+C= 60000000000

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

how to File.listFiles in alphabetical order?

In Java 8:

Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));

Reverse order:

Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));

Swift convert unix time to date and time

Anyway @Nate Cook's answer is accepted but I would like to improve it with better date format.

with Swift 2.2, I can get desired formatted date

//TimeStamp
let timeInterval  = 1415639000.67457
print("time interval is \(timeInterval)")

//Convert to Date
let date = NSDate(timeIntervalSince1970: timeInterval)

//Date formatting
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMMM yyyy HH:mm:a"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let dateString = dateFormatter.stringFromDate(date)
print("formatted date is =  \(dateString)")

the result is

time interval is 1415639000.67457

formatted date is = 10, November 2014 17:03:PM

Convert row names into first column

A one line option is :

df$names <- rownames(df)

How to add background-image using ngStyle (angular2)?

My solution, using if..else statement. It is always a good practice if you want to avoid unnecessary frustrations, to check that your variable exists and is set. Otherwise, provide a backup image in case; You can also specify multiple style properties, like background-position: center, etc.

_x000D_
_x000D_
<div [ngStyle]="{'background-image': this.photo ? 'url(' + this.photo + ')' : 'https://placehold.it/70x70', 'background-position': 'center' }"></div>
_x000D_
_x000D_
_x000D_

Correct way to synchronize ArrayList in java

Yes it is the correct way, but the synchronised block is required if you want all the removals together to be safe - unless the queue is empty no removals allowed. My guess is that you just want safe queue and dequeue operations, so you can remove the synchronised block.

However, there are far advanced concurrent queues in Java such as ConcurrentLinkedQueue

Less aggressive compilation with CSS3 calc

Less no longer evaluates expression inside calc by default since v3.00.


Original answer (Less v1.x...2.x):

Do this:

body { width: calc(~"100% - 250px - 1.5em"); }

In Less 1.4.0 we will have a strictMaths option which requires all Less calculations to be within brackets, so the calc will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.

IndexOf function in T-SQL

One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

http://en.wikipedia.org/wiki/Email_address

How to write both h1 and h2 in the same line?

Put the h1 and h2 in a container with an id of container then:

#container {
    display: flex;
    justify-content: space-beteen;
}

How to insert image in mysql database(table)?

Step 1: open your mysql workbench application select table. choose image cell right click select "Open value in Editor" enter image description here

Step 2: click on the load button and choose image file enter image description here

Step 3:then click apply buttonenter image description here

Step 4: Then apply the query to save the image .Don't forgot image data type is "BLOB". Step 5: You can can check uploaded image enter image description here

Change background color on mouseover and remove it after mouseout

Set the original background-color in you CSS file:

.forum{
    background-color:#f0f;
}?

You don't have to capture the original color in jQuery. Remember that jQuery will alter the style INLINE, so by setting the background-color to null you will get the same result.

$(function() {
    $(".forum").hover(
    function() {
        $(this).css('background-color', '#ff0')
    }, function() {
        $(this).css('background-color', '')
    });
});?

Calculate difference in keys contained in two Python dictionaries

Here is a solution for deep comparing 2 dictionaries keys:

def compareDictKeys(dict1, dict2):
  if type(dict1) != dict or type(dict2) != dict:
      return False

  keys1, keys2 = dict1.keys(), dict2.keys()
  diff = set(keys1) - set(keys2) or set(keys2) - set(keys1)

  if not diff:
      for key in keys1:
          if (type(dict1[key]) == dict or type(dict2[key]) == dict) and not compareDictKeys(dict1[key], dict2[key]):
              diff = True
              break

  return not diff

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

.nvmrc

If you are using NVM like this, which you likely should, then you can indicate the nodejs version required for given project in a git-tracked .nvmrc file:

echo v10.15.1 > .nvmrc

This does not take effect automatically on cd, which is sane: the user must then do a:

nvm use

and now that version of node will be used for the current shell.

You can list the versions of node that you have with:

nvm list

.nvmrc is documented at: https://github.com/creationix/nvm/tree/02997b0753f66c9790c6016ed022ed2072c22603#nvmrc

How to automatically select that node version on cd was asked at: Automatically switch to correct version of Node based on project

Tested with NVM 0.33.11.

Getting first value from map in C++

A map will not keep insertion order. Use *(myMap.begin()) to get the value of the first pair (the one with the smallest key when ordered).

You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.

How to add a Hint in spinner in XML

What worked for me is you would set your spinner up with a list of items including the hint at the beginning.

    final MaterialSpinner spinner = (MaterialSpinner) findViewById(R.id.spinner);

    spinner.setItems("Select something in this list", getString(R.string.ABC), getString(R.string.ERD), getString(R.string.KGD), getString(R.string.DFK), getString(R.string.TOE));

Now when the user actually selects something in the list, you would use the spinner.setItems method to set the list to everything besides your hint:

       spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                spinner.setItems(getString(R.string.ABC), getString(R.string.ERD), getString(R.string.KGD), getString(R.string.DFK), getString(R.string.TOE));

}

The hint will be removed as soon as the user selects something in the list.

How to read PDF files using Java?

PDFBox contains tools for text extraction.

iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.

iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.

jQuery function to open link in new window

Button click event only.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $("#btnext").click(function () {                    
                    window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
                });
            });
</script>

How to remove html special chars?

What I have done was to use: html_entity_decode, then use strip_tags to removed them.

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';