Programs & Examples On #Filepicker

Questions about the use of file pickers in general. Not to be confused with [filepicker.io]; use that tag for questions related to that service.

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

Event on a disabled input

Instead of disabled, you could consider using readonly. With some extra CSS you can style the input so it looks like an disabled field.

There is actually another problem. The event change only triggers when the element looses focus, which is not logic considering an disabled field. Probably you are pushing data into this field from another call. To make this work you can use the event 'bind'.

$('form').bind('change', 'input', function () {
    console.log('Do your thing.');
});

PHP Fatal error: Cannot access empty property

Interesting:

  1. You declared an array var $my_value = array();
  2. Pushed value into it $a->my_value[] = 'b';
  3. Assigned a string to variable. (so it is no more array) $a->set_value ('c');
  4. Tried to push a value into array, that does not exist anymore. (it's string) $a->my_class('d');

And your foreach wont work anymore.

encrypt and decrypt md5

This question is tagged with PHP. But many people are using Laravel framework now. It might help somebody in future. That's why I answering for Laravel. It's more easy to encrypt and decrypt with internal functions.

$string = 'c4ca4238a0b923820dcc';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);

var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);

Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.

But you should not use encrypt and decrypt for authentication. Rather you should use hash make and check.

To store password in database, make hash of password and then save.

$password = Input::get('password_from_user'); 
$hashed = Hash::make($password); // save $hashed value

To verify password, get password stored of account from database

// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
  // Password is not matching 
} else {
  // Password is matching 
}

image processing to improve tesseract OCR accuracy

Reading text from image documents using any OCR engine have many issues in order get good accuracy. There is no fixed solution to all the cases but here are a few things which should be considered to improve OCR results.

1) Presence of noise due to poor image quality / unwanted elements/blobs in the background region. This requires some pre-processing operations like noise removal which can be easily done using gaussian filter or normal median filter methods. These are also available in OpenCV.

2) Wrong orientation of image: Because of wrong orientation OCR engine fails to segment the lines and words in image correctly which gives the worst accuracy.

3) Presence of lines: While doing word or line segmentation OCR engine sometimes also tries to merge the words and lines together and thus processing wrong content and hence giving wrong results. There are other issues also but these are the basic ones.

This post OCR application is an example case where some image pre-preocessing and post processing on OCR result can be applied to get better OCR accuracy.

How to make a simple collection view with Swift

This project has been tested with Xcode 10 and Swift 4.2.

Create a new project

It can be just a Single View App.

Add the code

Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell. This class will hold the outlets for the views that you add to your cell in the storyboard.

import UIKit
class MyCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var myLabel: UILabel!
}

We will connect this outlet later.

Open ViewController.swift and make sure you have the following content:

import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
    
    
    // MARK: - UICollectionViewDataSource protocol
    
    // tell the collection view how many cells to make
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }
    
    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
        
        // Use the outlet in our custom class to get a reference to the UILabel in the cell
        cell.myLabel.text = self.items[indexPath.row] // The row value is the same as the index of the desired text within the array.
        cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
        
        return cell
    }
    
    // MARK: - UICollectionViewDelegate protocol
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }
}

Notes

  • UICollectionViewDataSource and UICollectionViewDelegate are the protocols that the collection view follows. You could also add the UICollectionViewFlowLayout protocol to change the size of the views programmatically, but it isn't necessary.
  • We are just putting simple strings in our grid, but you could certainly do images later.

Set up the storyboard

Drag a Collection View to the View Controller in your storyboard. You can add constraints to make it fill the parent view if you like.

enter image description here

Make sure that your defaults in the Attribute Inspector are also

  • Items: 1
  • Layout: Flow

The little box in the top left of the Collection View is a Collection View Cell. We will use it as our prototype cell. Drag a Label into the cell and center it. You can resize the cell borders and add constraints to center the Label if you like.

enter image description here

Write "cell" (without quotes) in the Identifier box of the Attributes Inspector for the Collection View Cell. Note that this is the same value as let reuseIdentifier = "cell" in ViewController.swift.

enter image description here

And in the Identity Inspector for the cell, set the class name to MyCollectionViewCell, our custom class that we made.

enter image description here

Hook up the outlets

  • Hook the Label in the collection cell to myLabel in the MyCollectionViewCell class. (You can Control-drag.)
  • Hook the Collection View delegate and dataSource to the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)

enter image description here

Finished

Here is what it looks like after adding constraints to center the Label in the cell and pinning the Collection View to the walls of the parent.

enter image description here

Making Improvements

The example above works but it is rather ugly. Here are a few things you can play with:

Background color

In the Interface Builder, go to your Collection View > Attributes Inspector > View > Background.

Cell spacing

Changing the minimum spacing between cells to a smaller value makes it look better. In the Interface Builder, go to your Collection View > Size Inspector > Min Spacing and make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.

Cell shape

If you want rounded corners, a border, and the like, you can play around with the cell layer. Here is some sample code. You would put it directly after cell.backgroundColor = UIColor.cyan in code above.

cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8

See this answer for other things you can do with the layer (shadow, for example).

Changing the color when tapped

It makes for a better user experience when the cells respond visually to taps. One way to achieve this is to change the background color while the cell is being touched. To do that, add the following two methods to your ViewController class:

// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.red
}

// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.cyan
}

Here is the updated look:

enter image description here

Further study

UITableView version of this Q&A

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

How to call Makefile from another Makefile?

It seems clear that $(TESTS) is empty so your 1.4.0 makefile is effectively

all: 

clean:
  rm -f  gtest.a gtest_main.a *.o

Indeed, all has nothing to do. and clean does exactly what it says rm -f gtest.a ...

Is there a C# case insensitive equals operator?

string.Equals(StringA, StringB, StringComparison.CurrentCultureIgnoreCase);

How to send HTML-formatted email?

This works for me

msg.BodyFormat = MailFormat.Html;

and then you can use html in your body

msg.Body = "<em>It's great to use HTML in mail!!</em>"

Spacing between elements

In general we use margins on one of the elements, not spacer elements.

Resizing an iframe based on content

<html>
<head>
<script>
function frameSize(id){
var frameHeight;

document.getElementById(id).height=0 + "px";
if(document.getElementById){
    newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;    
}

document.getElementById(id).height= (frameHeight) + "px";
}
</script>
</head>

<body>

<iframe id="frame"  src="startframe.html" frameborder="0" marginheight="0" hspace=20     width="100%" 

onload="javascript:frameSize('frame');">

<p>This will work, but you need to host it on an http server, you can do it locally.    </p>
</body>
</html>

How to POST form data with Spring RestTemplate?

How to POST mixed data: File, String[], String in one request.

You can use only what you need.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);
    }

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(
            builder.build().encode().toUri(),
            HttpMethod.POST,
            requestEntity,
            String.class);

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    }
    return result;
}

The POST request will have File in its Body and next structure:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

Parsing Query String in node.js

node -v v9.10.1

If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

So I would suggest use JSON.stringify

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}

How to Create a real one-to-one relationship in SQL Server

This can be done by creating a simple primary foreign key relationship and setting the foreign key column to unique in the following manner:

CREATE TABLE [Employee] (
    [ID]    INT PRIMARY KEY
,   [Name]  VARCHAR(50)
);

CREATE TABLE [Salary] (
    [EmployeeID]    INT UNIQUE NOT NULL
,   [SalaryAmount]  INT 
);

ALTER TABLE [Salary]
ADD CONSTRAINT FK_Salary_Employee FOREIGN KEY([EmployeeID]) 
    REFERENCES [Employee]([ID]);

Schema

INSERT INTO [Employee] (
    [ID]
,   [Name]
)
VALUES
    (1, 'Ram')
,   (2, 'Rahim')
,   (3, 'Pankaj')
,   (4, 'Mohan');

INSERT INTO [Salary] (
    [EmployeeID]
,   [SalaryAmount]
)
VALUES
    (1, 2000)
,   (2, 3000)
,   (3, 2500)
,   (4, 3000);

Check to see if everything is fine

SELECT * FROM [Employee];
SELECT * FROM [Salary];

Now Generally in Primary Foreign Relationship (One to many), you could enter multiple times EmployeeID, but here an error will be thrown

INSERT INTO [Salary] (
    [EmployeeID]
,   [SalaryAmount]
)
VALUES
    (1, 3000);

The above statement will show error as

Violation of UNIQUE KEY constraint 'UQ__Salary__7AD04FF0C044141D'. Cannot insert duplicate key in object 'dbo.Salary'. The duplicate key value is (1).

Generating a SHA-256 hash from the Linux command line

echo will normally output a newline, which is suppressed with -n. Try this:

echo -n foobar | sha256sum

How to count objects in PowerShell?

As short as @jumbo's answer is :-) you can do it even more tersely. This just returns the Count property of the array returned by the antecedent sub-expression:

@(Get-Alias).Count

A couple points to note:

  1. You can put an arbitrarily complex expression in place of Get-Alias, for example:

    @(Get-Process | ? { $_.ProcessName -eq "svchost" }).Count
    
  2. The initial at-sign (@) is necessary for a robust solution. As long as the answer is two or greater you will get an equivalent answer with or without the @, but when the answer is zero or one you will get no output unless you have the @ sign! (It forces the Count property to exist by forcing the output to be an array.)

2012.01.30 Update

The above is true for PowerShell V2. One of the new features of PowerShell V3 is that you do have a Count property even for singletons, so the at-sign becomes unimportant for this scenario.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Escape a string in SQL Server so that it is safe to use in LIKE expression

To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)

For example this escapes the % symbol, using \ as the escape char:

select * from table where myfield like '%15\% off%' ESCAPE '\'

If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:

set @myString = replace( 
                replace( 
                replace( 
                replace( @myString
                ,    '\', '\\' )
                ,    '%', '\%' )
                ,    '_', '\_' )
                ,    '[', '\[' )

(Note that you have to escape your escape char too, and make sure that's the inner replace so you don't escape the ones added from the other replace statements). Then you can use something like this:

select * from table where myfield like '%' + @myString + '%' ESCAPE '\'

Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.

Why is there no SortedList in Java?

JavaFX SortedList

Though it took a while, Java 8 does have a sorted List. http://docs.oracle.com/javase/8/javafx/api/javafx/collections/transformation/SortedList.html

As you can see in the javadocs, it is part of the JavaFX collections, intended to provide a sorted view on an ObservableList.

Update: Note that with Java 11, the JavaFX toolkit has moved outside the JDK and is now a separate library. JavaFX 11 is available as a downloadable SDK or from MavenCentral. See https://openjfx.io

Best way to get hostname with php

You could also use...

$hostname = getenv('HTTP_HOST');

.m2 , settings.xml in Ubuntu

You can find your maven files here:

cd ~/.m2

Probably you need to copy settings.xml in your .m2 folder:

cp /usr/local/bin/apache-maven-2.2.1/conf/settings.xml .m2/

If no .m2 folder exists:

mkdir -p ~/.m2

Custom Card Shape Flutter SDK

When Card I always use RoundedRectangleBorder.

Card(
  color: Colors.grey[900],
  shape: RoundedRectangleBorder(
    side: BorderSide(color: Colors.white70, width: 1),
    borderRadius: BorderRadius.circular(10),
  ),
  margin: EdgeInsets.all(20.0),
  child: Container(
    child: Column(
        children: <Widget>[
        ListTile(
            title: Text(
            'example',
            style: TextStyle(fontSize: 18, color: Colors.white),
            ),
        ),
        ],
    ),
  ),
),

Iterate over a Javascript associative array in sorted order

I really like @luke-schafer's prototype idea, but also hear what he is saying about the issues with prototypes. What about using a simple function?

_x000D_
_x000D_
function sortKeysAndDo( obj, worker ) {_x000D_
  var keys = Object.keys(obj);_x000D_
  keys.sort();_x000D_
  for (var i = 0; i < keys.length; i++) {_x000D_
     worker(keys[i], obj[keys[i]]);_x000D_
  }_x000D_
}_x000D_
_x000D_
function show( key, value ) {_x000D_
  document.write( key + ' : ' + value +'<br>' );_x000D_
}_x000D_
_x000D_
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
sortKeysAndDo( a, show);_x000D_
_x000D_
var my_object = { 'c': 3, 'a': 1, 'b': 2 };_x000D_
_x000D_
sortKeysAndDo( my_object, show);
_x000D_
_x000D_
_x000D_

This seems to eliminate the issues with prototypes and still provide a sorted iterator for objects. I am not really a JavaScript guru, though, so I'd love to know if this solution has hidden flaws I missed.

Overlapping Views in Android

Android handles transparency across views and drawables (including PNG images) natively, so the scenario you describe (a partially transparent ImageView in front of a Gallery) is certainly possible.

If you're having problems it may be related to either the layout or your image. I've replicated the layout you describe and successfully achieved the effect you're after. Here's the exact layout I used.

<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/gallerylayout"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Gallery
    android:id="@+id/overview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />
  <ImageView
    android:id="@+id/navigmaske"
    android:background="#0000"      
    android:src="@drawable/navigmask"
    android:scaleType="fitXY"
    android:layout_alignTop="@id/overview"
    android:layout_alignBottom="@id/overview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />
</RelativeLayout>

Note that I've changed the parent RelativeLayout to a height and width of fill_parent as is generally what you want for a main Activity. Then I've aligned the top and bottom of the ImageView to the top and bottom of the Gallery to ensure it's centered in front of it.

I've also explicitly set the background of the ImageView to be transparent.

As for the image drawable itself, if you put the PNG file somewhere for me to look at I can use it in my project and see if it's responsible.

OnItemCLickListener not working in listview

I just found a solution from here, but by deep clicking.

If any row item of list contains focusable or clickable view then OnItemClickListener won't work.

The row item must have a param like android:descendantFocusability = "blocksDescendants".

Here you can see an example of how your list item should look like. Your list item xml should be... row_item.xml (your_xml_file.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:descendantFocusability="blocksDescendants"
    android:gravity="center_vertical" >

    // your other widgets here

</LinearLayout>

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

A simple and intuitive way would be to use shuf.

Example:

Assume words.txt as:

the
an
linux
ubuntu
life
good
breeze

To shuffle the lines, do:

$ shuf words.txt

which would throws the shuffled lines to standard output; So, you've to pipe it to an output file like:

$ shuf words.txt > shuffled_words.txt

One such shuffle run could yield:

breeze
the
linux
an
ubuntu
good
life

How to get data by SqlDataReader.GetValue by column name

thisReader.GetString(int columnIndex)

How to activate virtualenv?

run this code it will get activated if you on a windows machine
source venv/Scripts/activate

enter image description here

What is NODE_ENV and how to use it in Express?

I assume the original question included how does Express use this environment variable.

Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error, to avoid leaking implementation details to the world.

Programmatically scroll a UIScrollView

You can scroll to some point in a scroll view with one of the following statements in Objective-C

[scrollView setContentOffset:CGPointMake(x, y) animated:YES];

or Swift

scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true)

See the guide "Scrolling the Scroll View Content" from Apple as well.

To do slideshows with UIScrollView, you arrange all images in the scroll view, set up a repeated timer, then -setContentOffset:animated: when the timer fires.

But a more efficient approach is to use 2 image views and swap them using transitions or simply switching places when the timer fires. See iPhone Image slideshow for details.

How to check if an option is selected?

If you're not familiar or comfortable with is(), you could just check the value of prop("selected").

As seen here:

$('#mySelectBox option').each(function() {
    if ($(this).prop("selected") == true) {
       // do something
    } else {
       // do something
    }
});?

Edit:

As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle update displaying this action.

if (this.selected == true) {

appears to work just as well! Thanks gdoron.

Function to Calculate Median in SQL Server

Below is My solution:

with tempa as

 (

    select value,row_number() over (order by value) as Rn,/* Assigning a 
                                                           row_number */
           count(value) over () as Cnt /*Taking total count of the values */
    from numbers
    where value is not null /* Excluding the null values */
 ),

tempb as

  (

    /* Since we don't know whether the number of rows is odd or even, we shall 
     consider both the scenarios */

    select round(cnt/2) as Ref from tempa where mod(cnt,2)=1
    union all
    select round(cnt/2) a Ref from tempa where mod(cnt,2)=0
     union all
    select round(cnt/2) + 1 as Ref from tempa where mod(cnt,2)=0
   )
  select avg(value) as Median_Value

  from tempa where rn in

    ( select Ref from tempb);

XSLT - How to select XML Attribute by Attribute?

Just remove the slash after Data and prepend the root:

<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>

The create-react-app imports restriction outside of src directory

You can try using simlinks, but in reverse.

React won't follow simlinks, but you can move something to the source directory, and create a simlink to it.

In the root of my project, I had a node server directory that had several schema files in it. I wanted to use them on the frontend, so I:

  • moved the files /src
  • in the termal, I cd'ed into where the schema files belonged in server
  • ln -s SRC_PATH_OF_SCHEMA_FILE

This gave react what it was looking for, and node was perfectly happy including files through simlinks.

pandas how to check dtype for all columns in a dataframe?

The singular form dtype is used to check the data type for a single column. And the plural form dtypes is for data frame which returns data types for all columns. Essentially:

For a single column:

dataframe.column.dtype

For all columns:

dataframe.dtypes

Example:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})

df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')

df.dtypes
#A     int64
#B      bool
#C    object
#dtype: object

Counting array elements in Python

Or,

myArray.__len__()

if you want to be oopy; "len(myArray)" is a lot easier to type! :)

Create dynamic variable name

C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuickTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> names = new Dictionary<string,int>();


            for (int i = 0; i < 10; i++)
            {
                names.Add(String.Format("name{0}", i.ToString()), i);
            }

            var xx1 = names["name1"];
            var xx2 = names["name2"];
            var xx3 = names["name3"];
        }
    }
}

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

I am using PHP for webservice and Android 4.x. device for connecting to the webservice. I had similar problem where, using 10.0.2.2 worked well with emulator but failed to connect from device. The solution that worked for me is: Find IP of your computer ... say 192.168.0.103 Find the port of your apache ... say 8080 Now open httpd.conf and locate following line Listen 127.0.0.1:8080 After this line add following Listen 192.168.0.103:8080 Thats it. Now if you use 192.168.0.103:8080 in your android code, it will connect!!

RegEx match open tags except XHTML self-contained tags

RegEx match open tags except XHTML self-contained tags
All other tags (and content) are skipped.


This regex does that. If you need to match only specific Open tags, make a list
in an alternation (?:p|br|<whatever tags you want>) and replace the [\w:]+ construct
in the appropriate place below.

<(?:(?:(?:(script|style|object|embed|applet|noframes|noscript|noembed)(?:\s+(?>"[\S\s]*?"|'[\S\s]*?'|(?:(?!/>)[^>])?)+)?\s*>)[\S\s]*?</\1\s*(?=>)(*SKIP)(*FAIL))|(?:[\w:]+\b(?=((?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)*)>)\2(?<!/))|(?:(?:/?[\w:]+\s*/?)|(?:[\w:]+\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)+\s*/?)|\?[\S\s]*?\?|(?:!(?:(?:DOCTYPE[\S\s]*?)|(?:\[CDATA\[[\S\s]*?\]\])|(?:--[\S\s]*?--)|(?:ATTLIST[\S\s]*?)|(?:ENTITY[\S\s]*?)|(?:ELEMENT[\S\s]*?))))(*SKIP)(*FAIL))>

https://regex101.com/r/uMvJn0/1

 # Mix html/xml     
 # https://regex101.com/r/uMvJn0/1     
 
 <
 (?:
    
    # Invisible content gets failed
    
    (?:
       (?:
                               # Invisible content; end tag req'd
          (                    # (1 start)
             script
           | style
           | object
           | embed
           | applet
           | noframes
           | noscript
           | noembed 
          )                    # (1 end)
          (?:
             \s+ 
             (?>
                " [\S\s]*? "
              | ' [\S\s]*? '
              | (?:
                   (?! /> )
                   [^>] 
                )?
             )+
          )?
          \s* >
       )
       
       [\S\s]*? </ \1 \s* 
       (?= > )
       (*SKIP)(*FAIL)
    )
    
  | 
    
    # This is any open html tag we will match
    
    (?:
       [\w:]+ \b 
       (?=
          (                    # (2 start)
             (?:
                " [\S\s]*? " 
              | ' [\S\s]*? ' 
              | [^>]? 
             )*
          )                    # (2 end)
          >
       )
       \2 
       (?<! / )
    )
    
  | 
    # All other tags get failed
    
    (?:
       (?: /? [\w:]+ \s* /? )
     | (?:
          [\w:]+ 
          \s+ 
          (?:
             " [\S\s]*? " 
           | ' [\S\s]*? ' 
           | [^>]? 
          )+
          \s* /?
       )
     | \? [\S\s]*? \?
     | (?:
          !
          (?:
             (?: DOCTYPE [\S\s]*? )
           | (?: \[CDATA\[ [\S\s]*? \]\] )
           | (?: -- [\S\s]*? -- )
           | (?: ATTLIST [\S\s]*? )
           | (?: ENTITY [\S\s]*? )
           | (?: ELEMENT [\S\s]*? )
          )
       )
    )
    (*SKIP)(*FAIL)
 )
 >

How to get current user, and how to use User class in MVC5?

Try something like:

var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;

Works with RTM.

Python Database connection Close

According to pyodbc documentation, connections to the SQL server are not closed by default. Some database drivers do not close connections when close() is called in order to save round-trips to the server.

To close your connection when you call close() you should set pooling to False:

import pyodbc

pyodbc.pooling = False

Python 3.1.1 string to hex

The easiest way to do it in Python 3.5 and higher is:

>>> 'halo'.encode().hex()
'68616c6f'

If you manually enter a string into a Python Interpreter using the utf-8 characters, you can do it even faster by typing b before the string:

>>> b'halo'.hex()
'68616c6f'

Equivalent in Python 2.x:

>>> 'halo'.encode('hex')
'68616c6f'

javascript how to create a validation error message without using alert

I would strongly suggest you start using jQuery. Your code would look like:

$(function() {
    $('form[name="myform"]').submit(function(e) {
        var username = $('form[name="myform"] input[name="username"]').val();
        if ( username == '') {
            e.preventDefault();
            $('#errors').text('*Please enter a username*');
        }
    });
});

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

How can I replace newlines using PowerShell?

If you want to remove all new line characters and replace them with some character (say comma) then you can use the following.

(Get-Content test.txt) -join ","

This works because Get-Content returns array of lines. You can see it as tokenize function available in many languages.

Command not found error in Bash variable assignment

When you define any variable then you do not have to put in any extra spaces.

E.g.

name = "Stack Overflow"  
// it is not valid, you will get an error saying- "Command not found"

So remove spaces:

name="Stack Overflow" 

and it will work fine.

Twitter bootstrap collapse: change display of toggle button

I guess you could look inside your downloaded code where exactly there is a + sign (but this might not be very easy).

What I'd do? I'd find the class/id of the DOM elements that contain the + sign (suppose it's ".collapsible", and with Javascript (actually jQuery):

<script>
     $(document).ready(function() {
         var content=$(".collapsible").html().replace("+", "-");
         $(".collapsible").html(content));
     });
</script>

edit Alright... Sorry I haven't looked at the bootstrap code... but I guess it works with something like slideToggle, or slideDown and slideUp... Imagine it's a slideToggle for the elements of class .collapsible, which reveal contents of some .info elements. Then:

         $(".collapsible").click(function() { 
             var content=$(".collapsible").html();
             if $(this).next().css("display") === "none") { 
                 $(".collapsible").html(content.replace("+", "-"));
             }
             else $(".collapsible").html(content.replace("-", "+"));
         });

This seems like the opposite thing to do, but since the actual animation runs in parallel, you will check css before animation, and that's why you need to check if it's visible (which will mean it will be hidden once the animation is complete) and then set the corresponding + or -.

How to increase font size in a plot in R?

For completeness, scaling text by 150% with cex = 1.5, here is a full solution:

cex <- 1.5
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
plot(...)
par(cex.lab=1, cex.axis=1, cex.main=1)

I recommend wrapping things like this to reduce boilerplate, e.g.:

plot_cex <- function(x, y, cex=1.5, ...) {
  par(cex.lab=cex, cex.axis=cex, cex.main=cex)
  plot(x, y, ...)
  par(cex.lab=1, cex.axis=1, cex.main=1)
  invisible(0)
}

which you can then use like this:

plot_cex(x=1:5, y=rnorm(5), cex=1.3)

The ... are known as ellipses in R and are used to pass additional parameters on to functions. Hence, they are commonly used for plotting. So, the following works as expected:

plot_cex(x=1:5, y=rnorm(5), cex=1.5, ylim=c(-0.5,0.5))

Full path from file input using jQuery

Well, getting full path is not possible but we can have a temporary path.

Try This:

It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-

JSFIDDLE

Here is the code :-

HTML:-

<input type="file" id="i_file" value=""> 
<input type="button" id="i_submit" value="Submit">
    <br>
<img src="" width="200" style="display:none;" />
        <br>
<div id="disp_tmp_path"></div>

JS:-

$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
    $("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));

    $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});

Its not exactly what you were looking for, but may be it can help you somewhere.

How to implement linear interpolation?

As I understand your question, you want to write some function y = interpolate(x_values, y_values, x), which will give you the y value at some x? The basic idea then follows these steps:

  1. Find the indices of the values in x_values which define an interval containing x. For instance, for x=3 with your example lists, the containing interval would be [x1,x2]=[2.5,3.4], and the indices would be i1=1, i2=2
  2. Calculate the slope on this interval by (y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1]) (ie dy/dx).
  3. The value at x is now the value at x1 plus the slope multiplied by the distance from x1.

You will additionally need to decide what happens if x is outside the interval of x_values, either it's an error, or you could interpolate "backwards", assuming the slope is the same as the first/last interval.

Did this help, or did you need more specific advice?

Memory address of an object in C#

Instead of this code, you should call GetHashCode(), which will return a (hopefully-)unique value for each instance.

You can also use the ObjectIDGenerator class, which is guaranteed to be unique.

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

Update style of a component onScroll in React.js

My bet here is using Function components with new hooks to solve it, but instead of using useEffect like in previous answers, I think the correct option would be useLayoutEffect for an important reason:

The signature is identical to useEffect, but it fires synchronously after all DOM mutations.

This can be found in React documentation. If we use useEffect instead and we reload the page already scrolled, scrolled will be false and our class will not be applied, causing an unwanted behavior.

An example:

import React, { useState, useLayoutEffect } from "react"

const Mycomponent = (props) => {
  const [scrolled, setScrolled] = useState(false)

  useLayoutEffect(() => {
    const handleScroll = e => {
      setScrolled(window.scrollY > 0)
    }

    window.addEventListener("scroll", handleScroll)

    return () => {
      window.removeEventListener("scroll", handleScroll)
    }
  }, [])

  ...

  return (
    <div className={scrolled ? "myComponent--scrolled" : ""}>
       ...
    </div>
  )
}

A possible solution to the problem could be https://codepen.io/dcalderon/pen/mdJzOYq

const Item = (props) => { 
  const [scrollY, setScrollY] = React.useState(0)

  React.useLayoutEffect(() => {
    const handleScroll = e => {
      setScrollY(window.scrollY)
    }

    window.addEventListener("scroll", handleScroll)

    return () => {
      window.removeEventListener("scroll", handleScroll)
    }
  }, [])

  return (
    <div class="item" style={{'--scrollY': `${Math.min(0, scrollY/3 - 60)}px`}}>
      Item
    </div>
  )
}

How to append one file to another in Linux from the shell?

Just for reference, using ddrescue provides an interruptible way of achieving the task if, for example, you have large files and the need to pause and then carry on at some later point:

ddrescue -o $(wc --bytes file1 | awk '{ print $1 }') file2 file1 logfile

The logfile is the important bit. You can interrupt the process with Ctrl-C and resume it by specifying the exact same command again and ddrescue will read logfile and resume from where it left off. The -o A flag tells ddrescue to start from byte A in the output file (file1). So wc --bytes file1 | awk '{ print $1 }' just extracts the size of file1 in bytes (you can just paste in the output from ls if you like).

As pointed out by ngks in the comments, the downside is that ddrescue will probably not be installed by default, so you will have to install it manually. The other complication is that there are two versions of ddrescue which might be in your repositories: see this askubuntu question for more info. The version you want is the GNU ddrescue, and on Debian-based systems is the package named gddrescue:

sudo apt install gddrescue

For other distros check your package management system for the GNU version of ddrescue.

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

How to specify function types for void (not Void) methods in Java8?

Set return type to Void instead of void and return null

// Modify existing method
public static Void displayInt(Integer i) {
    System.out.println(i);
    return null;
}

OR

// Or use Lambda
myForEach(theList, i -> {System.out.println(i);return null;});

How to count occurrences of a column value efficiently in SQL?

This should work:

SELECT age, count(age) 
  FROM Students 
 GROUP by age

If you need the id as well you could include the above as a sub query like so:

SELECT S.id, S.age, C.cnt
  FROM Students  S
       INNER JOIN (SELECT age, count(age) as cnt
                     FROM Students 
                    GROUP BY age) C ON S.age = C.age

How do I check if a number is positive or negative in C#?

bool positive = number > 0;
bool negative = number < 0;

Adding an item to an associative array

before for loop :

$data = array();

then in your loop:

$data[] = array($catagory => $question);

Save bitmap to file function

Here is the function which help you

private void saveBitmap(Bitmap bitmap,String path){
        if(bitmap!=null){
            try {
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }    
        }
    }

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

Storing Images in PostgreSQL

Quick update to mid 2015:

You can use the Postgres Foreign Data interface, to store the files in more suitable database. For example put the files in a GridFS which is part of MongoDB. Then use https://github.com/EnterpriseDB/mongo_fdw to access it in Postgres.

That has the advantages, that you can access/read/write/backup it in Postrgres and MongoDB, depending on what gives you more flexiblity.

There are also foreign data wrappers for file systems: https://wiki.postgresql.org/wiki/Foreign_data_wrappers#File_Wrappers

As an example you can use this one: https://multicorn.readthedocs.org/en/latest/foreign-data-wrappers/fsfdw.html (see here for brief usage example)

That gives you the advantage of the consistency (all linked files are definitely there) and all the other ACIDs, while there are still on the actual file system, which means you can use any file system you want and the webserver can serve them directly (OS caching applies too).

javascript Unable to get property 'value' of undefined or null reference

you have many HTML and java script mistakes includes: tag, using non UTF-8 encoding for form submission, no need,... You must use document.forms.FORMNAME or document.forms[0] for first appear form in page Corrected:

_x000D_
_x000D_
 function validate_frm_new_user_request()_x000D_
{_x000D_
    alert('test');_x000D_
    var valid = true;_x000D_
_x000D_
    if ( document.forms.frm_new_user_request.u_userid.value == "" )_x000D_
    {_x000D_
        alert ( "Please enter your valid ISID Information." );_x000D_
        document.forms.frm_new_user_request.u_userid.focus();_x000D_
        valid = false;_x000D_
  console.log("FALSE::Empty Value ");_x000D_
    }_x000D_
return valid;_x000D_
}
_x000D_
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <meta content="text/html;charset=UTF-8" http-equiv="content-type" />_x000D_
_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="" name="frm_new_user_request" id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">_x000D_
<center>_x000D_
<table>_x000D_
_x000D_
        <tr align="left">_x000D_
            <td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>_x000D_
            </tr>_x000D_
_x000D_
<tr>_x000D_
            <td align="center" colspan="4">_x000D_
                <input type="image" src="btn.png" border="0" ALT="Create New Request">_x000D_
_x000D_
                </td>_x000D_
        </tr>_x000D_
    </table>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Disabling the button after once click

jQuery now has the .one() function that limits any given event (such as "submit") to one occurrence.

Example:

$('#myForm').one('submit', function() {
    $(this).find('input[type="submit"]').attr('disabled','disabled');
});

This code will let you submit the form once, then disable the button. Change the selector in the find() function to whatever button you'd like to disable.

Note: Per Francisco Goldenstein, I've changed the selector to the form and the event type to submit. This allows you to submit the form from anywhere (places other than the button) while still disabling the button on submit.

Note 2: Per gorelog, using attr('disabled','disabled') will prevent your form from sending the value of the submit button. If you want to pass the button value, use attr('onclick','this.style.opacity = "0.6"; return false;') instead.

What is setContentView(R.layout.main)?

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

  • Activity is basically a empty window
  • SetContentView is used to fill the window with the UI provided from layout file incase of setContentView(R.layout.somae_file).
  • Here layoutfile is inflated to view and added to the Activity context(Window).

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

Android changing Floating Action Button color

The FAB is colored based on your colorAccent.

<style name="AppTheme" parent="Base.Theme.AppCompat.Light">
    <item name="colorAccent">@color/accent</item>
</style>

Create a rounded button / button with border-radius in Flutter

You can simply use RaisedButton or you can use InkWell to get custom button and also properties like onDoubleTap, onLongPress and etc.:

new InkWell(
  onTap: () => print('hello'),
  child: new Container(
    //width: 100.0,
    height: 50.0,
    decoration: new BoxDecoration(
      color: Colors.blueAccent,
      border: new Border.all(color: Colors.white, width: 2.0),
      borderRadius: new BorderRadius.circular(10.0),
    ),
    child: new Center(child: new Text('Click Me', style: new TextStyle(fontSize: 18.0, color: Colors.white),),),
  ),
),

enter image description here

If you want to use splashColor, highlightColor properties in InkWell widget, use Material widget as the parent of InkWell widget instead of decorating the container(deleting decoration property). Read why? here.

fs: how do I locate a parent folder?

Use path.join http://nodejs.org/docs/v0.4.10/api/path.html#path.join

var path = require("path"),
    fs = require("fs");

fs.readFile(path.join(__dirname, '..', '..', 'foo.bar'));

path.join() will handle leading/trailing slashes for you and just do the right thing and you don't have to try to remember when trailing slashes exist and when they dont.

Reading a text file with SQL Server

What does your text file look like?? Each line a record?

You'll have to check out the BULK INSERT statement - that should look something like:

BULK INSERT dbo.YourTableName
FROM 'D:\directory\YourFileName.csv'
WITH
(
  CODEPAGE = '1252',
  FIELDTERMINATOR = ';',
  CHECK_CONSTRAINTS
) 

Here, in my case, I'm importing a CSV file - but you should be able to import a text file just as well.

From the MSDN docs - here's a sample that hopefully works for a text file with one field per row:

BULK INSERT dbo.temp 
   FROM 'c:\temp\file.txt'
   WITH 
      (
         ROWTERMINATOR ='\n'
      )

Seems to work just fine in my test environment :-)

How to create a scrollable Div Tag Vertically?

This code creates a nice vertical scrollbar for me in Firefox and Chrome:

_x000D_
_x000D_
#answerform {
  position: absolute;
  border: 5px solid gray;
  padding: 5px;
  background: white;
  width: 300px;
  height: 400px;
  overflow-y: scroll;
}
_x000D_
<div id='answerform'>
  badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
  <br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
_x000D_
_x000D_

Here is a JS fiddle demo proving the above works.

Cell spacing in UICollectionView

Answer for Swift 3.0, Xcode 8

1.Make sure you set collection view delegate

class DashboardViewController: UIViewController {
    @IBOutlet weak var dashboardCollectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        dashboardCollectionView.delegate = self
    }
}

2.Implement UICollectionViewDelegateFlowLayout protocol, not UICollectionViewDelegate.

extension DashboardViewController: UICollectionViewDelegateFlowLayout {
    fileprivate var sectionInsets: UIEdgeInsets {
        return .zero
    }

    fileprivate var itemsPerRow: CGFloat {
        return 2
    }

    fileprivate var interitemSpace: CGFloat {
        return 5.0
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionPadding = sectionInsets.left * (itemsPerRow + 1)
        let interitemPadding = max(0.0, itemsPerRow - 1) * interitemSpace
        let availableWidth = collectionView.bounds.width - sectionPadding - interitemPadding
        let widthPerItem = availableWidth / itemsPerRow

        return CGSize(width: widthPerItem, height: widthPerItem)
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {
        return sectionInsets
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return interitemSpace
    }
}

How to increase the gap between text and underlining in CSS

I was able to Do it using the U (Underline Tag)

u {
    text-decoration: none;
    position: relative;
}
u:after {
    content: '';
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 1px;
    border-width: 0 0 1px;
    border-style: solid;
}


<a href="" style="text-decoration:none">
    <div style="text-align: right; color: Red;">
        <u> Shop Now</u>
    </div>
</a>

How can I process each letter of text using Javascript?

You can now iterate over individual Unicode code points contained in a String by using String.prototype[@@iterator], which returns a value of well known Symbol type Symbol.iterator - the default iterator for array-like Objects (String in this case).

Example code:

_x000D_
_x000D_
const str = 'The quick red  jumped over the lazy ! ???!';_x000D_
_x000D_
let iterator = str[Symbol.iterator]();_x000D_
let theChar = iterator.next();_x000D_
_x000D_
while(!theChar.done) {_x000D_
  console.log(theChar.value);_x000D_
  theChar = iterator.next();_x000D_
}_x000D_
_x000D_
// logs every unicode character as expected into the console.
_x000D_
_x000D_
_x000D_

This works with Unicode characters such as emoji or non-roman characters that would trip up legacy constructs.

Reference: MDN Link to String.prototype@@iterator.

Does "git fetch --tags" include "git fetch"?

git fetch upstream --tags

works just fine, it will only get new tags and will not get any other code base.

Error C1083: Cannot open include file: 'stdafx.h'

Add #include "afxwin.h" in your source file. It will solve your issue.

Sort an Array by keys based on another Array?

How about this solution

$order = array(1,5,2,4,3,6);

$array = array(
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
    5 => 'five',
    6 => 'six'
);

uksort($array, function($key1, $key2) use ($order) {
    return (array_search($key1, $order) > array_search($key2, $order));
});

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?

Recursively looping through an object to build a property list

Solution to flatten properties and arrays as well.

Example input:

{
  obj1: {
    prop1: "value1",
    prop2: "value2"
  },
  arr1: [
    "value1",
    "value2"
  ]
}

Output:

"arr1[0]": "value1"
"arr1[1]": "value2"
"obj1.prop1": "value1"
"obj1.prop2": "value2"

Source code:

flatten(object, path = '', res = undefined) {
      if (!Array.isArray(res)) {
          res = [];
      }
      if (object !== null && typeof object === 'object') {
          if (Array.isArray(object)) {
              for (let i = 0; i < object.length; i++) {
                  this.flatten(object[i], path + '[' + i + ']', res)
              }
          } else {
              const keys = Object.keys(object)
              for (let i = 0; i < keys.length; i++) {
                  const key = keys[i]
                  this.flatten(object[key], path ? path + '.' + key : key, res)
              }
          }
      } else {
          if (path) {
              res[path] = object
          }
      }
      return res
  }

How do I upgrade the Python installation in Windows 10?

If you are upgrading any 3.x.y to 3.x.z (patch) Python version, just go to Python downloads page get the latest version and start the installation. Since you already have Python installed on your machine installer will prompt you for "Upgrade Now". Click on that button and it will replace the existing version with a new one. You also will have to restart a computer after installation.

enter image description here

If you are upgrading from 3.x to 3.y (minor) then you will be prompted with "Install Now". In this case, you are not upgrading, but you are installing a new version of Python. You can have more than one version installed on your machine. They will be located in different directories. When you have more than one Python version on your machine you will need to use py lanucher to launch a specific version of Python.

For instance:

py -3.7

or

py -3.8

Make sure you have py launcher installed on your machine. It will be installed automatically if you are using default settings of windows installer. You can always check it if you click on "Customize installation" link on the installation window.

If you have several Python versions installed on your machine and you have a project that is using the previous version of Python using virtual environment e.g. (venv) you can upgrade Python just in that venv using:

python -m venv --upgrade "your virtual environment path"

For instance, I have Python 3.7 in my ./venv virtual environment and I would like upgrade venv to Python 3.8, I would do following

python -m venv --upgrade ./venv

iPhone get SSID without private library

Here's the cleaned up ARC version, based on @elsurudo's code:

- (id)fetchSSIDInfo {
     NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
     NSLog(@"Supported interfaces: %@", ifs);
     NSDictionary *info;
     for (NSString *ifnam in ifs) {
         info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
         NSLog(@"%@ => %@", ifnam, info);
         if (info && [info count]) { break; }
     }
     return info;
}

ORA-00060: deadlock detected while waiting for resource

I was recently struggling with a similar problem. It turned out that the database was missing indexes on foreign keys. That caused Oracle to lock many more records than required which quickly led to a deadlock during high concurrency.

Here is an excellent article with lots of good detail, suggestions, and details about how to fix a deadlock: http://www.oratechinfo.co.uk/deadlocks.html#unindex_fk

How can I change NULL to 0 when getting a single value from a SQL function?

You can use ISNULL().

SELECT ISNULL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

That should do the trick.

Reset push notification settings for app

Another just for testing solution to this is by simply changing your bundle id. Just don't forget to change it back once you're done!

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

If you are 100% sure that directories and files are ok, have a look at the project location.

There is a limit on the path length of files in the Operating System. Perhaps this limit is being exceded in your project files.

Move the project to a shorter folder (say C:/MyProject) and try again!

This was the problem for me!

How can I get an HTTP response body as a string?

Below is a simple way of accessing the response as a String using Apache HTTP Client library.

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

//... 

HttpGet get;
HttpClient httpClient;

// initialize variables above

ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(get, responseHandler);

PHP ternary operator vs null coalescing operator

Ran the below on php interactive mode (php -a on terminal). The comment on each line shows the result.

var_export (false ?? 'value2');   // false
var_export (true  ?? 'value2');   // true
var_export (null  ?? 'value2');   // value2
var_export (''    ?? 'value2');   // ""
var_export (0     ?? 'value2');   // 0

var_export (false ?: 'value2');   // value2
var_export (true  ?: 'value2');   // true
var_export (null  ?: 'value2');   // value2
var_export (''    ?: 'value2');   // value2
var_export (0     ?: 'value2');   // value2

The Null Coalescing Operator ??

  • ?? is like a "gate" that only lets NULL through.
  • So, it always returns first parameter, unless first parameter happens to be NULL.
  • This means ?? is same as ( !isset() || is_null() )

Use of ??

  • shorten !isset() || is_null() check
  • e.g $object = $object ?? new objClassName();

Stacking Null Coalese Operator

        $v = $x ?? $y ?? $z; 

        // This is a sequence of "SET && NOT NULL"s:

        if( $x  &&  !is_null($x) ){ 
            return $x; 
        } else if( $y && !is_null($y) ){ 
            return $y; 
        } else { 
            return $z; 
        }

The Ternary Operator ?:

  • ?: is like a gate that lets anything falsy through - including NULL
  • Anything falsy: 0, empty string, NULL, false, !isset(), empty()
  • Same like old ternary operator: X ? Y : Z
  • Note: ?: will throw PHP NOTICE on undefined (unset or !isset()) variables

Use of ?:

  • checking empty(), !isset(), is_null() etc
  • shorten ternary operation like !empty($x) ? $x : $y to $x ?: $y
  • shorten if(!$x) { echo $x; } else { echo $y; } to echo $x ?: $y

Stacking Ternary Operator

        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 1 ?: 0 ?: 3 ?: 2; //1
        echo 2 ?: 1 ?: 0 ?: 3; //2
        echo 3 ?: 2 ?: 1 ?: 0; //3
    
        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 0 ?: 0 ?: 2 ?: 3; //2
        echo 0 ?: 0 ?: 0 ?: 3; //3

    
        // Source & Credit: http://php.net/manual/en/language.operators.comparison.php#95997
   
        // This is basically a sequence of:

 
        if( truthy ) {}
        else if(truthy ) {}
        else if(truthy ) {}
        ..
        else {}

Stacking both, we can shorten this:

        if( isset($_GET['name']) && !is_null($_GET['name'])) {
            $name = $_GET['name'];
        } else if( !empty($user_name) ) {
             $name = $user_name; 
        } else {
            $name = 'anonymous';
        }

To this:

        $name = $_GET['name'] ?? $user_name ?: 'anonymous';

Cool, right? :-)

How to change color and font on ListView

You can select a child like

TextView tv = (TextView)lv.getChildAt(0);
tv.setTextColor(Color.RED);
tv.setTextSize(12);    

What is href="#" and why is it used?

It's a link that links to nowhere essentially (it just adds "#" onto the URL). It's used for a number of different reasons. For instance, if you're using some sort of JavaScript/jQuery and don't want the actual HTML to link anywhere.

It's also used for page anchors, which is used to redirect to a different part of the page.

How to use a calculated column to calculate another column in the same view

You could use a nested query:

Select
  ColumnA,
  ColumnB,
  calccolumn1,
  calccolumn1 / ColumnC as calccolumn2
From (
  Select
    ColumnA,
    ColumnB,
    ColumnC,
    ColumnA + ColumnB As calccolumn1
  from t42
);

With a row with values 3, 4, 5 that gives:

   COLUMNA    COLUMNB CALCCOLUMN1 CALCCOLUMN2
---------- ---------- ----------- -----------
         3          4           7         1.4

You can also just repeat the first calculation, unless it's really doing something expensive (via a function call, say):

Select
  ColumnA,
  ColumnB,
  ColumnA + ColumnB As calccolumn1,
  (ColumnA + ColumnB) / ColumnC As calccolumn2
from t42; 

   COLUMNA    COLUMNB CALCCOLUMN1 CALCCOLUMN2
---------- ---------- ----------- -----------
         3          4           7         1.4 

How to get first character of a string in SQL?

It is simple to achieve by the following

DECLARE @SomeString NVARCHAR(20) = 'This is some string'
DECLARE @Result NVARCHAR(20)

Either

SET @Result = SUBSTRING(@SomeString, 2, 3)
SELECT @Result

@Result = his

or

SET @Result = LEFT(@SomeString, 6)
SELECT @Result

@Result = This i

VBA - Select columns using numbers?

no need for loops or such.. try this..

dim startColumnas integer

dim endColumn as integer

startColumn = 7

endColumn = 24

Range(Cells(, startColumn), Cells(, endColumn)).ColumnWidth = 3.8 ' <~~ whatever width you want to set..* 

SVG: text inside rect

Programmatically display text over rect using basic Javascript

_x000D_
_x000D_
 var svg = document.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];_x000D_
_x000D_
        var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
        text.setAttribute('x', 20);_x000D_
        text.setAttribute('y', 50);_x000D_
        text.setAttribute('width', 500);_x000D_
        text.style.fill = 'red';_x000D_
        text.style.fontFamily = 'Verdana';_x000D_
        text.style.fontSize = '35';_x000D_
        text.innerHTML = "Some text line";_x000D_
_x000D_
        svg.appendChild(text);_x000D_
_x000D_
        var text2 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
        text2.setAttribute('x', 20);_x000D_
        text2.setAttribute('y', 100);_x000D_
        text2.setAttribute('width', 500);_x000D_
        text2.style.fill = 'green';_x000D_
        text2.style.fontFamily = 'Calibri';_x000D_
        text2.style.fontSize = '35';_x000D_
        text2.style.fontStyle = 'italic';_x000D_
        text2.innerHTML = "Some italic line";_x000D_
_x000D_
       _x000D_
        svg.appendChild(text2);_x000D_
_x000D_
        var text3 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
        text3.setAttribute('x', 20);_x000D_
        text3.setAttribute('y', 150);_x000D_
        text3.setAttribute('width', 500);_x000D_
        text3.style.fill = 'green';_x000D_
        text3.style.fontFamily = 'Calibri';_x000D_
        text3.style.fontSize = '35';_x000D_
        text3.style.fontWeight = 700;_x000D_
        text3.innerHTML = "Some bold line";_x000D_
_x000D_
       _x000D_
        svg.appendChild(text3);
_x000D_
    <svg width="510" height="250" xmlns="http://www.w3.org/2000/svg">_x000D_
        <rect x="0" y="0" width="510" height="250" fill="aquamarine" />_x000D_
    </svg>
_x000D_
_x000D_
_x000D_

enter image description here

MVC 3: How to render a view without its layout page when loaded via ajax?

Just put the following code on the top of the page

@{
    Layout = "";
}

Build android release apk on Phonegap 3.x CLI

i got this to work by copy pasting the signed app in the same dir as zipalign. It seems that aapt.exe could not find the source file even when given the path. i.e. this did not work zipalign -f -v 4 C:...\CordovaApp-release-unsigned.apk C:...\destination.apk it reached aapt.exeCordovaApp-release-unsigned.apk , froze and upon hitting return 'aapt.exeCordovaApp-release-unsigned.apk' is not recognized as an internal or external command, operable program or batch file. And this did zipalign -f -v 4 CordovaApp-release-unsigned.apk myappname.apk

set serveroutput on in oracle procedure

If you want to execute any procedure then firstly you have to set serveroutput on in the sqldeveloper work environment like.

->  SET SERVEROUTPUT ON;
-> BEGIN
dbms_output.put_line ('Hello World..');
dbms_output.put_line('Its displaying the values only for the Testing purpose');
END;
/

What are NR and FNR and what does "NR==FNR" imply?

Look for keys (first word of line) in file2 that are also in file1.
Step 1: fill array a with the first words of file 1:

awk '{a[$1];}' file1

Step 2: Fill array a and ignore file 2 in the same command. For this check the total number of records until now with the number of the current input file.

awk 'NR==FNR{a[$1]}' file1 file2

Step 3: Ignore actions that might come after } when parsing file 1

awk 'NR==FNR{a[$1];next}' file1 file2 

Step 4: print key of file2 when found in the array a

awk 'NR==FNR{a[$1];next} $1 in a{print $1}' file1 file2

How to Execute a Python File in Notepad ++?

Extending Reshure's answer

  1. Open Run ? Run... from the menubar in Notepad++ (shortcut: F5)

  2. In the given space, enter:

    "$(FULL_CURRENT_PATH)"  -1
    
  3. Click Run

ta da!

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

I haven't worked much with Appcelerator Titanium, but I'll put my understanding of it at the end.

I can speak a bit more to the differences between PhoneGap and Xamarin, as I work with these two 5 (or more) days a week.

If you are already familiar with C# and JavaScript, then the question I guess is, does the business logic lie in an area more suited to JavaScript or C#?

PhoneGap

PhoneGap is designed to allow you to write your applications using JavaScript and HTML, and much of the functionality that they do provide is designed to mimic the current proposed specifications for the functionality that will eventually be available with HTML5. The big benefit of PhoneGap in my opinion is that since you are doing the UI with HTML, it can easily be ported between platforms. The downside is, because you are porting the same UI between platforms, it won't feel quite as at home in any of them. Meaning that, without further tweaking, you can't have an application that feels fully at home in iOS and Android, meaning that it has the iOS and Android styling. The majority of your logic can be written using JavaScript, which means it too can be ported between platforms. If the current PhoneGap API does most of what you want, then it's pretty easy to get up and running. If however, there are things you need from the device that are not in the API, then you get into the fun of Plugin Development, which will be in the native device's development language of choice (with one caveat, but I'll get to that), which means you would likely need to get up to speed quickly in Objective-C, Java, etc. The good thing about this model, is you can usually adapt many different native libraries to serve your purpose, and many libraries already have PhoneGap Plugins. Although you might not have much experience with these languages, there will at least be a plethora of examples to work from.

Xamarin

Xamarin.iOS and Xamarin.Android (also known as MonoTouch and MonoDroid), are designed to allow you to have one library of business logic, and use this within your application, and hook it into your UI. Because it's based on .NET 4.5, you get some awesome lambda notations, LINQ, and a whole bunch of other C# awesomeness, which can make writing your business logic less painful. The downside here is that Xamarin expects that you want to make your applications truly feel native on the device, which means that you will likely end up rewriting your UI for each platform, before hooking it together with the business logic. I have heard about MvvmCross, which is designed to make this easier for you, but I haven't really had an opportunity to look into it yet. If you are familiar with the MVVM system in C#, you may want to have a look at this. When it comes to native libraries, MonoTouch becomes interesting. MonoTouch requires a Binding library to tell your C# code how to link into the underlying Objective-C and Java code. Some of these libraries will already have bindings, but if yours doesn't, creating one can be, interesting. Xamarin has made a tool called Objective Sharpie to help with this process, and for the most part, it will get you 95% of the way there. The remaining 5% will probably take 80% of your time attempting to bind a library.

Update

As noted in the comments below, Xamarin has released Xamarin Forms which is a cross platform abstraction around the platform specific UI components. Definitely worth the look.

PhoneGap / Xamarin Hybrid

Now because I said I would get to it, the caveat mentioned in PhoneGap above, is a Hybrid approach, where you can use PhoneGap for part, and Xamarin for part. I have quite a bit of experience with this, and I would caution you against it. Highly. The problem with this, is it is such a no mans' land that if you ever run into issues, almost no one will have come close to what you're doing, and will question what you're trying to do greatly. It is doable, but it's definitely not fun.

Appcelerator Titanium

As I mentioned before, I haven't worked much with Appcelerator Titanium, So for the differences between them, I will suggest you look at Comparing Titanium and Phonegap or Comparison between Corona, Phonegap, Titanium as it has a very thorough description of the differences. Basically, it appears that though they both use JavaScript, how that JavaScript is interpreted is slightly different. With Titanium, you will be writing your JavaScript to the Titanium SDK, whereas with PhoneGap, you will write your application using the PhoneGap API. As PhoneGap is very HTML5 and JavaScript standards compliant, you can use pretty much any JavaScript libraries you want, such as JQuery. With PhoneGap your user interface will be composed of HTML and CSS. With Titanium, you will benefit from their Cross-platform XML which appears to generate Native components. This means it will definitely have a better native look and feel.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

IT IS POSSIBLE!

_x000D_
_x000D_
var i = 0;_x000D_
_x000D_
with({_x000D_
  get a() {_x000D_
    return ++i;_x000D_
  }_x000D_
}) {_x000D_
  if (a == 1 && a == 2 && a == 3)_x000D_
    console.log("wohoo");_x000D_
}
_x000D_
_x000D_
_x000D_

This uses a getter inside of a with statement to let a evaluate to three different values.

... this still does not mean this should be used in real code...

Even worse, this trick will also work with the use of ===.

_x000D_
_x000D_
  var i = 0;_x000D_
_x000D_
  with({_x000D_
    get a() {_x000D_
      return ++i;_x000D_
    }_x000D_
  }) {_x000D_
    if (a !== a)_x000D_
      console.log("yep, this is printed.");_x000D_
  }
_x000D_
_x000D_
_x000D_

MySQL - UPDATE multiple rows with different values in one query

MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.

INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
 cod_user=VALUES(cod_user), date=VALUES(date)

This assumes that the user_rol, cod_office combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list. If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.

However, this approach makes prepared statements easier to build and more concise.

Connecting to TCP Socket from browser using javascript

See jsocket. Haven't used it myself. Been more than 3 years since last update (as of 26/6/2014).

* Uses flash :(

From the documentation:

<script type='text/javascript'>
    // Host we are connecting to
    var host = 'localhost'; 
    // Port we are connecting on
    var port = 3000;

    var socket = new jSocket();

    // When the socket is added the to document 
    socket.onReady = function(){
            socket.connect(host, port);             
    }

    // Connection attempt finished
    socket.onConnect = function(success, msg){
            if(success){
                    // Send something to the socket
                    socket.write('Hello world');            
            }else{
                    alert('Connection to the server could not be estabilished: ' + msg);            
            }       
    }
    socket.onData = function(data){
            alert('Received from socket: '+data);   
    }

    // Setup our socket in the div with the id="socket"
    socket.setup('mySocket');       
</script>

What are the undocumented features and limitations of the Windows FINDSTR command?

I'd like to report a bug regarding the section Source of data to search in the first answer when using en dash (–) or em dash (—) within the filename.

More specifically, if you are about to use the first option - filenames specified as arguments, the file won't be found. As soon as you use either option 2 - stdin via redirection or 3 - data stream from a pipe, findstr will find the file.

For example, this simple batch script:

echo off
chcp 1250 > nul
set INTEXTFILE1=filename with – dash.txt
set INTEXTFILE2=filename with — dash.txt

rem 3 way of findstr use with en dashed filename
echo.
echo Filename with en dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE1%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE1%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE1%" | findstr .
echo.
echo.
rem The same set of operations with em dashed filename
echo Filename with em dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE2%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE2%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE2%" | findstr .
echo.

pause

will print:

Filename with en dash:

  1. As argument
    FINDSTR: Cannot open filename with - dash.txt

  2. As stdin via redirection
    I am the file with an en dash.

  3. As datastream from a pipe
    I am the file with an en dash.

Filename with em dash:

  1. As argument
    FINDSTR: Cannot open filename with - dash.txt

  2. As stdin via redirection
    I am the file with an em dash.

  3. As datastream from a pipe
    I am the file with an em dash.

Hope it helps.

M.

How can I pass an argument to a PowerShell script?

You can also define a variable directly in the PowerShell command line and then execute the script. The variable will be defined there, too. This helped me in a case where I couldn't modify a signed script.

Example:

 PS C:\temp> $stepsize = 30
 PS C:\temp> .\itunesForward.ps1

with iTunesForward.ps1 being

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $stepsize
}

How to open remote files in sublime text 3

Base on this.

Step by step:

  • On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub
  • On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line
  • On your remote server:

    sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/local/bin/rsub
    

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.

Java Regex Replace with Capturing Group

How about:

if (regexMatcher.find()) {
    resultString = regexMatcher.replaceAll(
            String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

To get the first match, use #find(). After that, you can use #group(1) to refer to this first match, and replace all matches by the first maches value multiplied by 3.

And in case you want to replace each match with that match's value multiplied by 3:

    Pattern p = Pattern.compile("(\\d{1,2})");
    Matcher m = p.matcher("12 54 1 65");
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
    System.out.println(s.toString());

You may want to look through Matcher's documentation, where this and a lot more stuff is covered in detail.

How to enumerate an enum

It looks to me like you really want to print out the names of each enum, rather than the values. In which case Enum.GetNames() seems to be the right approach.

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (string name in Enum.GetNames(typeof(Suits)))
    {
        System.Console.WriteLine(name);
    }
}

By the way, incrementing the value is not a good way to enumerate the values of an enum. You should do this instead.

I would use Enum.GetValues(typeof(Suit)) instead.

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (var suit in Enum.GetValues(typeof(Suits)))
    {
        System.Console.WriteLine(suit.ToString());
    }
}

How to view instagram profile picture in full-size?

You can even set the prof. pic size to its high resolution that is '1080x1080'

replace "150x150" with 1080x1080 and remove /vp/ from the link.

What does functools.wraps do?

In short, functools.wraps is just a regular function. Let's consider this official example. With the help of the source code, we can see more details about the implementation and the running steps as follows:

  1. wraps(f) returns an object, say O1. It is an object of the class Partial
  2. The next step is @O1... which is the decorator notation in python. It means

wrapper=O1.__call__(wrapper)

Checking the implementation of __call__, we see that after this step, (the left hand side )wrapper becomes the object resulted by self.func(*self.args, *args, **newkeywords) Checking the creation of O1 in __new__, we know self.func is the function update_wrapper. It uses the parameter *args, the right hand side wrapper, as its 1st parameter. Checking the last step of update_wrapper, one can see the right hand side wrapper is returned, with some of attributes modified as needed.

whitespaces in the path of windows filepath

path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv"

Closing the path in r"string" also solved this problem very well.

SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

chart.js load totally new data

There is a way to do this without clearing the canvas or starting over, but you have to man handle the creation of the chart so that the data is in the same format for when you update.

Here is how I did it.

    var ctx = document.getElementById("myChart").getContext("2d");
    if (chartExists) {
        for (i=0;i<10;i++){
            myNewChart.scale.xLabels[i]=dbLabels[i]; 
            myNewChart.datasets[0].bars[i].value=dbOnAir[i];
        }
        myNewChart.update();
      }else{
          console.log('chart doesnt exist');
          myNewChart = new Chart(ctx).Bar(dataNew);
          myNewChart.removeData();
          for (i=0;i<10;i++){
              myNewChart.addData([10],dbLabels[i]);
          }
          for (i=0;i<10;i++){      
              myNewChart.datasets[0].bars[i].value=dbOnAir[i];
          }
          myNewChart.update();
          chartExists=true;
        }

I basically scrap the data loaded in at creation, and then reform with the add data method. This means that I can then access all the points. Whenever I have tried to access the data structure that is created by the:

Chart(ctx).Bar(dataNew);

command, I can't access what I need. This means you can change all the data points, in the same way you created them, and also call update() without animating completely from scratch.

How can I list ALL DNS records?

host -a works well, similar to dig any.

EG:

$ host -a google.com
Trying "google.com"
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 10403
;; flags: qr rd ra; QUERY: 1, ANSWER: 18, AUTHORITY: 0, ADDITIONAL: 0


;; QUESTION SECTION:
;google.com.            IN  ANY

;; ANSWER SECTION:
google.com.     1165    IN  TXT "v=spf1 include:_spf.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all"
google.com.     53965   IN  SOA ns1.google.com. dns-admin.google.com. 2014112500 7200 1800 1209600 300
google.com.     231 IN  A   173.194.115.73
google.com.     231 IN  A   173.194.115.78
google.com.     231 IN  A   173.194.115.64
google.com.     231 IN  A   173.194.115.65
google.com.     231 IN  A   173.194.115.66
google.com.     231 IN  A   173.194.115.67
google.com.     231 IN  A   173.194.115.68
google.com.     231 IN  A   173.194.115.69
google.com.     231 IN  A   173.194.115.70
google.com.     231 IN  A   173.194.115.71
google.com.     231 IN  A   173.194.115.72
google.com.     128 IN  AAAA    2607:f8b0:4000:809::1001
google.com.     40766   IN  NS  ns3.google.com.
google.com.     40766   IN  NS  ns4.google.com.
google.com.     40766   IN  NS  ns1.google.com.
google.com.     40766   IN  NS  ns2.google.com.

Angular: conditional class with *ngClass

ngClass syntax:

[ngClass]="{'classname' : conditionFlag}"

You can use like this:

<ol class="breadcrumb">
  <li [ngClass]="{'active': step==='step1'}" (click)="step='step1'">Step1</li>
  <li [ngClass]="{'active': step==='step2'}" (click)="step='step2'">Step2</li>
  <li [ngClass]="{'active': step==='step3'}" (click)="step='step3'">Step3</li>
</ol>

Getting and removing the first character of a string

Use this function from stringi package

> x <- 'hello stackoverflow'
> stri_sub(x,2)
[1] "ello stackoverflow"

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

This is probably due to its lack of connections to the Hive Meta Store,my hive Meta Store is stored in Mysql,so I need to visit Mysql,So I add a dependency in my build.sbt

libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.38"

and the problem is solved!

Bitwise and in place of modulus operator

In this specific case (mod 7), we still can replace %7 with bitwise operators:

// Return X%7 for X >= 0.
int mod7(int x)
{
  while (x > 7) x = (x&7) + (x>>3);
  return (x == 7)?0:x;
}

It works because 8%7 = 1. Obviously, this code is probably less efficient than a simple x%7, and certainly less readable.

Regular Expression for alphanumeric and underscores

I believe you are not taking Latin and Unicode characters in your matches. For example, if you need to take "ã" or "ü" chars, the use of "\w" won't work.

You can, alternatively, use this approach:

^[A-ZÀ-Ýa-zà-ý0-9_]+$

Hope it helps!

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn't static. Thus you need an instance of your form to call SetTextboxText.

Filter Java Stream to 1 and only 1 element

The "escape hatch" operation that lets you do weird things that are not otherwise supported by streams is to ask for an Iterator:

Iterator<T> it = users.stream().filter((user) -> user.getId() < 0).iterator();
if (!it.hasNext()) 
    throw new NoSuchElementException();
else {
    result = it.next();
    if (it.hasNext())
        throw new TooManyElementsException();
}

Guava has a convenience method to take an Iterator and get the only element, throwing if there are zero or multiple elements, which could replace the bottom n-1 lines here.

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

The serial port communication programs moserial or gtkterm provide an easy way to check connectivity and modify /dev/ttyUSB0 (or /dev/ttyUSB1!) settings. Even though there maybe only a single USB to RS232 adapter, the n designation /dev/ttyUSBn can and does change periodically! Both moserial and gtkterm will show what port designation is relevant in their respective pull down menus when selecting an appropriate port to use.

Check out help.ubuntu.com/community/Minicom for details on minicom.

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

How to get a list column names and datatypes of a table in PostgreSQL?

To get information about the table's column, you can use:

\dt+ [tablename]

To get information about the datatype in the table, you can use:

\dT+ [datatype]

Change label text using JavaScript

Try this:

<label id="lbltipAddedComment"></label>
<script type="text/javascript"> 
      document.getElementById('<%= lbltipAddedComment.ClientID %>').innerHTML = 'your tip has been submitted!';
</script>

Take a screenshot via a Python script on Linux

I couldn't take screenshot in Linux with pyscreenshot or scrot because output of pyscreenshot was just a black screen png image file.

but thank god there was another very easy way for taking screenshot in Linux without installing anything. just put below code in your directory and run with python demo.py

import os
os.system("gnome-screenshot --file=this_directory.png")

also there is many available options for gnome-screenshot --help

Application Options:
  -c, --clipboard                Send the grab directly to the clipboard
  -w, --window                   Grab a window instead of the entire screen
  -a, --area                     Grab an area of the screen instead of the entire screen
  -b, --include-border           Include the window border with the screenshot
  -B, --remove-border            Remove the window border from the screenshot
  -p, --include-pointer          Include the pointer with the screenshot
  -d, --delay=seconds            Take screenshot after specified delay [in seconds]
  -e, --border-effect=effect     Effect to add to the border (shadow, border, vintage or none)
  -i, --interactive              Interactively set options
  -f, --file=filename            Save screenshot directly to this file
  --version                      Print version information and exit
  --display=DISPLAY              X display to use

How to download a file via FTP with Python ftplib

FILENAME = 'StarWars.avi'    

with ftplib.FTP(FTP_IP, FTP_LOGIN, FTP_PASSWD) as ftp:
    ftp.cwd('movies')
    with open(FILENAME, 'wb') as f:
        ftp.retrbinary('RETR ' + FILENAME, f.write)

Of course it would we be wise to handle possible errors.

How to create a MySQL hierarchical recursive query?

Did the same thing for another quetion here

Mysql select recursive get all child with multiple level

The query will be :

SELECT GROUP_CONCAT(lv SEPARATOR ',') FROM (
  SELECT @pv:=(
    SELECT GROUP_CONCAT(id SEPARATOR ',')
    FROM table WHERE parent_id IN (@pv)
  ) AS lv FROM table 
  JOIN
  (SELECT @pv:=1)tmp
  WHERE parent_id IN (@pv)
) a;

How to check file input size with jQuery?

You can do this type of checking with Flash or Silverlight but not Javascript. The javascript sandbox does not allow access to the file system. The size check would need to be done server side after it has been uploaded.

If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. This way, if the do have Silverlight/Flash installed their experience will be a bit more rich.

Why isn't textarea an input[type="textarea"]?

A textarea can contain multiple lines of text, so one wouldn't be able to pre-populate it using a value attribute.

Similarly, the select element needs to be its own element to accommodate option sub-elements.

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

Disable form autofill in Chrome without disabling autocomplete

This might help: https://stackoverflow.com/a/4196465/683114

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

It looks like on load, it finds all inputs with autofill, adds their outerHTML and removes the original, while preserving value and name (easily changed to preserve ID etc)

If this preserves the autofill text, you could just set

var text = "";   /* $(this).val(); */

From the original form where this was posted, it claims to preserve autocomplete. :)

Good luck!

nodejs mysql Error: Connection lost The server closed the connection

Try to use this code to handle server disconnect:

var db_config = {
  host: 'localhost',
    user: 'root',
    password: '',
    database: 'example'
};

var connection;

function handleDisconnect() {
  connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connection.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      handleDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

handleDisconnect();

In your code i am missing the parts after connection = mysql.createConnection(db_config);

How to resolve 'npm should be run outside of the node repl, in your normal shell'

enter image description here

Just open Node.js commmand promt as run as administrator

In where shall I use isset() and !empty()

!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations

<?php
$array = [ "name_new" => "print me"];

if (!empty($array['name'])){
   echo $array['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array2 = [ "name" => NULL];

if (!empty($array2['name'])){
   echo $array2['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array3 = [ "name" => ""];

if (!empty($array3['name'])){
   echo $array3['name'];
}

//output : {nothing}  

////////////////////////////////////////////////////////////////////

$array4 = [1,2];

if (!empty($array4['name'])){
   echo $array4['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array5 = [];

if (!empty($array5['name'])){
   echo $array5['name'];
}

//output : {nothing}

?>

Getting the text from a drop-down box

function getValue(obj)
{  
   // it will return the selected text
   // obj variable will contain the object of check box
   var text = obj.options[obj.selectedIndex].innerHTML ; 

}

HTML Snippet

 <asp:DropDownList ID="ddl" runat="server" CssClass="ComboXXX" 
  onchange="getValue(this)">
</asp:DropDownList>

system("pause"); - Why is it wrong?

In summary, it has to pause the programs execution and make a system call and allocate unnecessary resources when you could be using something as simple as cin.get(). People use System("PAUSE") because they want the program to wait until they hit enter to they can see their output. If you want a program to wait for input, there are built in functions for that which are also cross platform and less demanding.

Further explanation in this article.

Retrieve CPU usage and memory usage of a single process on Linux?

Launch a program and monitor it

This form is useful if you want to benchmark an executable easily:

topp() (
  $* &>/dev/null &
  pid="$!"
  trap ':' INT
  echo 'CPU  MEM'
  while sleep 1; do ps --no-headers -o '%cpu,%mem' -p "$pid"; done
  kill "$pid"
)
topp ./myprog arg1 arg2

Now when you hit Ctrl + C it exits the program and stops monitoring. Sample output:

CPU  MEM
20.0  1.3
35.0  1.3
40.0  1.3

Related: https://unix.stackexchange.com/questions/554/how-to-monitor-cpu-memory-usage-of-a-single-process

Tested on Ubuntu 16.04.

How to specify legend position in matplotlib in graph coordinates

The loc parameter specifies in which corner of the bounding box the legend is placed. The default for loc is loc="best" which gives unpredictable results when the bbox_to_anchor argument is used.
Therefore, when specifying bbox_to_anchor, always specify loc as well.

The default for bbox_to_anchor is (0,0,1,1), which is a bounding box over the complete axes. If a different bounding box is specified, is is usually sufficient to use the first two values, which give (x0, y0) of the bounding box.

Below is an example where the bounding box is set to position (0.6,0.5) (green dot) and different loc parameters are tested. Because the legend extents outside the bounding box, the loc parameter may be interpreted as "which corner of the legend shall be placed at position given by the 2-tuple bbox_to_anchor argument".

enter image description here

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6, 3
fig, axes = plt.subplots(ncols=3)
locs = ["upper left", "lower left", "center right"]
for l, ax in zip(locs, axes.flatten()):
    ax.set_title(l)
    ax.plot([1,2,3],[2,3,1], "b-", label="blue")
    ax.plot([1,2,3],[1,2,1], "r-", label="red")
    ax.legend(loc=l, bbox_to_anchor=(0.6,0.5))
    ax.scatter((0.6),(0.5), s=81, c="limegreen", transform=ax.transAxes)

plt.tight_layout()    
plt.show()

See especially this answer for a detailed explanation and the question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? .


If you want to specify the legend position in other coordinates than axes coordinates, you can do so by using the bbox_transform argument. If may make sense to use figure coordinates

ax.legend(bbox_to_anchor=(1,0), loc="lower right",  bbox_transform=fig.transFigure)

It may not make too much sense to use data coordinates, but since you asked for it this would be done via bbox_transform=ax.transData.

Print JSON parsed object?

If you want to debug why not use console debug

window.console.debug(jsonObject);

Form onSubmit determine which submit button was pressed

First Suggestion:

Create a Javascript Variable that will reference the button clicked. Lets call it buttonIndex

<input type="submit" onclick="buttonIndex=0;" name="save" value="Save" />
<input type="submit" onclick="buttonIndex=1;" name="saveAndAdd" value="Save and add another" />

Now, you can access that value. 0 means the save button was clicked, 1 means the saveAndAdd Button was clicked.

Second Suggestion

The way I would handle this is to create two JS functions that handle each of the two buttons.

First, make sure your form has a valid ID. For this example, I'll say the ID is "myForm"

change

<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />

to

<input type="submit" onclick="submitFunc();return(false);" name="save" value="Save" />
<input type="submit" onclick="submitAndAddFunc();return(false);" name="saveAndAdd" value="Save and add 

the return(false) will prevent your form submission from actually processing, and call your custom functions, where you can submit the form later on.

Then your functions will work something like this...

function submitFunc(){
    // Do some asyncrhnous stuff, that will later on submit the form
    if (okToSubmit) {
        document.getElementById('myForm').submit();
    }
}
function submitAndAddFunc(){
    // Do some asyncrhnous stuff, that will later on submit the form
    if (okToSubmit) {
        document.getElementById('myForm').submit();
    }
}

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

How can I reverse a list in Python?

You can also use the bitwise complement of the array index to step through the array in reverse:

>>> array = [0, 10, 20, 40]
>>> [array[~i] for i, _ in enumerate(array)]
[40, 20, 10, 0]

Whatever you do, don't do it this way ;)

CSS pseudo elements in React

Inline styling does not support pseudos or at-rules (e.g., @media). Recommendations range from reimplement CSS features in JavaScript for CSS states like :hover via onMouseEnter and onMouseLeave to using more elements to reproduce pseudo-elements like :after and :before to just use an external stylesheet.

Personally dislike all of those solutions. Reimplementing CSS features via JavaScript does not scale well -- neither does adding superfluous markup.

Imagine a large team wherein each developer is recreating CSS features like :hover. Each developer will do it differently, as teams grow in size, if it can be done, it will be done. Fact is with JavaScript there are about n ways to reimplement CSS features, and over time you can bet on every one of those ways being implemented with the end result being spaghetti code.

So what to do? Use CSS. Granted you asked about inline styling going to assume you're likely in the CSS-in-JS camp (me too!). Have found colocating HTML and CSS to be as valuable as colocating JS and HTML, lots of folks just don't realise it yet (JS-HTML colocation had lots of resistance too at first).

Made a solution in this space called Style It that simply lets your write plaintext CSS in your React components. No need to waste cycles reinventing CSS in JS. Right tool for the right job, here is an example using :after:

npm install style-it --save

Functional Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return Style.it(`
      #heart {
        position: relative;
        width: 100px;
        height: 90px;
      }
      #heart:before,
      #heart:after {
        position: absolute;
        content: "";
        left: 50px;
        top: 0;
        width: 50px;
        height: 80px;
        background: red;
        -moz-border-radius: 50px 50px 0 0;
        border-radius: 50px 50px 0 0;
        -webkit-transform: rotate(-45deg);
        -moz-transform: rotate(-45deg);
        -ms-transform: rotate(-45deg);
        -o-transform: rotate(-45deg);
        transform: rotate(-45deg);
        -webkit-transform-origin: 0 100%;
        -moz-transform-origin: 0 100%;
        -ms-transform-origin: 0 100%;
        -o-transform-origin: 0 100%;
        transform-origin: 0 100%;
      }
      #heart:after {
        left: 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        -o-transform: rotate(45deg);
        transform: rotate(45deg);
        -webkit-transform-origin: 100% 100%;
        -moz-transform-origin: 100% 100%;
        -ms-transform-origin: 100% 100%;
        -o-transform-origin: 100% 100%;
        transform-origin :100% 100%;
      }
    `,
      <div id="heart" />
    );
  }
}

export default Intro;

JSX Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return (
      <Style>
      {`
        #heart {
          position: relative;
          width: 100px;
          height: 90px;
        }
        #heart:before,
        #heart:after {
          position: absolute;
          content: "";
          left: 50px;
          top: 0;
          width: 50px;
          height: 80px;
          background: red;
          -moz-border-radius: 50px 50px 0 0;
          border-radius: 50px 50px 0 0;
          -webkit-transform: rotate(-45deg);
          -moz-transform: rotate(-45deg);
          -ms-transform: rotate(-45deg);
          -o-transform: rotate(-45deg);
          transform: rotate(-45deg);
          -webkit-transform-origin: 0 100%;
          -moz-transform-origin: 0 100%;
          -ms-transform-origin: 0 100%;
          -o-transform-origin: 0 100%;
          transform-origin: 0 100%;
        }
        #heart:after {
          left: 0;
          -webkit-transform: rotate(45deg);
          -moz-transform: rotate(45deg);
          -ms-transform: rotate(45deg);
          -o-transform: rotate(45deg);
          transform: rotate(45deg);
          -webkit-transform-origin: 100% 100%;
          -moz-transform-origin: 100% 100%;
          -ms-transform-origin: 100% 100%;
          -o-transform-origin: 100% 100%;
          transform-origin :100% 100%;
        }
     `}

      <div id="heart" />
    </Style>
  }
}

export default Intro;

Heart example pulled from CSS-Tricks

npm check and update package if needed

  • To update a single local package:

    1. First find out your outdated packages:

      npm outdated

    2. Then update the package or packages that you want manually as:

      npm update --save package_name

This way it is not necessary to update your local package.json file.

Note that this will update your package to the latest version.

  • If you write some version in your package.json file and do:

    npm update package_name

    In this case you will get just the next stable version (wanted) regarding the version that you wrote in your package.json file.

And with npm list (package_name) you can find out the current version of your local packages.

How to underline a UILabel in swift?

Underline to multiple strings in a sentence.

extension UILabel {
    func underlineMyText(range1:String, range2:String) {
        if let textString = self.text {

            let str = NSString(string: textString)
            let firstRange = str.range(of: range1)
            let secRange = str.range(of: range2)
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: firstRange)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: secRange)
            attributedText = attributedString
        }
    }
}

Use by this way.

    lbl.text = "By continuing you agree to our Terms of Service and Privacy Policy."
    lbl.underlineMyText(range1: "Terms of Service", range2: "Privacy Policy.")

Identify duplicate values in a list in Python

These answers are O(n), so a little more code than using mylist.count() but much more efficient as mylist gets longer

If you just want to know the duplicates, use collections.Counter

from collections import Counter
mylist = [20, 30, 25, 20]
[k for k,v in Counter(mylist).items() if v>1]

If you need to know the indices,

from collections import defaultdict
D = defaultdict(list)
for i,item in enumerate(mylist):
    D[item].append(i)
D = {k:v for k,v in D.items() if len(v)>1}

Passing arguments to C# generic new() of templated type

If you have access to the class you're going to use, you can use this approach which I used.

Create an interface that has an alternative creator:

public interface ICreatable1Param
{
    void PopulateInstance(object Param);
}

Make your classes with an empty creator and implement this method:

public class MyClass : ICreatable1Param
{
    public MyClass() { //do something or nothing }
    public void PopulateInstance (object Param)
    {
        //populate the class here
    }
}

Now use your generic methods:

public void MyMethod<T>(...) where T : ICreatable1Param, new()
{
    //do stuff
    T newT = new T();
    T.PopulateInstance(Param);
}

If you don't have access, wrap the target class:

public class MyClass : ICreatable1Param
{
    public WrappedClass WrappedInstance {get; private set; }
    public MyClass() { //do something or nothing }
    public void PopulateInstance (object Param)
    {
        WrappedInstance = new WrappedClass(Param);
    }
}

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

most answers are true . and some another reasons that happens are

? your min sdk smaller than device sdk.
? you have the older application in your device with the same package name

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Editable 'Select' element

Nothing is impossible. Here's a solution that simply sets the value of a text input whenever the value of the <select> changes (rendering has been tested on Firefox and Google Chrome):

_x000D_
_x000D_
.select-editable {position:relative; background-color:white; border:solid grey 1px;  width:120px; height:18px;}_x000D_
.select-editable select {position:absolute; top:0px; left:0px; font-size:14px; border:none; width:120px; margin:0;}_x000D_
.select-editable input {position:absolute; top:0px; left:0px; width:100px; padding:1px; font-size:12px; border:none;}_x000D_
.select-editable select:focus, .select-editable input:focus {outline:none;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" name="format" value=""/>_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/nwH8A/

The next example adds the user input to the empty option slot of the <select> (thanks to @TomerPeled). It also has a little bit more flexible/variable CSS:

_x000D_
_x000D_
.select-editable {position:relative; width:120px;}_x000D_
.select-editable > * {position:absolute; top:0; left:0; box-sizing:border-box; outline:none;}_x000D_
.select-editable select {width:100%;}_x000D_
.select-editable input {width:calc(100% - 20px); margin:1px; border:none; text-overflow:ellipsis;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" onchange="this.previousElementSibling.selectedIndex=0" value="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/pu7cndLv/1/


DataList

In HTML5 you can also do this with the <input> list attribute and <datalist> element:

_x000D_
_x000D_
<input list="browsers" name="browser">_x000D_
<datalist id="browsers">_x000D_
  <option value="Internet Explorer">_x000D_
  <option value="Firefox">_x000D_
  <option value="Chrome">_x000D_
  <option value="Opera">_x000D_
  <option value="Safari">_x000D_
</datalist>_x000D_
(click once to focus and edit, click again to see option dropdown)
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/hrkxebtw/

But this acts more like an auto-complete list; once you start typing, only the options that contain the typed string are left as suggestions. Depending on what you want to use it for, this may or may not be practical.

MySQL parameterized queries

The linked docs give the following example:

   cursor.execute ("""
         UPDATE animal SET name = %s
         WHERE name = %s
       """, ("snake", "turtle"))
   print "Number of rows updated: %d" % cursor.rowcount

So you just need to adapt this to your own code - example:

cursor.execute ("""
            INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
            VALUES
                (%s, %s, %s, %s, %s, %s)

        """, (var1, var2, var3, var4, var5, var6))

(If SongLength is numeric, you may need to use %d instead of %s).

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

jQuery checkbox change and click event

Try this

$('#checkbox1').click(function() {
        if (!this.checked) {
            var sure = confirm("Are you sure?");
            this.checked = sure;
            $('#textbox1').val(sure.toString());
        }
    });

PostgreSQL ERROR: canceling statement due to conflict with recovery

As stated here about hot_standby_feedback = on :

Well, the disadvantage of it is that the standby can bloat the master, which might be surprising to some people, too

And here:

With what setting of max_standby_streaming_delay? I would rather default that to -1 than default hot_standby_feedback on. That way what you do on the standby only affects the standby


So I added

max_standby_streaming_delay = -1

And no more pg_dump error for us, nor master bloat :)

For AWS RDS instance, check http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.html

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

You either need to import the project as a Gradle project from within Idea. When you add a dependency you need to open the Gradle window and perform a refresh.

Alternatively generate the project files from gradle with this:

build.gradle:

apply plugin: 'idea'

And then run:

$ gradle idea

If you modify the dependencies you will need to rerun the above again.

Upload folder with subfolders using S3 and the AWS console

Solution 1:

var AWS = require('aws-sdk');
var path = require("path");
var fs = require('fs');

const uploadDir = function(s3Path, bucketName) {

    let s3 = new AWS.S3({
    accessKeyId: process.env.S3_ACCESS_KEY,
    secretAccessKey: process.env.S3_SECRET_KEY
    });

    function walkSync(currentDirPath, callback) {
        fs.readdirSync(currentDirPath).forEach(function (name) {
            var filePath = path.join(currentDirPath, name);
            var stat = fs.statSync(filePath);
            if (stat.isFile()) {
                callback(filePath, stat);
            } else if (stat.isDirectory()) {
                walkSync(filePath, callback);
            }
        });
    }

    walkSync(s3Path, function(filePath, stat) {
        let bucketPath = filePath.substring(s3Path.length+1);
        let params = {Bucket: bucketName, Key: bucketPath, Body: fs.readFileSync(filePath) };
        s3.putObject(params, function(err, data) {
            if (err) {
                console.log(err)
            } else {
                console.log('Successfully uploaded '+ bucketPath +' to ' + bucketName);
            }
        });

    });
};
uploadDir("path to your folder", "your bucket name");

Solution 2:

aws s3 cp SOURCE_DIR s3://DEST_BUCKET/ --recursive

Call JavaScript function on DropDownList SelectedIndexChanged Event:

Or you can do it like as well:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>

javascript: calculate x% of a number

var result = (35.8 / 100) * 10000;

(Thank you jball for this change of order of operations. I didn't consider it).

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Copied from the stacktrace:

BeanInstantiationException: Could not instantiate bean class [com.gestEtu.project.model.dao.CompteDAOHib]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.gestEtu.project.model.dao.CompteDAOHib.<init>()

By default, Spring will try to instantiate beans by calling a default (no-arg) constructor. The problem in your case is that the implementation of the CompteDAOHib has a constructor with a SessionFactory argument. By adding the @Autowired annotation to a constructor, Spring will attempt to find a bean of matching type, SessionFactory in your case, and provide it as a constructor argument, e.g.

@Autowired
public CompteDAOHib(SessionFactory sessionFactory) {
    // ...
}

How to send FormData objects with Ajax-requests in jQuery?

If you want to submit files using ajax use "jquery.form.js" This submits all form elements easily.

Samples http://jquery.malsup.com/form/#ajaxSubmit

rough view :

<form id='AddPhotoForm' method='post' action='../photo/admin_save_photo.php' enctype='multipart/form-data'>


<script type="text/javascript">
function showResponseAfterAddPhoto(responseText, statusText)
{ 
    information= responseText;
    callAjaxtolist();
    $("#AddPhotoForm").resetForm();
    $("#photo_msg").html('<div class="album_msg">Photo uploaded Successfully...</div>');        
};

$(document).ready(function(){
    $('.add_new_photo_div').live('click',function(){
            var options = {success:showResponseAfterAddPhoto};  
            $("#AddPhotoForm").ajaxSubmit(options);
        });
});
</script>

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

If you use mutexes to protect all your data, you really shouldn't need to worry. Mutexes have always provided sufficient ordering and visibility guarantees.

Now, if you used atomics, or lock-free algorithms, you need to think about the memory model. The memory model describes precisely when atomics provide ordering and visibility guarantees, and provides portable fences for hand-coded guarantees.

Previously, atomics would be done using compiler intrinsics, or some higher level library. Fences would have been done using CPU-specific instructions (memory barriers).

Convert Java String to sql.Timestamp

If you get time as string in format such as 1441963946053 you simply could do something as following:

//String timestamp;
Long miliseconds = Long.valueOf(timestamp);
Timestamp ti = new Timestamp(miliseconds);

Is there a way to remove the separator line from a UITableView?

You can do this in the storyboard / xib editor as well. Just set Seperator to none.

enter image description here

How to display count of notifications in app launcher icon

This is sample and best way for showing badge on notification launcher icon.

Add This Class in your application

public class BadgeUtils {

    public static void setBadge(Context context, int count) {
        setBadgeSamsung(context, count);
        setBadgeSony(context, count);
    }

    public static void clearBadge(Context context) {
        setBadgeSamsung(context, 0);
        clearBadgeSony(context);
    }


    private static void setBadgeSamsung(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    }

    private static void setBadgeSony(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }


    private static void clearBadgeSony(Context context) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(0));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }

    private static String getLauncherClassName(Context context) {

        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                String className = resolveInfo.activityInfo.name;
                return className;
            }
        }
        return null;
    }


}

==> MyGcmListenerService.java Use BadgeUtils class when notification comes.

public class MyGcmListenerService extends GcmListenerService { 

    private static final String TAG = "MyGcmListenerService"; 
    @Override
    public void onMessageReceived(String from, Bundle data) {

            String message = data.getString("Msg");
            String Type = data.getString("Type"); 
            Intent intent = new Intent(this, SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.BigTextStyle bigTextStyle= new NotificationCompat.BigTextStyle();

            bigTextStyle .setBigContentTitle(getString(R.string.app_name))
                    .bigText(message);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(getNotificationIcon())
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(message)
                    .setStyle(bigTextStyle) 
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            int color = getResources().getColor(R.color.appColor);
            notificationBuilder.setColor(color);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


            int unOpenCount=AppUtill.getPreferenceInt("NOTICOUNT",this);
            unOpenCount=unOpenCount+1;

            AppUtill.savePreferenceLong("NOTICOUNT",unOpenCount,this);  
            notificationManager.notify(unOpenCount /* ID of notification */, notificationBuilder.build()); 

// This is for bladge on home icon          
        BadgeUtils.setBadge(MyGcmListenerService.this,(int)unOpenCount);

    }


    private int getNotificationIcon() {
        boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.drawable.notification_small_icon : R.drawable.icon_launcher;
    }
}

And clear notification from preference and also with badge count

 public class SplashActivity extends AppCompatActivity { 
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_splash);

                    AppUtill.savePreferenceLong("NOTICOUNT",0,this);
                    BadgeUtils.clearBadge(this);
            }
    }
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />

Difference between a View's Padding and Margin

In simple words:
padding changes the size of the box (with something).
margin changes the space between different boxes

What's the difference between JPA and Hibernate?

JPA is just a specification which needs concrete implementation. The default implementation oracle provide is "Eclipselink" now. (Toplink is donated by Oracle to Eclipse foundation to merge with eclipselink)

(Reference : http://www.oracle.com/technetwork/middleware/toplink/index-085257.html http://www.eclipse.org/org/press-release/20080317_Eclipselink.php )

Using Eclipselink, one can be sure that the code is portable to any implementation if need arises. Hibernate is also a full JPA implementation + MORE ( Sort of JPA Plus). Hibernate is super set of JPA with some extra Hibernate specific functionality. So app developed in Hibernate may not be compatible when switched to other implementation. Still hibernate is choice of majority of developers as JPA implementation and widely used.

Another JPA implementation is OpenJPA (openjpa.apache.org) which is an extension of Kodo implementation.

How can I programmatically check whether a keyboard is present in iOS app?

Add an extension

extension UIApplication {
    /// Checks if view hierarchy of application contains `UIRemoteKeyboardWindow` if it does, keyboard is presented
    var isKeyboardPresented: Bool {
        if let keyboardWindowClass = NSClassFromString("UIRemoteKeyboardWindow"),
            self.windows.contains(where: { $0.isKind(of: keyboardWindowClass) }) {
            return true
        } else {
            return false
        }
    }
}

Then check if keyboard is present,

if UIApplication.shared.isKeyboardPresented {
     print("Keyboard presented")
} else { 
     print("Keyboard is not presented")
}

Git - How to fix "corrupted" interactive rebase?

I got stuck in this. I created the head-name file, and then I ran into another error saying it couldn't find the onto file, so I created that file. Then I got another error saying could not read '.git/rebase-apply/onto': No such file or directory.

So I looked at the git documentation for rebasing and found another command:

git rebase --quit

This set me back on my branch with no changes, and I could start my rebase over again, good as new.

How to convert list of key-value tuples into dictionary?

If Tuple has no key repetitions, it's Simple.

tup = [("A",0),("B",3),("C",5)]
dic = dict(tup)
print(dic)

If tuple has key repetitions.

tup = [("A",0),("B",3),("C",5),("A",9),("B",4)]
dic = {}
for i, j in tup:
    dic.setdefault(i,[]).append(j)
print(dic)

Detecting TCP Client Disconnect

To expand on this a bit more:

If you are running a server you either need to use TCP_KEEPALIVE to monitor the client connections, or do something similar yourself, or have knowledge about the data/protocol that you are running over the connection.

Basically, if the connection gets killed (i.e. not properly closed) then the server won't notice until it tries to write something to the client, which is what the keepalive achieves for you. Alternatively, if you know the protocol better, you could just disconnect on an inactivity timeout anyway.

How do I get rid of an element's offset using CSS?

moving element top: -12px or positioning it absolutely doesn't solve the problem but only masks it

I had the same problem - check if you have in one wrapping element mixed: floating elements with non-floating ones - my non-floating element caused this strange offset to the floating one

Response Content type as CSV

Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )

  • text/comma-separated-values
  • text/csv
  • application/csv
  • application/excel
  • application/vnd.ms-excel
  • application/vnd.msexcel

Also, the mime-type might be case sensitive...

Find the IP address of the client in an SSH session

I'm getting the following output from who -m --ips on Debian 10:

root pts/0 Dec 4 06:45 123.123.123.123

Looks like a new column was added, so {print $5} or "take 5th column" attempts don't work anymore.

Try this:

who -m --ips | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'

Source:

How to make a dropdown readonly using jquery?

$('#cf_1268591').attr("disabled", true); 

drop down is always read only . what you can do is make it disabled

if you work with a form , the disabled fields does not submit , so use a hidden field to store disabled dropdown value

How to convert float number to Binary?

void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}

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

test.matches() method checks all text.use test.find()

Removing ul indentation with CSS

-webkit-padding-start: 0;

will remove padding added by webkit engine

Namespace not recognized (even though it is there)

I resolved this issue by right clicking on the folder containing the files and choosing Exclude From Project and then right clicking again and selecting Include In Project (you first have to enable Show All Files to make the excluded folder visible)

How do I get the currently-logged username from a Windows service in .NET?

Just in case someone is looking for user Display Name as opposed to User Name, like me.

Here's the treat :

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName.

Add Reference to System.DirectoryServices.AccountManagement in your project.

jquery json to string?

Edit: You should use the json2.js library from Douglas Crockford instead of implementing the code below. It provides some extra features and better/older browser support.

Grab the json2.js file from: https://github.com/douglascrockford/JSON-js


// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

var tmp = {one: 1, two: "2"};
JSON.stringify(tmp); // '{"one":1,"two":"2"}'

Code from: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/

asp.net validation to make sure textbox has integer values

If all that you are concerned about is that the field contains an integer (i.e., not concerned with a range), then add a CompareValidator with it's Operator property set to DataTypeCheck:

<asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer" 
 ControlToValidate="ValueTextBox" ErrorMessage="Value must be a whole number" />

If there is a specific range of values that are valid (there probably are), then you can use a RangeValidator, like so:

<asp:RangeValidator runat="server" Type="Integer" 
MinimumValue="0" MaximumValue="400" ControlToValidate="ValueTextBox" 
ErrorMessage="Value must be a whole number between 0 and 400" />

These will only validate if there is text in the TextBox, so you will need to keep the RequiredFieldValidator there, too.

As @Mahin said, make sure you check the Page.IsValid property on the server side, otherwise the validator only works for users with JavaScript enabled.

Get current URL/URI without some of $_GET variables

I don't know about doing it in Yii, but you could just do this, and it should work anywhere (largely lifted from my answer here):

// Get HTTP/HTTPS (the possible values for this vary from server to server)
$myUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && !in_array(strtolower($_SERVER['HTTPS']),array('off','no'))) ? 'https' : 'http';
// Get domain portion
$myUrl .= '://'.$_SERVER['HTTP_HOST'];
// Get path to script
$myUrl .= $_SERVER['REQUEST_URI'];
// Add path info, if any
if (!empty($_SERVER['PATH_INFO'])) $myUrl .= $_SERVER['PATH_INFO'];

$get = $_GET; // Create a copy of $_GET
unset($get['lg']); // Unset whatever you don't want
if (count($get)) { // Only add a query string if there's anything left
  $myUrl .= '?'.http_build_query($get);
}

echo $myUrl;

Alternatively, you could pass the result of one of the Yii methods into parse_url(), and manipulate the result to re-build what you want.

How to type a new line character in SQL Server Management Studio

Try using MS Access instead. Create a new file and select 'Project using existing data' template. This will create .adp file.

Then simply open your table and press Ctrl+Enter for new line.

Pasting from clipboard also works correctly.

CSS text-align not working

You have to make the UL inside the div behave like a block. Try adding

.navigation ul {
     display: inline-block;
}

Commenting code in Notepad++

for .sql files Ctrl+K or Ctrl+Q does not work.

to insert comments in .sql files in Notepad++ try Ctrl+Shift+Q

(there is no shortcut to uncomment the code block though. I have tried that on v5.8.2 )

Correct way to handle conditional styling in React

If you need to conditionally apply inline styles (apply all or nothing) then this notation also works:

style={ someCondition ? { textAlign:'center', paddingTop: '50%'} : {}}

In case 'someCondition' not fulfilled then you pass empty object.

How can I resolve the error: "The command [...] exited with code 1"?

For me : I have a white space in my path's folder name G:\Other Imp Projects\Mi.....

Solution 1 :

Remove white space from folder

Example: Other Imp Projects ->> Other_Imp_Projects

Solution 2:

add Quote ("") for your path.

Example: mkdir "$(ProjectDir)$(OutDir)Configurations" //see double quotes

C# "internal" access modifier when doing unit testing

Adding to Eric's answer, you can also configure this in the csproj file:

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>MyTests</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

Or if you have one test project per project to be tested, you could do something like this in your Directory.Build.props file:

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>$(MSBuildProjectName).Test</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

See: https://stackoverflow.com/a/49978185/1678053
Example: https://github.com/gldraphael/evlog/blob/master/Directory.Build.props#L5-L12

Reverse Y-Axis in PyPlot

Alternatively, you can use the matplotlib.pyplot.axis() function, which allows you inverting any of the plot axis

ax = matplotlib.pyplot.axis()
matplotlib.pyplot.axis((ax[0],ax[1],ax[3],ax[2]))

Or if you prefer to only reverse the X-axis, then

matplotlib.pyplot.axis((ax[1],ax[0],ax[2],ax[3]))

Indeed, you can invert both axis:

matplotlib.pyplot.axis((ax[1],ax[0],ax[3],ax[2]))

Should a RESTful 'PUT' operation return something

As opposed to most of the answers here, I actually think that PUT should return the updated resource (in addition to the HTTP code of course).

The reason why you would want to return the resource as a response for PUT operation is because when you send a resource representation to the server, the server can also apply some processing to this resource, so the client would like to know how does this resource look like after the request completed successfully. (otherwise it will have to issue another GET request).

Want to move a particular div to right

For me, I used margin-left: auto; which is more responsive with horizontal resizing.

Removing "http://" from a string

Something like this ought to do:

$url = preg_replace("|^.+?://|", "", $url); 

Removes everything up to and including the ://

What does "Use of unassigned local variable" mean?

If you declare the variable "annualRate" like

class Program {

**static double annualRate;**

public static void Main() {

Try it..

TypeScript and array reduce function

With TypeScript generics you can do something like this.

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);

Write Base64-encoded image to file

import java.util.Base64;

.... Just making it clear that this answer uses the java.util.Base64 package, without using any third-party libraries.

String crntImage=<a valid base 64 string>

byte[] data = Base64.getDecoder().decode(crntImage);

try( OutputStream stream = new FileOutputStream("d:/temp/abc.pdf") ) 
{
   stream.write(data);
}
catch (Exception e) 
{
   System.err.println("Couldn't write to file...");
}

Finding and removing non ascii characters from an Oracle Varchar2

In a single-byte ASCII-compatible encoding (e.g. Latin-1), ASCII characters are simply bytes in the range 0 to 127. So you can use something like [\x80-\xFF] to detect non-ASCII characters.

How to get query string parameter from MVC Razor markup?

I think a more elegant solution is to use the controller and the ViewData dictionary:

//Controller:
public ActionResult Action(int IFRAME)
    {
        ViewData["IsIframe"] = IFRAME == 1;
        return View();
    }

//view
@{
    string classToUse = (bool)ViewData["IsIframe"] ? "iframe-page" : "";
   <div id="wrap" class='@classToUse'></div>
 }

How to create a custom-shaped bitmap marker with Android map API v2

I hope it still not too late to share my solution. Before that, you can follow the tutorial as stated in Android Developer documentation. To achieve this, you need to use Cluster Manager with defaultRenderer.

  1. Create an object that implements ClusterItem

    public class SampleJob implements ClusterItem {
    
    private double latitude;
    private double longitude;
    
    //Create constructor, getter and setter here
    
    @Override
    public LatLng getPosition() {
        return new LatLng(latitude, longitude);
    }
    
  2. Create a default renderer class. This is the class that do all the job (inflating custom marker/cluster with your own style). I am using Universal image loader to do the downloading and caching the image.

    public class JobRenderer extends DefaultClusterRenderer< SampleJob > {
    
    private final IconGenerator iconGenerator;
    private final IconGenerator clusterIconGenerator;
    private final ImageView imageView;
    private final ImageView clusterImageView;
    private final int markerWidth;
    private final int markerHeight;
    private final String TAG = "ClusterRenderer";
    private DisplayImageOptions options;
    
    
    public JobRenderer(Context context, GoogleMap map, ClusterManager<SampleJob> clusterManager) {
        super(context, map, clusterManager);
    
        // initialize cluster icon generator
        clusterIconGenerator = new IconGenerator(context.getApplicationContext());
        View clusterView = LayoutInflater.from(context).inflate(R.layout.multi_profile, null);
        clusterIconGenerator.setContentView(clusterView);
        clusterImageView = (ImageView) clusterView.findViewById(R.id.image);
    
        // initialize cluster item icon generator
        iconGenerator = new IconGenerator(context.getApplicationContext());
        imageView = new ImageView(context.getApplicationContext());
        markerWidth = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
        markerHeight = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(markerWidth, markerHeight));
        int padding = (int) context.getResources().getDimension(R.dimen.custom_profile_padding);
        imageView.setPadding(padding, padding, padding, padding);
        iconGenerator.setContentView(imageView);
    
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.circle_icon_logo)
                .showImageForEmptyUri(R.drawable.circle_icon_logo)
                .showImageOnFail(R.drawable.circle_icon_logo)
                .cacheInMemory(false)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }
    
    @Override
    protected void onBeforeClusterItemRendered(SampleJob job, MarkerOptions markerOptions) {
    
    
        ImageLoader.getInstance().displayImage(job.getJobImageURL(), imageView, options);
        Bitmap icon = iconGenerator.makeIcon(job.getName());
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(job.getName());
    
    
    }
    
    @Override
    protected void onBeforeClusterRendered(Cluster<SampleJob> cluster, MarkerOptions markerOptions) {
    
        Iterator<Job> iterator = cluster.getItems().iterator();
        ImageLoader.getInstance().displayImage(iterator.next().getJobImageURL(), clusterImageView, options);
        Bitmap icon = clusterIconGenerator.makeIcon(iterator.next().getName());
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
    }
    
    @Override
    protected boolean shouldRenderAsCluster(Cluster cluster) {
        return cluster.getSize() > 1;
    }
    
  3. Apply cluster manager in your activity/fragment class.

    public class SampleActivity extends AppCompatActivity implements OnMapReadyCallback {
    
    private ClusterManager<SampleJob> mClusterManager;
    private GoogleMap mMap;
    private ArrayList<SampleJob> jobs = new ArrayList<SampleJob>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landing);
    
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.getUiSettings().setMapToolbarEnabled(true);
        mClusterManager = new ClusterManager<SampleJob>(this, mMap);
        mClusterManager.setRenderer(new JobRenderer(this, mMap, mClusterManager));
        mMap.setOnCameraChangeListener(mClusterManager);
        mMap.setOnMarkerClickListener(mClusterManager);
    
        //Assume that we already have arraylist of jobs
    
    
        for(final SampleJob job: jobs){
            mClusterManager.addItem(job);
        }
        mClusterManager.cluster();
    }
    
  4. Result

Result

Get the latest record with filter in Django

See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest

You need to specify a field in latest(). eg.

obj= Model.objects.filter(testfield=12).latest('testfield')

Or if your model’s Meta specifies get_latest_by, you can leave off the field_name argument to earliest() or latest(). Django will use the field specified in get_latest_by by default.