Programs & Examples On #Class factory

Anything related to the class-factory design pattern, i.e. a design pattern in object oriented programming where a class is used to create objects of derived classes.

Delete duplicate elements from an array

you may try like this using jquery

 var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];
    var uniqueVals = [];
    $.each(arr, function(i, el){
        if($.inArray(el, uniqueVals) === -1) uniqueVals.push(el);
    });

How to parse JSON to receive a Date object in JavaScript?

As Callum mentioned, for me, the best way is to change the Controller method to string instead of JsonResult".

public string GetValues()
{
  MyObject.DateFrom = DateTime.Now;
  return JsonConvert.SerializeObject(MyObject);
}

From the ajax method you can do something like this

 $.ajax({
 url: "/MyController/GetValues",
 type: "post",
 success: function (data) {
 var validData = JSON.parse(data);
//if you are using datepicker and you want set a format
$("#DateFrom").val($.datepicker.formatDate("dd/mm/yy", new Date(validData.DateFrom)));                                      
// if you want the date as returned
$("#DateFrom").val(new Date(validData.DateFrom))
}
});

Java Hashmap: How to get key from value?

public class NewClass1 {

    public static void main(String[] args) {
       Map<Integer, String> testMap = new HashMap<Integer, String>();
        testMap.put(10, "a");
        testMap.put(20, "b");
        testMap.put(30, "c");
        testMap.put(40, "d");
        for (Entry<Integer, String> entry : testMap.entrySet()) {
            if (entry.getValue().equals("c")) {
                System.out.println(entry.getKey());
            }
        }
    }
}

Some additional info... May be useful to you

Above method may not be good if your hashmap is really big. If your hashmap contain unique key to unique value mapping, you can maintain one more hashmap that contain mapping from Value to Key.

That is you have to maintain two hashmaps

1. Key to value

2. Value to key 

In that case you can use second hashmap to get key.

How to host material icons offline?

By the way there is video available on youtube with step by step instructions.

https://youtu.be/7j6eOkhISzk

  1. These are the steps. Download materialize icon package from https://github.com/google/material-design-icons/releases

  2. Copy the icon-font folder and rename it to icons.

  3. Open the materialize.css file and update the following paths:

a. from url(MaterialIcons-Regular.eot) to url(../fonts/MaterialIcons-Regular.eot) b. from url(MaterialIcons-Regular.woff2) format('woff2') to url(../fonts/MaterialIcons-Regular.woff2) format('woff2') c. from url(MaterialIcons-Regular.woff) format('woff') to url(../fonts/MaterialIcons-Regular.woff) format('woff') d. from url(MaterialIcons-Regular.ttf) format('truetype') to url(../fonts/MaterialIcons-Regular.ttf) format('truetype')

  1. Copy the materialize-icon.css to your css folder and reference it in your html file.

Everything will work like magic !

Add empty columns to a dataframe with specified names from a vector

The below works for me

dataframe[,"newName"] <- NA

Make sure to add "" for new name string.

Auto number column in SharePoint list

If you want to control the formatting of the unique identifier you can create your own <FieldType> in SharePoint. MSDN also has a visual How-To. This basically means that you're creating a custom column.

WSS defines the Counter field type (which is what the ID column above is using). I've never had the need to re-use this or extend it, but it should be possible.

A solution might exist without creating a custom <FieldType>. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (="CUST" & [ID]). I haven't tried this, but this should work :)

Spring Bean Scopes

From the spring specs, there are five types of bean scopes supported :

1. singleton(default*)

Scopes a single bean definition to a single object instance per Spring IoC container.

2. prototype

Scopes a single bean definition to any number of object instances.

3. request

Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

4. session

Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

5. global session

Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

*default means when no scope is explicitly provided in the <bean /> tag. read more about them here: http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html

Password masking console application

You could append your keys to an accumulating linked list.

When a backspace key is received, remove the last key from the list.

When you receive the enter key, collapse your list into a string and do the rest of your work.

TypeError: coercing to Unicode: need string or buffer

Here is the best way I found for Python 2:

def inplace_change(file,old,new):
        fin = open(file, "rt")
        data = fin.read()
        data = data.replace(old, new)
        fin.close()

        fin = open(file, "wt")
        fin.write(data)
        fin.close()

An example:

inplace_change('/var/www/html/info.txt','youtub','youtube')

When and how should I use a ThreadLocal variable?

Since Java 8 release, there is more declarative way to initialize ThreadLocal:

ThreadLocal<Cipher> local = ThreadLocal.withInitial(() -> "init value");

Until Java 8 release you had to do the following:

ThreadLocal<String> local = new ThreadLocal<String>(){
    @Override
    protected String initialValue() {
        return "init value";
    }
};

Moreover, if instantiation method (constructor, factory method) of class that is used for ThreadLocal does not take any parameters, you can simply use method references (introduced in Java 8):

class NotThreadSafe {
    // no parameters
    public NotThreadSafe(){}
}

ThreadLocal<NotThreadSafe> container = ThreadLocal.withInitial(NotThreadSafe::new);

Note: Evaluation is lazy since you are passing java.util.function.Supplier lambda that is evaluated only when ThreadLocal#get is called but value was not previously evaluated.

Sort Dictionary by keys

If you want to iterate over both the keys and the values in a key sorted order, this form is quite succinct

let d = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

Swift 1,2:

for (k,v) in Array(d).sorted({$0.0 < $1.0}) {
    println("\(k):\(v)")
}

Swift 3+:

for (k,v) in Array(d).sorted(by: {$0.0 < $1.0}) {
    println("\(k):\(v)")
}

Indirectly referenced from required .class file

How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project?

If you right click on your project and choose build path->configure build path and then choose the libraries tab. You should see the weblogic libraries associated here. If you do not you can click Add Library->Server Runtime. If the library is not there, then you first need to configure it. Windows->Preferences->Server->Installed runtimes

How to call a C# function from JavaScript?

You can use a Web Method and Ajax:

<script type="text/javascript">             //Default.aspx
   function DeleteKartItems() {     
         $.ajax({
         type: "POST",
         url: 'Default.aspx/DeleteItem',
         data: "",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
             $("#divResult").html("success");
         },
         error: function (e) {
             $("#divResult").html("Something Wrong.");
         }
     });
   }
</script>

[WebMethod]                                 //Default.aspx.cs
public static void DeleteItem()
{
    //Your Logic
}

How to determine one year from now in Javascript

In very simple way. use this code.

// define function 
function nextYearDate(date1) {
    var date2 = new Date(date1);
    var date3 = date2.setDate(date2.getDate() - 1);
    var date = new Date(date3);
    var day = date.getDate();
    var month = date.getMonth()+1;
    var year = date.getFullYear()+1;
    var newdate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
    $("#next_date").val(newdate);
}
// call function.
<input type="date" name="current_date" id="current_date" value="" onblur="nextYearDate(this.value);" />

<input type="date" name="next_date" id="next_date" value="" onblur="nextYearDate(this.value);" />

Why am I getting a NoClassDefFoundError in Java?

I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.

My solution was: Restart Eclipse. Since then I haven't seen this message again :-)

Javascript button to insert a big black dot (•) into a html textarea

Just access the element and append it to the value.

<input
     type="button" 
     onclick="document.getElementById('myTextArea').value += '•'" 
     value="Add •">

See a live demo.

For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.

Also it needs to be a UTF8 character.

Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

it is very simple....

[in make file]

==== 1 ===================

OBJS = ....\

version.o <<== add to your obj lists

==== 2 ===================

DATE = $(shell date +'char szVersionStr[20] = "%Y-%m-%d %H:%M:%S";') <<== add

all:version $(ProgramID) <<== version add at first

version: <<== add

echo '$(DATE)' > version.c  <== add ( create version.c file)

[in program]

=====3 =============

extern char szVersionStr[20];

[ using ]

=== 4 ====

printf( "Version: %s\n", szVersionStr );

How to work on UAC when installing XAMPP

This is a specific issue for Windows Vista, 7, 8 (and presumably newer).

User Account Control (UAC) is a feature in Windows that can help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of your user account.

This is applied mostly to C:\Program Files. You may have noticed sometimes, that some applications can see files in C:\Program Files that does not exist there. You know why? Windows now tend to have "C:\Program Files" folder customized for every user. For example, old applications store config files (like .ini) in the same folder where the executable files are stored. In the good old days all users had the same configurations for such apps. In nowadays Windows stores configs in the special folder tied to the user account. Thus, now different users may have different configs while application still think that config files are in the same folder with the executables.

XAMPP does not like to have different config for different users. In fact it is not a config file for XAMPP, it is folders where you keep your projects and databases. The idea of XAMPP is to make projects same for all users. This is a source of a conflict with Windows.

All you need is to avoid installing XAMPP into C:\Program Files. Thus XAMPP will always use the original files for all users and there would be no confusion.

I recommend to install XAMPP into the special folder in root directory like in C:\XAMPP. But before you choose the folder you need to click on this warning message.

Encode/Decode URLs in C++

This version is pure C and can optionally normalize the resource path. Using it with C++ is trivial:

#include <string>
#include <iostream>

int main(int argc, char** argv)
{
    const std::string src("/some.url/foo/../bar/%2e/");
    std::cout << "src=\"" << src << "\"" << std::endl;

    // either do it the C++ conformant way:
    char* dst_buf = new char[src.size() + 1];
    urldecode(dst_buf, src.c_str(), 1);
    std::string dst1(dst_buf);
    delete[] dst_buf;
    std::cout << "dst1=\"" << dst1 << "\"" << std::endl;

    // or in-place with the &[0] trick to skip the new/delete
    std::string dst2;
    dst2.resize(src.size() + 1);
    dst2.resize(urldecode(&dst2[0], src.c_str(), 1));
    std::cout << "dst2=\"" << dst2 << "\"" << std::endl;
}

Outputs:

src="/some.url/foo/../bar/%2e/"
dst1="/some.url/bar/"
dst2="/some.url/bar/"

And the actual function:

#include <stddef.h>
#include <ctype.h>

/**
 * decode a percent-encoded C string with optional path normalization
 *
 * The buffer pointed to by @dst must be at least strlen(@src) bytes.
 * Decoding stops at the first character from @src that decodes to null.
 * Path normalization will remove redundant slashes and slash+dot sequences,
 * as well as removing path components when slash+dot+dot is found. It will
 * keep the root slash (if one was present) and will stop normalization
 * at the first questionmark found (so query parameters won't be normalized).
 *
 * @param dst       destination buffer
 * @param src       source buffer
 * @param normalize perform path normalization if nonzero
 * @return          number of valid characters in @dst
 * @author          Johan Lindh <[email protected]>
 * @legalese        BSD licensed (http://opensource.org/licenses/BSD-2-Clause)
 */
ptrdiff_t urldecode(char* dst, const char* src, int normalize)
{
    char* org_dst = dst;
    int slash_dot_dot = 0;
    char ch, a, b;
    do {
        ch = *src++;
        if (ch == '%' && isxdigit(a = src[0]) && isxdigit(b = src[1])) {
            if (a < 'A') a -= '0';
            else if(a < 'a') a -= 'A' - 10;
            else a -= 'a' - 10;
            if (b < 'A') b -= '0';
            else if(b < 'a') b -= 'A' - 10;
            else b -= 'a' - 10;
            ch = 16 * a + b;
            src += 2;
        }
        if (normalize) {
            switch (ch) {
            case '/':
                if (slash_dot_dot < 3) {
                    /* compress consecutive slashes and remove slash-dot */
                    dst -= slash_dot_dot;
                    slash_dot_dot = 1;
                    break;
                }
                /* fall-through */
            case '?':
                /* at start of query, stop normalizing */
                if (ch == '?')
                    normalize = 0;
                /* fall-through */
            case '\0':
                if (slash_dot_dot > 1) {
                    /* remove trailing slash-dot-(dot) */
                    dst -= slash_dot_dot;
                    /* remove parent directory if it was two dots */
                    if (slash_dot_dot == 3)
                        while (dst > org_dst && *--dst != '/')
                            /* empty body */;
                    slash_dot_dot = (ch == '/') ? 1 : 0;
                    /* keep the root slash if any */
                    if (!slash_dot_dot && dst == org_dst && *dst == '/')
                        ++dst;
                }
                break;
            case '.':
                if (slash_dot_dot == 1 || slash_dot_dot == 2) {
                    ++slash_dot_dot;
                    break;
                }
                /* fall-through */
            default:
                slash_dot_dot = 0;
            }
        }
        *dst++ = ch;
    } while(ch);
    return (dst - org_dst) - 1;
}

Session 'app': Error Launching activity

My Answer is specifically for Redmi/Mi Phone users. I faced this issue multiple times.

Sometimes we uninstall the app but it is not completely uninstalled but app will not display on screen and also it will not be listed in Settings -> Apps.

After checking multiple answers, What worked for me is below command

Go to Android Studio and click on Terminal tab in bottom of Android Studio. Connect your device, once adb detects your device, Run this command and try again to Run your application. Hope it will help.

adb uninstall com.shyam.smsapp

com.shyam.smsapp replace with your application package name

I am not able launch JNLP applications using "Java Web Start"?

If javacpl does not open and gives you Could not find the main class:, it could be that Java is confused because of changes in deployment.properties (can be found in C:\Users\<username>\AppData\LocalLow\Sun\Java\Deployment on Win7). Delete that file and everything's fine.

This bug seems to be 6 years old, cf. An app should be able to ignore properties that have become obsolete over time, shouldn't it?

I can't install python-ldap

sudo apt-get install build-essential python3-dev python2.7-dev libldap2-dev libsasl2-dev slapd ldap-utils python-tox lcov valgrind

Format Float to n decimal places

public static double roundToDouble(float d, int decimalPlace) {
        BigDecimal bd = new BigDecimal(Float.toString(d));
        bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

SQL Case Sensitive String Compare

simplifying the general answer

SQL Case Sensitive String Compare

These examples may be helpful:

Declare @S1 varchar(20) = 'SQL'
Declare @S2 varchar(20) = 'sql'

  
if @S1 = @S2 print 'equal!' else print 'NOT equal!' -- equal (default non-case sensitivity for SQL

if cast(@S1 as binary) = cast(Upper(@S2) as binary) print 'equal!' else print 'NOT equal!' -- equal

if cast(@S1 as binary) = cast(@S2 as binary) print 'equal!' else print 'NOT equal!' -- not equal

if  @S1 COLLATE Latin1_General_CS_AS  = Upper(@S2) COLLATE Latin1_General_CS_AS  print 'equal!' else print 'NOT equal!' -- equal

if  @S1 COLLATE Latin1_General_CS_AS  = @S2 COLLATE Latin1_General_CS_AS  print 'equal!' else print 'NOT equal!' -- not equal

 

The convert is probably more efficient than something like runtime calculation of hashbytes, and I'd expect the collate may be even faster.

How to hide/show more text within a certain length (like youtube)

Here's a really simple solution that worked for me,

<span id="text">Extra Text</span>
<span id="more">show more...</span>
<span id="less">show less...</span>

<script>
 $("#text").hide();
 $("#less").hide();
 $("#more").click( function() {
   $("#text").show();
   $("#less").show();
   $("#more").hide();
 });
 $("#less").click( function() {
   $("#text").hide();
   $("#less").hide();
   $("#more").show();
 });
</script>

Get latest from Git branch

If you have forked a repository fro Delete your forked copy and fork it again from master.

How to make padding:auto work in CSS?

auto is not a valid value for padding property, the only thing you can do is take out padding: 0; from the * declaration, else simply assign padding to respective property block.

If you remove padding: 0; from * {} than browser will apply default styles to your elements which will give you unexpected cross browser positioning offsets by few pixels, so it is better to assign padding: 0; using * and than if you want to override the padding, simply use another rule like

.container p {
   padding: 5px;
}

Saving excel worksheet to CSV files with filename+worksheet name using VB

I had a similar problem. Data in a worksheet I needed to save as a separate CSV file.

Here's my code behind a command button


Private Sub cmdSave()
    Dim sFileName As String
    Dim WB As Workbook

    Application.DisplayAlerts = False

    sFileName = "MyFileName.csv"
    'Copy the contents of required sheet ready to paste into the new CSV
    Sheets(1).Range("A1:T85").Copy 'Define your own range

    'Open a new XLS workbook, save it as the file name
    Set WB = Workbooks.Add
    With WB
        .Title = "MyTitle"
        .Subject = "MySubject"
        .Sheets(1).Select
        ActiveSheet.Paste
        .SaveAs "MyDirectory\" & sFileName, xlCSV
        .Close
    End With

    Application.DisplayAlerts = True
End Sub

This works for me :-)

Creating composite primary key in SQL Server

If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.

enter image description here

Command for this is,

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID)

MySQL: Enable LOAD DATA LOCAL INFILE

Also, for other readers, if you are trying to do this in Django AND your server allows local_infile (you can check by typing SHOW VARIABLES via a mysql client) then you can add this to your settings.py file (since python MySQLdb doesn't by default read the .my.cnf file):

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'myname',
        'PASSWORD': 'mypass',
        'HOST': 'myserver',
        'PORT': '3306',
        'OPTIONS' : {
            'local_infile':1,
        },
    }
}

Check whether specific radio button is checked

I think you're using the wrong approach. You should set the value attribute of your input elements. Check the docs for .val() for examples of setting and returning the .val() of input elements.

ie.

<input type="radio" runat="server" name="testGroup" value="test2" />

return $('input:radio[name=testGroup]:checked').val() == 'test2';

How to make the corners of a button round?

Create an XML file like below one. Set it as background for the button. Change the radius attribute to your wish, if you need more curve for the button.

button_background.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/primary" />
    <corners android:radius="5dp" />
</shape>

Set background to your button:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_background"/>

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

Its available in androidx as following package

implementation "androidx.constraintlayout:constraintlayout:2.0.0-alpha1"

How do you store Java objects in HttpSession?

The request object is not the session.

You want to use the session object to store. The session is added to the request and is were you want to persist data across requests. The session can be obtained from

HttpSession session = request.getSession(true);

Then you can use setAttribute or getAttribute on the session.

A more up to date tutorial on jsp sessions is: http://courses.coreservlets.com/Course-Materials/pdf/csajsp2/08-Session-Tracking.pdf

Cannot find firefox binary in PATH. Make sure firefox is installed

System.setProperty("webdriver.gecko.driver", "D:\\Katalon_Studio_Windows_64-5.10.1\\configuration\\resources\\drivers\\firefox_win64\\geckodriver.exe");
        DesiredCapabilities capabilities = DesiredCapabilities.firefox();
        capabilities.setCapability("marionette", true);
        WebDriver driver = new FirefoxDriver(capabilities);
        DriverFactory.changeWebDriver(driver)

Rotate image with javascript

CSS can be applied and you will have to set transform-origin correctly to get the applied transformation in the way you want

See the fiddle:

http://jsfiddle.net/OMS_/gkrsz/

Main code:

/* assuming that the image's height is 70px */

img.rotated {
    transform: rotate(90deg);
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -ms-transform: rotate(90deg);

    transform-origin: 35px 35px;
    -webkit-transform-origin: 35px 35px;
    -moz-transform-origin: 35px 35px;
    -ms-transform-origin: 35px 35px;
}

jQuery and JS:

$(img)
    .css('transform-origin-x', imgWidth / 2)
    .css('transform-origin-y', imgHeight / 2);

// By calculating the height and width of the image in the load function

// $(img).css('transform-origin', (imgWidth / 2) + ' ' + (imgHeight / 2) );

Logic:

Divide the image's height by 2. The transform-x and transform-y values should be this value

Link:

transform-origin at CSS | MDN

Mvn install or Mvn package

The proper way is mvn package if you did things correctly for the core part of your build then there should be no need to install your packages in the local repository.

In addition if you use Travis you can "cache" your dependencies because it will not touch your $HOME.m2/repository if you use package for your own project.

In practicality if you even attempt to do a mvn site you usually need to do a mvn install before. There's just too many bugs with either site or it's numerous poorly maintained plugins.

Shall we always use [unowned self] inside closure in Swift

I thought I would add some concrete examples specifically for a view controller. Many of the explanations, not just here on Stack Overflow, are really good, but I work better with real world examples (@drewag had a good start on this):

  • If you have a closure to handle a response from a network requests use weak, because they are long lived. The view controller could close before the request completes so self no longer points to a valid object when the closure is called.
  • If you have closure that handles an event on a button. This can be unowned because as soon as the view controller goes away, the button and any other items it may be referencing from self goes away at the same time. The closure block will also go away at the same time.

    class MyViewController: UIViewController {
          @IBOutlet weak var myButton: UIButton!
          let networkManager = NetworkManager()
          let buttonPressClosure: () -> Void // closure must be held in this class. 
    
          override func viewDidLoad() {
              // use unowned here
              buttonPressClosure = { [unowned self] in
                  self.changeDisplayViewMode() // won't happen after vc closes. 
              }
              // use weak here
              networkManager.fetch(query: query) { [weak self] (results, error) in
                  self?.updateUI() // could be called any time after vc closes
              }
          }
          @IBAction func buttonPress(self: Any) {
             buttonPressClosure()
          }
    
          // rest of class below.
     }
    

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

Center text output from Graphics.DrawString()

I'd like to add another vote for the StringFormat object. You can use this simply to specify "center, center" and the text will be drawn centrally in the rectangle or points provided:

StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;

However there is one issue with this in CF. If you use Center for both values then it turns TextWrapping off. No idea why this happens, it appears to be a bug with the CF.

Date Difference in php on days?

strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$seconds_diff = $ts2 - $ts1;

Deserialize a JSON array in C#

This should work...

JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
    public string Name;
    public int Age;
    public string Location;
}
public class Record
{
    public Person record;
}

Implement Stack using Two Queues

import java.util.LinkedList;
import java.util.Queue;


public class StackQueue {

    static Queue<Integer> Q1 = new LinkedList<Integer>();
    static Queue<Integer> Q2 = new LinkedList<Integer>();
    public static void main(String args[]) {



        push(24);
        push(34);
        push(4);
        push(10);
        push(1);
        push(43);
        push(21);
        System.out.println("Popped element is  "+pop());
        System.out.println("Popped element is  "+pop());
        System.out.println("Popped element is  "+pop());


    }

    public static void push(int data) {

        Q1.add(data);

    }

    public static int pop() {

        if(Q1.isEmpty()) {
        System.out.println("Cannot pop elements ,  Stack is Empty !!"); 
        return -1;
        }
        else
        {
        while(Q1.size() > 1) {
            Q2.add(Q1.remove());
        }
        int element = Q1.remove();
        Queue<Integer> temp = new LinkedList<Integer>();
        temp = Q1;
        Q1 = Q2;
        Q2 = temp;
        return element;
        }
    }
}

How to check Grants Permissions at Run-Time?

Check out the below library in git :

RuntimePermission

Implementation :

        allprojects {
            repositories {
                ...
                maven { url 'https://jitpack.io' }
            }
        }
        
        dependencies {
            implementation 'com.github.manoj140220:RuntimePermission:1.0.3'
        }
    
    
      
    
        new RuntimePermission({Current Class Object}, String[] , {ActvityContext});
          
          String[] : permission array.
          example  : String[] permissionArray = {Manifest.permission.CAMERA, Manifest.permission.BODY_SENSORS,...} 
    
    Implement : {PermissionNotify}
    
    interface notifier methods.
    
    @Override
    public void notifyPermissionGrant() {
        
    }
    
    @Override
    public void notifyPermissionDeny() {
         
    }

Something better than .NET Reflector?

I am not sure what you really want here. If you want to see the .NET framework source code, you may try Netmassdownloader. It's free.

If you want to see any assembly's code (not just .NET), you can use ReSharper. Although it's not free.

Strip / trim all strings of a dataframe

If you really want to use regex, then

>>> df.replace('(^\s+|\s+$)', '', regex=True, inplace=True)
>>> df
   0   1
0  a  10
1  c   5

But it should be faster to do it like this:

>>> df[0] = df[0].str.strip()

How to use a SQL SELECT statement with Access VBA

Here is another way to use SQL SELECT statement in VBA:

 sSQL = "SELECT Variable FROM GroupTable WHERE VariableCode = '" & Me.comboBox & "'" 
 Set rs = CurrentDb.OpenRecordset(sSQL)
 On Error GoTo resultsetError 
 dbValue = rs!Variable
 MsgBox dbValue, vbOKOnly, "RS VALUE"
resultsetError:
 MsgBox "Error Retrieving value from database",VbOkOnly,"Database Error"

Setting the focus to a text field

In a JFrame or JDialog you can always overwrite the setVisible() method, it works well. I haven't tried in a JPanel, but can be an alternative.

@Override
public void setVisible(boolean value) {
    super.setVisible(value);
    control.requestFocusInWindow();
}

How to get the python.exe location programmatically?

This works in Linux & Windows:

Python 3.x

>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe

Python 2.x

>>> import sys
>>> print sys.executable
/usr/bin/python

How to fire a button click event from JavaScript in ASP.NET

document.FormName.btnSubmit.click(); 

works for me. Enjoy.

CSS: how do I create a gap between rows in a table?

Simply you can use padding-top and padding-bottom on a td element.

Unit can anything from this list:

enter image description here

Demo Code:

_x000D_
_x000D_
td_x000D_
{_x000D_
  padding-top: 10px;_x000D_
  padding-bottom: 10px;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <th>Firstname</th>_x000D_
    <th>Lastname</th>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Peter</td>_x000D_
    <td>Griffin</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Lois</td>_x000D_
    <td>Griffin</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to use clock() in C++

clock() returns the number of clock ticks since your program started. There is a related constant, CLOCKS_PER_SEC, which tells you how many clock ticks occur in one second. Thus, you can test any operation like this:

clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;

CSS how to make an element fade in and then fade out?

If you need a single fadeIn/Out without an explicit user action (like a mouseover/mouseout) you may use a CSS3 animation: http://codepen.io/anon/pen/bdEpwW

.elementToFadeInAndOut {

    animation: fadeinout 4s linear 1 forwards;
}



@keyframes fadeinout {
  0% { opacity: 0; }
  50% { opacity: 1; }
  100% { opacity: 0; }
}

By setting animation-fill-mode: forwards the animation will retain its last keyframe

By setting animation-iteration-count: 1 the animation will run just once (change this value if you need to repeat the effect more than once)

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

How to access accelerometer/gyroscope data from Javascript?

Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation

function orientationhandler(evt){


  // For FF3.6+
  if (!evt.gamma && !evt.beta) {
    evt.gamma = -(evt.x * (180 / Math.PI));
    evt.beta = -(evt.y * (180 / Math.PI));
  }

  // use evt.gamma, evt.beta, and evt.alpha 
  // according to dev.w3.org/geo/api/spec-source-orientation


}

window.addEventListener('deviceorientation',  orientationhandler, false);
window.addEventListener('MozOrientation',     orientationhandler, false);

Creating a simple XML file using python

The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:

#!/usr/bin/python
import lxml.etree
import lxml.builder    

E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2

the_doc = ROOT(
        DOC(
            FIELD1('some value1', name='blah'),
            FIELD2('some value2', name='asdfasd'),
            )   
        )   

print lxml.etree.tostring(the_doc, pretty_print=True)

Output:

<root>
  <doc>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>
  </doc>
</root>

It also supports adding to an already-made node, e.g. after the above you could say

the_doc.append(FIELD2('another value again', name='hithere'))

Private vs Protected - Visibility Good-Practice Concern

I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.

  1. Make all classes final unless you need to subclass them right away.
  2. Make all methods final unless you need to subclass and override them right away.
  3. Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.

Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.

If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.

Disclaimer: I don't program much in Java :)

Unsigned values in C

Assign a int -1 to an unsigned: As -1 does not fit in the range [0...UINT_MAX], multiples of UINT_MAX+1 are added until the answer is in range. Evidently UINT_MAX is pow(2,32)-1 or 429496725 on OP's machine so a has the value of 4294967295.

    unsigned int a = -1;

The "%x", "%u" specifier expects a matching unsigned. Since these do not match, "If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined." C11 §7.21.6.1 9. The printf specifier does not change b.

    printf("%x\n", b);  // UB
    printf("%u\n", b);  // UB

The "%d" specifier expects a matching int. Since these do not match, more UB.

    printf("%d\n", a);  // UB

Given undefined behavior, the conclusions are not supported.


both cases, the bytes are the same (ffffffff).

Even with the same bit pattern, different types may have different values. ffffffff as an unsigned has the value of 4294967295. As an int, depending signed integer encoding, it has the value of -1, -2147483647 or TBD. As a float it may be a NAN.

what is unsigned word for?

unsigned stores a whole number in the range [0 ... UINT_MAX]. It never has a negative value. If code needs a non-negative number, use unsigned. If code needs a counting number that may be +, - or 0, use int.


Update: to avoid a compiler warning about assigning a signed int to unsigned, use the below. This is an unsigned 1u being negated - which is well defined as above. The effect is the same as a -1, but conveys to the compiler direct intentions.

unsigned int a = -1u;

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

In my case this error occurred because a make command was expecting to fetch shared libraries (*.so files) from a remote directory indicated by a LDFLAGS environment variable. In a mistake, only static libraries were available there (*.la or *.a files).

Hence, my problem did not reside with the program I was compiling but with the remote libraries it was trying to fetch. So, I did not need to add any flag (say, -fPIC) to the compilation interrupted by the relocation error. Rather, I recompiled the remote library so that the shared objects were available.

Basically, it's been a file-not-found error in disguise.

In my case I had to remove a misplaced --disable-shared switch in the configure invocation for the requisite program, since shared and static libraries were both built as default.


I noticed that most programs build both types of libraries at the same time, so mine is probably a corner case. In general, it may be the case that you rather have to enable shared libraries, depending on defaults.

To inspect your particular situation with compile switches and defaults, I would read out the summary that shows up with ./configure --help | less, typically in the section Optional Features. I often found that this reading is more reliable than installation guides that are not updated while dependency programs evolve.

Get integer value from string in swift

In Swift 3.0

Type 1: Convert NSString to String

    let stringNumb:NSString = "1357"
    let someNumb = Int(stringNumb as String) // 1357 as integer

Type 2: If the String has Integer only

    let stringNumb = "1357"
    let someNumb = Int(stringNumb) // 1357 as integer

Type 3: If the String has Float value

    let stringNumb = "13.57"
    if let stringToFloat = Float(stringNumb){
        let someNumb = Int(stringToFloat)// 13 as Integer
    }else{
       //do something if the stringNumb not have digit only. (i.e.,) let stringNumb = "13er4"
    }

Play audio file from the assets directory

enter image description here

start sound

startSound("mp3/ba.mp3");

method

private void startSound(String filename) {
    AssetFileDescriptor afd = null;
    try {
        afd = getResources().getAssets().openFd(filename);
    } catch (IOException e) {
        e.printStackTrace();
    }
    MediaPlayer player = new MediaPlayer();
    try {
        assert afd != null;
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        player.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    player.start();
}

SyntaxError: missing ) after argument list

For me, once there was a mistake in spelling of function

For e.g. instead of

$(document).ready(function(){

});

I wrote

$(document).ready(funciton(){

});

So keep that also in check

Updating a local repository with changes from a GitHub repository

This should work for every default repo:

git pull origin master

If your default branch is different than master, you will need to specify the branch name:

git pull origin my_default_branch_name

How to invert a grep expression

 grep "subscription" | grep -v "spec"  

C free(): invalid pointer

You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.

There are two main types of memory you seem to be confusing - stack memory and heap memory.

  • Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main, it sets aside some memory for your variables you've declared (p,token, and so on).

  • Heap memory lives from when you malloc it to when you free it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!

You have a few errors:

  • You're trying to free memory that's not heap memory. Don't do that.

  • You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.

For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).

EDIT: The malloc function does allocate heap memory*.

"9.9.1 The malloc and free Functions

The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."

~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011

EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.

How can I make a horizontal ListView in Android?

You know, it might be possible to use an existing ListView with some judicious overriding of dispatchDraw() (to rotate the Canvas by 90 degrees), onTouch() (to swap the X and Y of the MotionEvent coords) and maybe onMeasure() or whatever to fool it into thinking it's y by x rather than x by y...

I have no idea if this would actually work but it'd be fun to find out. :)

How do I set adaptive multiline UILabel text?

I kind of got things working by adding auto layout constraints:

auto layout contraints

But I am not happy with this. Took a lot of trial and error and couldn't understand why this worked.

Also I had to add to use titleLabel.numberOfLines = 0 in my ViewController

How to tell if homebrew is installed on Mac OS X

Another one possible way:

# Check if Ninja is installed
if ! which ninja > /dev/null
then
echo 'Ninja installation...'
brew install ninja
fi

Any way to clear python's IDLE window?

As mark.ribau said, it seems that there is no way to clear the Text widget in idle. One should edit the EditorWindow.py module and add a method and a menu item in the EditorWindow class that does something like:

self.text.tag_remove("sel", "1.0", "end")
self.text.delete("1.0", "end")

and perhaps some more tag management of which I'm unaware of.

How do I align views at the bottom of the screen?

The modern way to do this is to have a ConstraintLayout and constrain the bottom of the view to the bottom of the ConstraintLayout with app:layout_constraintBottom_toBottomOf="parent"

The example below creates a FloatingActionButton that will be aligned to the end and the bottom of the screen.

<android.support.constraint.ConstraintLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_height="match_parent"
   android:layout_width="match_parent">

<android.support.design.widget.FloatingActionButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"

    app:layout_constraintBottom_toBottomOf="parent"

    app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

For reference, I will keep my old answer.

Before the introduction of ConstraintLayout the answer was a relative layout.


If you have a relative layout that fills the whole screen you should be able to use android:layout_alignParentBottom to move the button to the bottom of the screen.

If your views at the bottom are not shown in a relative layout then maybe the layout above it takes all the space. In this case you can put the view, that should be at the bottom, first in your layout file and position the rest of the layout above the views with android:layout_above. This enables the bottom view to take as much space as it needs, and the rest of the layout can fill all the rest of the screen.

IE9 jQuery AJAX with CORS returns "Access is denied"

Update as of early 2015. xDomain is a widely used library to supports CORS on IE9 with limited extra coding.

https://github.com/jpillora/xdomain

Use LIKE %..% with field values in MySQL

Use:

SELECT t1.Notes, 
       t2.Name
  FROM Table1 t1
  JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')

Can you use if/else conditions in CSS?

I've devised the below demo using a mix of tricks which allows simulating if/else scenarios for some properties. Any property which is numerical in its essence is easy target for this method, but properties with text values are.

This code has 3 if/else scenarios, for opacity, background color & width. All 3 are governed by two Boolean variables bool and its opposite notBool.

Those two Booleans are the key to this method, and to achieve a Boolean out of a none-boolean dynamic value, requires some math which luckily CSS allows using min & max functions.

Obviously those functions (min/max) are supported in recent browsers' versions which also supports CSS custom properties (variables).

_x000D_
_x000D_
var elm = document.querySelector('div')

setInterval(()=>{
  elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
_x000D_
:root{
   --color1: lightgreen;
   --color2: salmon;
   --width: 70;  /* starting value, randomly changed by javascript every 1 second */
}

div{
 --widthThreshold: 50;
 --is-width-above-limit: Min(1, Max(var(--width) - var(--widthThreshold), 0));
 --is-width-below-limit: calc(1 - var(--is-width-above-limit));
 
 --opacity-wide: .4;     /* if width is ABOVE 50 */
 --radius-narrow: 10px;  /* if width is BELOW 50 */
 --radius-wide: 60px;    /* if width is ABOVE 50 */
 --height-narrow: 80px;  /* if width is ABOVE 50 */
 --height-wide: 160px;   /* if width is ABOVE 50 */
 
 --radiusToggle: Max(var(--radius-narrow), var(--radius-wide) * var(--is-width-above-limit));
 --opacityToggle: calc(calc(1 + var(--opacity-wide)) - var(--is-width-above-limit));
 --colorsToggle: var(--color1) calc(100% * var(--is-width-above-limit)), 
                 var(--color2) calc(100% * var(--is-width-above-limit)), 
                 var(--color2) calc(100% * (1 - var(--is-width-above-limit)));
  
 --height: Max(var(--height-wide) * var(--is-width-above-limit), var(--height-narrow));
 
 height: var(--height);
 text-align: center;
 line-height: var(--height);

 width: calc(var(--width) * 1%);
 opacity: var(--opacityToggle);
 border-radius: var(--radiusToggle);
 background: linear-gradient(var(--colorsToggle));

 transition: .3s;
}

/* prints some variables */
div::before{
  counter-reset: aa var(--width);
  content: counter(aa)"%";
}

div::after{
  counter-reset: bb var(--is-width-above-limit);
  content: " is over 50% ? "counter(bb);
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Another simply way using clamp:

_x000D_
_x000D_
label{ --width: 150 }
input:checked + div{ --width: 400 }

div{
  --isWide: Clamp(0,   (var(--width) - 150) * 99999  , 1);
  width: calc(var(--width) * 1px);
  height: 150px;
  border-radius: calc(var(--isWide) * 20px); /* if wide - add radius */
  background: lightgreen;
}
_x000D_
<label>
<input type='checkbox' hidden> 
<div>Click to toggle width</div>
</label>
_x000D_
_x000D_
_x000D_

Best so far:

I have come up with a totally unique method, which is even simpler!

This method is so cool because it is so easy to implement and also to understand. it is based on animation step() function.

Since bool can be easily calculated as either 0 or 1, this value can be used in the step! if only a single step is defined, then the if/else problem is solved.

Using the keyword forwards persist the changes.

_x000D_
_x000D_
var elm = document.querySelector('div')

setInterval(()=>{
  elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
_x000D_
:root{
   --color1: salmon;
   --color2: lightgreen;
}

@keyframes if-over-threshold--container{
  to{ 
     --height: 160px;
     --radius: 30px;
     --color: var(--color2);
     opacity: .4; /* consider this as additional, never-before, style */
  }
}

@keyframes if-over-threshold--after{
  to{ 
    content: "true"; 
    color: green; 
  }
}

div{
 --width: 70;           /* must be unitless */
 --height: 80px;
 --radius: 10px;
 --color: var(--color1);
 --widthThreshold: 50;
 --is-width-over-threshold: Min(1, Max(var(--width) - var(--widthThreshold), 0));

 
 text-align: center;
 white-space: nowrap;
 transition: .3s;
 
 /* if element is narrower than --widthThreshold */
 width: calc(var(--width) * 1%);
 height: var(--height);
 line-height: var(--height);
 border-radius: var(--radius);
 background: var(--color);

 /* else */
 animation: if-over-threshold--container forwards steps(var(--is-width-over-threshold));
}

/* prints some variables */
div::before{
  counter-reset: aa var(--width);
  content: counter(aa)"% is over 50% width ? ";
}

div::after{
  content: 'false'; 
  font-weight: bold; 
  color: darkred;
  
  /* if element is wider than --widthThreshold */
  animation: if-over-threshold--after forwards steps(var(--is-width-over-threshold)) ;
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_


I've found a Chrome bug which I have reported that can affect this method in some situations where specific type of calculations is necessary, but there's a way around it.

https://bugs.chromium.org/p/chromium/issues/detail?id=1138497

Invalidating JSON Web Tokens

Keep an in-memory list like this

user_id   revoke_tokens_issued_before
-------------------------------------
123       2018-07-02T15:55:33
567       2018-07-01T12:34:21

If your tokens expire in one week then clean or ignore the records older than that. Also keep only the most recent record of each user. The size of the list will depend on how long you keep your tokens and how often users revoke their tokens. Use db only when the table changes. Load the table in memory when your application starts.

Simple http post example in Objective-C?

ASIHTTPRequest makes network communication really easy

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:@"Ben" forKey:@"names"];
[request addPostValue:@"George" forKey:@"names"];
[request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"];
[request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"];

How to enable explicit_defaults_for_timestamp?

On Windows -- open my.ini file, present at "C:\ProgramData\MySQL\MySQL Server 5.6", find "[mysqld]" (without quotes) in next line add explicit_defaults_for_timestamp and then save the changes.

jQuery window scroll event does not fire up

$('#div').scroll(function () {
   if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight-1) {

     //fire your event


    }
}

Is it possible to use jQuery .on and hover?

$("#MyTableData").on({

 mouseenter: function(){

    //stuff to do on mouse enter
    $(this).css({'color':'red'});

},
mouseleave: function () {
    //stuff to do on mouse leave
    $(this).css({'color':'blue'});

}},'tr');

Atom menu is missing. How do I re-enable

Open atom editor and then press Alt and menu bar will appear. Now click on View tab and then click on Toggle Menu Bar as seen on this screenshot.

When is layoutSubviews called?

A rather obscure, yet potentially important case when layoutSubviews never gets called is:

import UIKit

class View: UIView {

    override class var layerClass: AnyClass { return Layer.self }

    class Layer: CALayer {
        override func layoutSublayers() {
            // if we don't call super.layoutSublayers()...
            print(type(of: self), #function)
        }
    }

    override func layoutSubviews() {
        // ... this method never gets called by the OS!
        print(type(of: self), #function)
    }
}

let view = View(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

echo that outputs to stderr

You could define a function:

echoerr() { echo "$@" 1>&2; }
echoerr hello world

This would be faster than a script and have no dependencies.

Camilo Martin's bash specific suggestion uses a "here string" and will print anything you pass to it, including arguments (-n) that echo would normally swallow:

echoerr() { cat <<< "$@" 1>&2; }

Glenn Jackman's solution also avoids the argument swallowing problem:

echoerr() { printf "%s\n" "$*" >&2; }

ISO time (ISO 8601) in Python

ISO 8601 allows a compact representation with no separators except for the T, so I like to use this one-liner to get a quick timestamp string:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S.%fZ")
'20180905T140903.591680Z'

If you don't need the microseconds, just leave out the .%f part:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
'20180905T140903Z'

For local time:

>>> datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
'20180905T140903'

Edit:

After reading up on this some more, I recommend you leave the punctuation in. RFC 3339 recommends that style because if everyone uses punctuation, there isn't a risk of things like multiple ISO 8601 strings being sorted in groups on their punctuation. So the one liner for a compliant string would be:

>>> datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
'2018-09-05T14:09:03Z'

How to send password securely over HTTP?

Using HTTP with SSL will make your life much easier and you can rest at ease very smart people (smarter than me at least!) have scrutinized this method of confidential communication for years.

get an element's id

Yes you can just use the .id property of the dom element, for example:

myDOMElement.id

Or, something like this:

var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
  alert(inputs[i].id);
}

Ansible: create a user with sudo privileges

To create a user with sudo privileges is to put the user into /etc/sudoers, or make the user a member of a group specified in /etc/sudoers. And to make it password-less is to additionally specify NOPASSWD in /etc/sudoers.

Example of /etc/sudoers:

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
%wheel  ALL=(ALL)       NOPASSWD: ALL

And instead of fiddling with /etc/sudoers file, we can create a new file in /etc/sudoers.d/ directory since this directory is included by /etc/sudoers by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers.

To achieve above in Ansible, refer to the following:

- name: sudo without password for wheel group
  copy:
    content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
    dest: /etc/sudoers.d/wheel_nopasswd
    mode: 0440

You may replace %wheel with other group names like %sudoers or other user names like deployer.

Return multiple values from a function in swift

Swift 3

func getTime() -> (hour: Int, minute: Int,second: Int) {
        let hour = 1
        let minute = 20
        let second = 55
        return (hour, minute, second)
    }

To use :

let(hour, min,sec) = self.getTime()
print(hour,min,sec)

SQL Server 2008: how do I grant privileges to a username?

Like the following. It will make the user database owner.

EXEC sp_addrolemember N'db_owner', N'USerNAme'

What are some resources for getting started in operating system development?

When I started working on my basic operating systems I needed a basic guide like Stepping stones for a basic operating system. It helped me not loose my head.

That if you want to make it from absolutely nothing (pure assembly code)

Subtract two variables in Bash

For simple integer arithmetic, you can also use the builtin let command.

 ONE=1
 TWO=2
 let "THREE = $ONE + $TWO"
 echo $THREE
    3

For more info on let, look here.

Store an array in HashMap

HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();

pick one, for example

HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Something", new ArrayList<Integer>());
for (int i=0;i<numarulDeCopii; i++) {
    map.get("Something").add(coeficientUzura[i]); 
}

or just

HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);

EXTRACT() Hour in 24 Hour format

simple and easier solution:

select extract(hour from systimestamp) from dual;

EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
                           16 

Tensorflow installation error: not a supported wheel on this platform

It means that the version of your default python (python -V) and the version of your default pip (pip -V) do not match. You have built tensorflow with your default python and trying to use a different pip version to install it. In mac, delete /usr/local/bin/pip and rename(copy) pipx.y (whatever x.y version that matches your python version) to pip in that folder.

Get Table and Index storage size in sql server

with pages as (
    SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
            SUM (case 
                    when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
                    else lob_used_page_count + row_overflow_used_page_count
                 end) as pages
    FROM sys.dm_db_partition_stats
    group by object_id
), extra as (
    SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
    FROM sys.dm_db_partition_stats p, sys.internal_tables it
    WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
    group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
        pages * 8 as data_kb,
        (CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
        (CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id

Takes into account internal tables, such as those used for XML storage.

Edit: If you divide the data_kb and index_kb values by 1024.0, you will get the numbers you see in the GUI.

How to remove a branch locally?

Force Delete a Local Branch:

$ git branch -D <branch-name>

[NOTE]:

-D is a shortcut for --delete --force.


"java.lang.OutOfMemoryError: PermGen space" in Maven build

Increase the size of your perm space, of course. Use the -XX:MaxPermSize=128m option. Set the value to something appropriate.

What does `m_` variable prefix mean?

As stated in the other answers, m_ prefix is used to indicate that a variable is a class member. This is different from Hungarian notation because it doesn't indicate the type of the variable but its context.

I use m_ in C++ but not in some other languages where 'this' or 'self' is compulsory. I don't like to see 'this->' used with C++ because it clutters the code.

Another answer says m_dsc is "bad practice" and 'description;' is "good practice" but this is a red herring because the problem there is the abbreviation.

Another answer says typing this pops up IntelliSense but any good IDE will have a hotkey to pop up IntelliSense for the current class members.

How to compress a String in Java?

The ZIP algorithm is a combination of LZW and Huffman Trees. You can use one of theses algorithms separately.

The compression is based on 2 factors :

  • the repetition of substrings in your original chain (LZW): if there are a lot of repetitions, the compression will be efficient. This algorithm has good performances for compressing a long plain text, since words are often repeated
  • the number of each character in the compressed chain (Huffman): more the repartition between characters is unbalanced, more the compression will be efficient

In your case, you should try the LZW algorithm only. Used basically, the chain can be compressed without adding meta-informations: it is probably better for short strings compression.

For the Huffman algorithm, the coding tree has to be sent with the compressed text. So, for a small text, the result can be larger than the original text, because of the tree.

error: pathspec 'test-branch' did not match any file(s) known to git

My friend, you need to create those corresponding branches locally first, in order to check-out to those other two branches, using this line of code

git branch test-branch  

and

git branch change-the-title

then only you will be able to do git checkout to those branches

Also after creating each branch, take latest changes of those particular branches by using git pull origin branch_name as shown in below code

git branch test-branch
git checkout test-branch
git pull origin test-branch

and for other branch named change-the-title run following code =>

git branch change-the-title
git checkout change-the-title
git pull origin change-the-title

Happy programming :)

Removing carriage return and new-line from the end of a string in c#

If there's always a single CRLF, then:

myString = myString.Substring(0, myString.Length - 2);

If it may or may not have it, then:

Regex re = new Regex("\r\n$");
re.Replace(myString, "");

Both of these (by design), will remove at most a single CRLF. Cache the regex for performance.

why are there two different kinds of for loops in java?

Something none of the other answers touch on is that your first loop is indexing though the list. Whereas the for-each loop is using an Iterator. Some lists like LinkedList will iterate faster with an Iterator versus get(i). This is because because link list's iterator keeps track of the current pointer. Whereas each get in your for i=0 to 9 has to recompute the offset into the linked list. In general, its better to use for-each or an Iterator because it will be using Collections iterator, which in theory is optimized for the collection type.

How to output in CLI during execution of PHP Unit tests?

In short, phpunit supresses STDOUT. It writes to STDERR by default, unless you add --verbose or --debug . You can do one of those things:

  • print your debug output to STDERR instead
  • var_dump your debug as usual but add --verbose to the phpunit command line
  • var_dump your debug as usual but add a line ob_flush(); beneath it
  • use the correct commands in phpunit for testing exactly what you're trying to test here

Obviously, the last thing is the Good Thing to do, and the rest are quick temporary hacks.

React PropTypes : Allow different types of PropTypes for one prop

import React from 'react';              <--as normal
import PropTypes from 'prop-types';     <--add this as a second line

    App.propTypes = {
        monkey: PropTypes.string,           <--omit "React."
        cat: PropTypes.number.isRequired    <--omit "React."
    };

    Wrong:  React.PropTypes.string
    Right:  PropTypes.string

C# Error "The type initializer for ... threw an exception

I got this error with my own code. My problem was that I had duplicate keys in the config file.

How to pass query parameters with a routerLink

queryParams

queryParams is another input of routerLink where they can be passed like

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>

fragment

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>

routerLinkActiveOptions

To also get routes active class set on parent routes:

[routerLinkActiveOptions]="{ exact: false }"

To pass query parameters to this.router.navigate(...) use

let navigationExtras: NavigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

See also https://angular.io/guide/router#query-parameters-and-fragments

Creating an Instance of a Class with a variable in Python

If you haven't found it yet, here is Dive into Python's chapter on object-oriented programming.

Here are some more examples, scroll to BankAccount.


You can call a class directly to create an instance. Parameters are passed to the __init__ method.

class Tamago(object):
    def __init__(self, name):
        self.name = name

imouto = Tamago('imouto')
oba = Tamago('oba')
oba.name # 'oba'
imouto.name # 'imouto'

How to get multiple select box values using jQuery?

Get selected values in comma separator

var Accessids = "";
$(".multi_select .btn-group>ul>li input:checked").each(function(i,obj)
{
    Accessids=Accessids+$(obj).val()+",";
});
Accessids = Accessids.substring(0,Accessids.length - 1);
console.log(Accessids);

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Another possible solution, that worked for me:

Currently, react-router-redux is in beta and npm returns 4.x, but not 5.x. But the @types/react-router-redux returned 5.x. So there were undefined variables used.

Forcing NPM/Yarn to use 5.x solved it for me.

How to sort in mongoose?

This is what i did, it works fine.

User.find({name:'Thava'}, null, {sort: { name : 1 }})

Precision String Format Specifier In Swift

What about extensions on Double and CGFloat types:

extension Double {

   func formatted(_ decimalPlaces: Int?) -> String {
      let theDecimalPlaces : Int
      if decimalPlaces != nil {
         theDecimalPlaces = decimalPlaces!
      }
      else {
         theDecimalPlaces = 2
      }
      let theNumberFormatter = NumberFormatter()
      theNumberFormatter.formatterBehavior = .behavior10_4
      theNumberFormatter.minimumIntegerDigits = 1
      theNumberFormatter.minimumFractionDigits = 1
      theNumberFormatter.maximumFractionDigits = theDecimalPlaces
      theNumberFormatter.usesGroupingSeparator = true
      theNumberFormatter.groupingSeparator = " "
      theNumberFormatter.groupingSize = 3

      if let theResult = theNumberFormatter.string(from: NSNumber(value:self)) {
         return theResult
      }
      else {
         return "\(self)"
      }
   }
}

Usage:

let aNumber: Double = 112465848348508.458758344
Swift.print("The number: \(aNumber.formatted(2))")

prints: 112 465 848 348 508.46

Change the Theme in Jupyter Notebook?

To install the Jupyterthemes package directly with conda, use:

conda install -c conda-forge jupyterthemes

Then, as others have pointed out, change the theme with jt -t <theme-name>

Group a list of objects by an attribute

You can use the following:

Map<String, List<Student>> groupedStudents = new HashMap<String, List<Student>>();
for (Student student: studlist) {
    String key = student.stud_location;
    if (groupedStudents.get(key) == null) {
        groupedStudents.put(key, new ArrayList<Student>());
    }
    groupedStudents.get(key).add(student);
}

//print

Set<String> groupedStudentsKeySet = groupedCustomer.keySet();
for (String location: groupedStudentsKeySet) {
   List<Student> stdnts = groupedStudents.get(location);
   for (Student student : stdnts) {
        System.out.println("ID : "+student.stud_id+"\t"+"Name : "+student.stud_name+"\t"+"Location : "+student.stud_location);
    }
}

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

This is a first step for somebody that is a beginner. Same thing happened to me:

Look in the Solution Explorer box to the left. Make sure that there is actually a .cpp file there. You can do the same by looking the .cpp file where the .sln file for the project is stored. If there is not one, then you will get that error.

When adding a cpp file you want to use the Add new item icon. (top left with a gold star on it, hover over it to see the name) For some reason Ctrl+N does not actually add a .cpp file to the project.

Process.start: how to get the output?

When you create your Process object set StartInfo appropriately:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

You can use int.Parse() or int.TryParse() to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

How to add a fragment to a programmatically generated layout?

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".

MainActivity.java:

public class MainActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp" >

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

And this is the result of the above code: (the two Fragments are aligned next to each other) result

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

 function convertDatePickerTimeToMySQLTime(str) {
        var month, day, year, hours, minutes, seconds;
        var date = new Date(str),
            month = ("0" + (date.getMonth() + 1)).slice(-2),
            day = ("0" + date.getDate()).slice(-2);
        hours = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
        seconds = ("0" + date.getSeconds()).slice(-2);

        var mySQLDate = [date.getFullYear(), month, day].join("-");
        var mySQLTime = [hours, minutes, seconds].join(":");
        return [mySQLDate, mySQLTime].join(" ");
    }

How do you perform address validation?

Here's a free and sort of "outside the box" way to do it. Not 100% perfect, but it should reject blatantly non-existent addresses.

Submit the entire address to Google's geocoding web service. This service attempts to return the exact coordinates of the location you feed it, i.e. latitude and longitude.

In my experience if the address is invalid you will get a result of 602 from the service. There's definitely a possibility of false positives or false negatives, but used in conjunction with other consistency checks it could be useful.

(Yahoo's geocoding web service, on the other hand, will return the coordinates of the center of the town if the town exists but the rest of the address is bogus. Potentially useful as long as you pay close attention to the "precision" field in the result).

How to use the TextWatcher class in Android?

Create custom TextWatcher subclass:

public class CustomWatcher implements TextWatcher {

    private boolean mWasEdited = false;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        if (mWasEdited){

            mWasEdited = false;
            return;
        }

        // get entered value (if required)
        String enteredValue  = s.toString();

        String newValue = "new value";

        // don't get trap into infinite loop
        mWasEdited = true;
        // just replace entered value with whatever you want
        s.replace(0, s.length(), newValue);

    }
}

Set listener for your EditText:

mTargetEditText.addTextChangedListener(new CustomWatcher());

Count the number of items in my array list

Outside of your loop create an int:

int numberOfItemIds = 0;
for (int i = 0; i < key.length; i++) {

Then in the loop, increment it:

itemId = p.getItemId();
numberOfItemIds++;

oracle diff: how to compare two tables?

In addition to some of the other answers provided, if you wanted to look at the differences in table structure with a table that might have the similar but differing structure, you could do this in multiple ways:

First - If using Oracle SQL Developer, you could run a describe on both tables to compare them:

descr TABLE_NAME1
descr TABLE_NAME2

Second - The first solution may not be ideal for larger tables with a lot of columns. If you only want to see the differences in the data between the two tables, then as mentioned by several others, using the SQL Minus operator should do the job.

Third - If you are using Oracle SQL Developer, and you want to compare the table structure of two tables using different schemas you can do the following:

  1. Select "Tools"
  2. Select "Database Diff"
  3. Select "Source Connection"
  4. Select "Destination Connection"
  5. Select the "Standard Object Types" you want to compare
  6. Enter the "Table Name"
  7. Click "Next" until you reach "Finish"
  8. Click "Finish"
  9. NOTE: In steps 3 & 4 is where you would select the differing schemas in which the objects exist that you want to compare.

Fourth - If the tables two tables you wish to compare have more columns, are in the same schema, have no need to compare more than two tables and are unappealing to compare visually using the DESCR command you can use the following to compare the differences in the table structure:

select 
     a.column_name    || ' | ' || b.column_name, 
     a.data_type      || ' | ' || b.data_type, 
     a.data_length    || ' | ' || b.data_length, 
     a.data_scale     || ' | ' || b.data_scale, 
     a.data_precision || ' | ' || b.data_precision
from 
     user_tab_columns a,
     user_tab_columns b
where 
     a.table_name = 'TABLE_NAME1' 
and  b.table_name = 'TABLE_NAME2'
and  ( 
       a.data_type      <> b.data_type     or 
       a.data_length    <> b.data_length   or 
       a.data_scale     <> b.data_scale    or 
       a.data_precision <> b.data_precision
     )
and a.column_name = b.column_name;

How to allow http content within an iframe on a https site

add <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> in head

reference: http://thehackernews.com/2015/04/disable-mixed-content-warning.html

browser compatibility: http://caniuse.com/#feat=upgradeinsecurerequests

How can I add an item to a ListBox in C# and WinForms?

The way I do this - using the format Event

  MyClass c = new MyClass();
  listBox1.Items.Add(c);

  private void listBox1_Format(object sender, ListControlConvertEventArgs e)
    {
        if(e.ListItem is MyClass)
        {
            e.Value = ((MyClass)e.ListItem).ToString();
        }
        else
        {
            e.Value = "Unknown item added";
        }
    }

e.Value being the Display Text

Then you can attempt to cast the SelectedItem to MyClass to get access to anything you had in there.
Also note, you can use anything (that inherits from object anyway(which is pretty much everything)) in the Items Collection.

WRONGTYPE Operation against a key holding the wrong kind of value php

I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like

$redis->set('persons', $persons)

Later I decided to change to "hSet" method, and I tried it this way

foreach($persons as $person){
    $redis->hSet('persons', $person->id, $person);
}

Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with

del persons

It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.

Left align and right align within div in Bootstrap

In Bootstrap 4 the correct answer is to use the text-xs-right class.

This works because xs denotes the smallest viewport size in BS. If you wanted to, you could apply the alignment only when the viewport is medium or larger by using text-md-right.

In the latest alpha, text-xs-right has been simplified to text-right.

<div class="row">
    <div class="col-md-6">Total cost</div>
    <div class="col-md-6 text-right">$42</div>
</div>

Calculate number of hours between 2 dates in PHP

<?
     $day1 = "2014-01-26 11:30:00";
     $day1 = strtotime($day1);
     $day2 = "2014-01-26 12:30:00";
     $day2 = strtotime($day2);

   $diffHours = round(($day2 - $day1) / 3600);

   echo $diffHours;

?>

What is JavaScript garbage collection?

To the best of my knowledge, JavaScript's objects are garbage collected periodically when there are no references remaining to the object. It is something that happens automatically, but if you want to see more about how it works, at the C++ level, it makes sense to take a look at the WebKit or V8 source code

Typically you don't need to think about it, however, in older browsers, like IE 5.5 and early versions of IE 6, and perhaps current versions, closures would create circular references that when unchecked would end up eating up memory. In the particular case that I mean about closures, it was when you added a JavaScript reference to a dom object, and an object to a DOM object that referred back to the JavaScript object. Basically it could never be collected, and would eventually cause the OS to become unstable in test apps that looped to create crashes. In practice these leaks are usually small, but to keep your code clean you should delete the JavaScript reference to the DOM object.

Usually it is a good idea to use the delete keyword to immediately de-reference big objects like JSON data that you have received back and done whatever you need to do with it, especially in mobile web development. This causes the next sweep of the GC to remove that object and free its memory.

How to unpackage and repackage a WAR file

you can update your war from the command line using java commands as mentioned here:

jar -uvf test.war yourclassesdir 

Other useful commands:

Command to unzip/explode the war file

jar -xvf test.war

Command to create the war file

jar -cvf test.war yourclassesdir 

Eg:

jar -cvf test.war *
jar -cvf test.war WEB-INF META-INF

Retrieving Dictionary Value Best Practices

I imagine that trygetvalue is doing something more like:

if(myDict.ReallyOptimisedVersionofContains(someKey))
{ 
  someVal = myDict[someKey];
  return true;
}
return false;

So hopefully no try/catch anywhere.

I think it is just a method of convenience really. I generally use it as it saves a line of code or two.

How to have image and text side by side

HTML

<div class='containerBox'>
    <div>
       <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails'>
       <div>
       <h4>Facebook</h4>  
       <div style="font-size:.6em;float:left; margin-left:5px;color:white;">fine location, GPS, coarse location</div>
       <div style="float:right;font-size:.6em; margin-right:5px; color:white;">0 mins ago</div>
       </div>
   </div> 
</div>

CSS

 .iconDetails {
 margin-left:2%;
 float:left; 
 height:40px;
 width:40px;
 } 

.containerBox {
width:300px;
height:60px;
padding:1px;
background-color:#303030;
}
h4{
margin:0px;
margin-top:3%;
margin-left:50px;
color:white;
}

Matrix multiplication using arrays

try this,it may help you

import java.util.Scanner;

public class MulTwoArray {

public static void main(String[] args) {

    int i, j, k;
    int[][] a = new int[3][3];
    int[][] b = new int[3][3];
    int[][] c = new int[3][3];



    Scanner sc = new Scanner(System.in);

    System.out.println("Enter size of array a");
    int rowa = sc.nextInt();
    int cola = sc.nextInt();

    System.out.println("Enter size of array b");
    int rowb = sc.nextInt();
    int colb = sc.nextInt();


    //read and b

    System.out.println("Enter elements of array a");
    for (i = 0; i < rowa; ++i) {
        for (j = 0; j < cola; ++j) {

            a[i][j] = sc.nextInt();

        }
        System.out.println();
    }
    System.out.println("Enter elements of array b");
    for (i = 0; i < rowb; ++i) {
        for (j = 0; j < colb; ++j) {

            b[i][j] = sc.nextInt();

        }
        System.out.println("\n");
    }

    //print a and b

    System.out.println("the elements of array a");
    for (i = 0; i < rowa; ++i) {
        for (j = 0; j < cola; ++j) {

            System.out.print(a[i][j]);
            System.out.print("\t");

        }
        System.out.println("\n");
    }
    System.out.println("the elements of array b");
    for (i = 0; i < rowb; ++i) {
        for (j = 0; j < colb; ++j) {

            System.out.print(b[i][j]);
            System.out.print("\t");

        }
        System.out.println("\n");

    }

    //multiply a and b

    for (i = 0; i < rowa; ++i) {

        for (j = 0; j < colb; ++j) {
            c[i][j] = 0;
            for (k = 0; k < cola; ++k) {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }


    //print multi result

    System.out.println("result of multiplication of array a and b is ");
    for (i = 0; i < rowa; ++i) {
        for (j = 0; j < colb; ++j) {

            System.out.print(c[i][j]);
            System.out.print("\t");
        }
        System.out.println("\n");
    }
}
}

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

Add a UIView above all, even the navigation bar

Swift versions for the checked response :

Swift 4 :

let view = UIView()
view.frame = UIApplication.shared.keyWindow!.frame
UIApplication.shared.keyWindow!.addSubview(view)

Swift 3.1 :

let view = UIView()
view.frame = UIApplication.sharedApplication().keyWindow!.frame 
UIApplication.sharedApplication().keyWindow!.addSubview(view)

Which maven dependencies to include for spring 3.0?

You can add spring-context dependency for spring jars. You will get the following jars along with it.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

Spring context dependencies

if you also want web components, you can use spring-webmvc dependency.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

Spring webmvc dependencies

You can use whatever version of that you want. I have used 5.0.5.RELEASE here.

Bulk package updates using Conda

# list packages that can be updated
conda search --outdated

# update all packages prompted(by asking the user yes/no)
conda update --all

# update all packages unprompted
conda update --all -y

Android Studio Google JAR file causing GC overhead limit exceeded error

in my case, I Edit my gradle.properties :

note: if u enable the minifyEnabled true :

remove this line :

android.enableR8=true

and add this lines in ur build.gradle , android block :

  dexOptions {
        incremental = true
        preDexLibraries = false
        javaMaxHeapSize "4g" // 2g should be also OK
    }

hope this help some one :)

Is ASCII code 7-bit or 8-bit?

On Linux man ascii says:

ASCII is the American Standard Code for Information Interchange. It is a 7-bit code.

How do I fix "Expected to return a value at the end of arrow function" warning?

The warning indicates that you're not returning something at the end of your map arrow function in every case.

A better approach to what you're trying to accomplish is first using a .filter and then a .map, like this:

this.props.comments
  .filter(commentReply => commentReply.replyTo === comment.id)
  .map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>);

How to check for an active Internet connection on iOS or macOS?

To do this yourself is extremely simple. The following method will work. Just be sure to not allow a hostname protocol such as HTTP, HTTPS, etc. to be passed in with the name.

-(BOOL)hasInternetConnection:(NSString*)urlAddress
{
    SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);
    SCNetworkReachabilityFlags flags;
    if (!SCNetworkReachabilityGetFlags(ref, &flags))
    {
        return NO;
    }
    return flags & kSCNetworkReachabilityFlagsReachable;
}

It is quick simple and painless.

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

You can use git checkout <file> to check out the committed version of the file (thus discarding your changes), or git reset --hard HEAD to throw away any uncommitted changes for all files.

no target device found android studio 2.1.1

I had the same thing on Windows 7 where I had the device properly set and the driver installed, and I was routinely running on the device. Then suddenly I started getting this error every time. I opened the Edit Configurations dialog as described above, switched to an emulator, tried one run, then went to the same dialog and changed back to USB. Then if worked again.

Find kth smallest element in a binary search tree in Optimum way

http://www.geeksforgeeks.org/archives/10379

this is the exact answer to this question:-

1.using inorder traversal on O(n) time 2.using Augmented tree in k+log n time

Rails 4 LIKE query - ActiveRecord adds quotes

ActiveRecord is clever enough to know that the parameter referred to by the ? is a string, and so it encloses it in single quotes. You could as one post suggests use Ruby string interpolation to pad the string with the required % symbols. However, this might expose you to SQL-injection (which is bad). I would suggest you use the SQL CONCAT() function to prepare the string like so:

"name LIKE CONCAT('%',?,'%') OR postal_code LIKE CONCAT('%',?,'%')", search, search)

Center Align on a Absolutely Positioned Div

If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:

div#wrapper {
    position: absolute;
    width: 100%;
    text-align: center;
}

Remember that in order to position an element absolutely, the parent element must be positioned relatively.

Input mask for numeric and decimal

Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.

How to update std::map after using the find method?

I would use the operator[].

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

So using this technique it becomes really easy to read all the character from a stream and count them:

map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;

for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}

How do I download the Android SDK without downloading Android Studio?

You can find the command line tools at the downloads page under the "Command line tools only" section.

enter image description here

These are the links provided in the page as of now (version 26.1.1):

Be sure to have read and agreed with the terms of service before downloading any of the command line tools.

The installer version for windows doesn't seem to be available any longer, this is the link for version 24.4.1:

How to check "hasRole" in Java Code with Spring Security?

On your user model just add a 'hasRole' method like below

public boolean hasRole(String auth) {
    for (Role role : roles) {
        if (role.getName().equals(auth)) { return true; }
    }
    return false;
}

I usually use it to check if the authenticated user has the role admin as follows

Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // This gets the authentication
User authUser = (User) authentication.getPrincipal(); // This gets the logged in user
authUser.hasRole("ROLE_ADMIN") // This returns true or false

Difference between java HH:mm and hh:mm on SimpleDateFormat

Actually the last one is not weird. Code is setting the timezone for working instead of working2.

SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).

Fixing this error gives:

24:00:00
00:00:00
01:00:00

How to change resolution (DPI) of an image?

You have to copy the bits over a new image with the target resolution, like this:

    using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
    {
        using (Bitmap newBitmap = new Bitmap(bitmap))
        {
            newBitmap.SetResolution(300, 300);
            newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
        }
    }

calling server side event from html button control

On your aspx page define the HTML Button element with the usual suspects: runat, class, title, etc.

If this element is part of a data bound control (i.e.: grid view, etc.) you may want to use CommandName and possibly CommandArgument as attributes. Add your button's content and closing tag.

<button id="cmdAction" 
    runat="server" onserverclick="cmdAction_Click()" 
    class="Button Styles" 
    title="Does something on the server" 
    <!-- for databound controls -->
    CommandName="cmdname"> 
    CommandArgument="args..."
    >
    <!-- content -->
    <span class="ui-icon ..."></span>
    <span class="push">Click Me</span>
</button>

On the code behind page the element would call the handler that would be defined as the element's ID_Click event function.

protected void cmdAction_Click(object sender, EventArgs e)
{
: do something.
}

There are other solutions as in using custom controls, etc. Also note that I am using this live on projects in VS2K8.

Hoping this helps. Enjoy!

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

Import a module from a relative path

This is the relevant PEP:

http://www.python.org/dev/peps/pep-0328/

In particular, presuming dirFoo is a directory up from dirBar...

In dirFoo\Foo.py:

from ..dirBar import Bar

How to concatenate columns in a Postgres SELECT?

CONCAT functions sometimes not work with older postgreSQL version

see what I used to solve problem without using CONCAT

 u.first_name || ' ' || u.last_name as user,

Or also you can use

 "first_name" || ' ' || "last_name" as user,

in second case I used double quotes for first_name and last_name

Hope this will be useful, thanks

Disable a Button

Let's say in Swift 4 you have a button set up for a segue as an IBAction like this @IBAction func nextLevel(_ sender: UIButton) {} and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:

var appMode = 0

@IBAction func mySegue(_ sender: UIButton) {

    if appMode == 1 {  // avoid crash if button pressed during other app actions and/or conditions
        let conflictingAction = sender as UIButton
        conflictingAction.isEnabled = false
    }
}

Please note that you will likely have other conditions within if appMode == 0 and/or if appMode == 1 that will still occur and NOT conflict with the mySegue button. Thus, AVOIDING A CRASH.

How to convert between bytes and strings in Python 3?

In python3, there is a bytes() method that is in the same format as encode().

str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True

I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode and decode, and without having to prefex b in front of quotes.

How to get file extension from string in C++

You have to make sure you take care of file names with more then one dot. example: c:\.directoryname\file.name.with.too.many.dots.ext would not be handled correctly by strchr or find.

My favorite would be the boost filesystem library that have an extension(path) function

Error to run Android Studio

First check if the Java JDK is installed correctly:

dpkg --list | grep -i jdk

If not, install the JDK:

  1. Download the latest version of the JDK from Oracle: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

  2. Extract it to the appropriate location in your machine. Get the extract location:

    vi ~/.bashrc or vi ~./ bash_profile

    JAVA_HOME=/home/user/installs/jdk1.7.0_40
    PATH=$JAVA_HOME/bin
    

    source ~/.bashrc or source ~/.bash_profile

  3. After the installation you can check it:

    java -version
    which java
    

    If all things are correct then the right the answer should be something like this:

    java version "1.7.0_40"
    Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
    Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)

  4. Append the following statement to studio.sh the file in android-studio/bin directory:

    JAVA_HOME=/home/user/installs/jdk1.7.0_40
    

Finally start your Android Studio with the following command:

./studio.sh 

Setting maxlength of textbox with JavaScript or jQuery

You can make it like this:

$('#inputID').keypress(function () {
    var maxLength = $(this).val().length;
    if (maxLength >= 5) {
        alert('You cannot enter more than ' + maxLength + ' chars');
        return false;
    }
});

URL.Action() including route values

You also can use in this form:

<a href="@Url.Action("Information", "Admin", null)"> Admin</a>

Android ADB devices unauthorized

I had this problem and it wasnt solved by the deleting of any keys (at least deleting them didnt fix it, maybe had an effect after i did fix it though)

I actually had a discrepancy between my sdk-tools version and my Android Studio version. After updating my tools it still didnt work, but after updating AS (to 1.4) everything worked fine again.

Always update both sdk-tools and AS version together ;)

General error: 1364 Field 'user_id' doesn't have a default value

User Auth::user()->id instead.

Here is the correct way :

//PostController
Post::create(request([
    'body' => request('body'),
    'title' => request('title'),
    'user_id' => Auth::user()->id
]));

If your user is authenticated, Then Auth::user()->id will do the trick.

How can I override inline styles with external CSS?

!important, after your CSS declaration.

div {
   color: blue !important; 

   /* This Is Now Working */
}

SyntaxError: non-default argument follows default argument

As the error message says, non-default argument til should not follow default argument hgt.

Changing order of parameters (function call also be adjusted accordingly) or making hgt non-default parameter will solve your problem.

def a(len1, hgt=len1, til, col=0):

->

def a(len1, hgt, til, col=0):

UPDATE

Another issue that is hidden by the SyntaxError.

os.system accepts only one string parameter.

def a(len1, hgt, til, col=0):
    system('mode con cols=%s lines=%s' % (len1, hgt))
    system('title %s' % til)
    system('color %s' % col)

Java Date vs Calendar

With Java 8, the new java.time package should be used.

Objects are immutable, time zones and day light saving are taken into account.

You can create a ZonedDateTime object from an old java.util.Date object like this:

    Date date = new Date();
    ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault());

fe_sendauth: no password supplied

Do not use passwords. Use peer authentication instead:

postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb

Running a script inside a docker container using shell script

In case you don't want (or have) a running container, you can call your script directly with the run command.

Remove the iterative tty -i -t arguments and use this:

    $ docker run ubuntu:bionic /bin/bash /path/to/script.sh

This will (didn't test) also work for other scripts:

    $ docker run ubuntu:bionic /usr/bin/python /path/to/script.py

How can I list all the deleted files in a Git repository?

And if you want to somehow constrain the results here's a nice one:

$ git log --diff-filter=D --summary | sed -n '/^commit/h;/\/some_dir\//{G;s/\ncommit \(.*\)/ \1/gp}'
delete mode 100644 blah/some_dir/file1 d3bfbbeba5b5c1da73c432cb3fb61990bdcf6f64
delete mode 100644 blah/some_dir/file2 d3bfbbeba5b5c1da73c432cb3fb61990bdcf6f64
delete mode 100644 blah/some_dir/file3 9c89b91d8df7c95c6043184154c476623414fcb7

You'll get all files deleted from some_dir (see the sed command) together with the commit number in which it happen. Any sed regex will do (I use this to find deleted file types, etc)

Count distinct value pairs in multiple columns in SQL

Get all distinct id, name and address columns and count the resulting rows.

SELECT COUNT(*) FROM mytable GROUP BY id, name, address

How to find text in a column and saving the row number where it is first found - Excel VBA

I'm not really familiar with all those parameters of the Find method; but upon shortening it, the following is working for me:

With WB.Sheets("ECM Overview")
    Set FindRow = .Range("A:A").Find(What:="ProjTemp", LookIn:=xlValues)
End With

And if you solely need the row number, you can use this after:

Dim FindRowNumber As Long
.....
FindRowNumber = FindRow.Row

How do you change Background for a Button MouseOver in WPF?

For change button style

1st: define resource styles

<Window.Resources>

    <Style x:Key="OvergroundIn" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FF16832F">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FF06731F">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>

    <Style x:Key="OvergroundOut" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FFF35E5E">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FFE34E4E">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>


</Window.Resources>

2nd define button code

                           <Border Grid.Column="2" BorderBrush="LightGray" BorderThickness="2" CornerRadius="3" Margin="2,2,2,2"  >
                                <Button Name="btnFichar" BorderThickness="0" Click="BtnFichar_Click">
                                    <Button.Content>
                                        <Grid>
                                            <TextBlock Margin="0,7,0,7" TextAlignment="Center">Fichar</TextBlock> 
                                        </Grid>
                                    </Button.Content>
                                </Button>
                            </Border>

3th code behind

    public void ShowStatus()
    {
        switch (((MainDto)this.DataContext).State)
        {
            case State.IN:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(243, 94, 94));
                this.btnFichar.Style = Resources["OvergroundIn"] as Style;
                this.btnFichar.Content = "Fichar Salida";
                break;

            case State.OUT:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(76, 106, 83));
                this.btnFichar.Style = Resources["OvergroundOut"] as Style;
                this.btnFichar.Content = "Fichar Entrada";
                break;

        }
    }

How to truncate float values?

You can do:

def truncate(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

testing:

>>> f=1.923328437452
>>> [truncate(f, n) for n in range(5)]
[1.0, 1.9, 1.92, 1.923, 1.9233]

Scanner is never closed

I am assuming you are using java 7, thus you get a compiler warning, when you don't close the resource you should close your scanner usually in a finally block.

Scanner scanner = null;
try {
    scanner = new Scanner(System.in);
    //rest of the code
}
finally {
    if(scanner!=null)
        scanner.close();
}

Or even better: use the new Try with resource statement:

try(Scanner scanner = new Scanner(System.in)){
    //rest of your code
}

Can we instantiate an abstract class?

It's impossible to instantiate an abstract class. What you really can do, has implement some common methods in an abstract class and let others unimplemented (declaring them abstract) and let the concrete descender implement them depending on their needs. Then you can make a factory, which returns an instance of this abstract class (actually his implementer). In the factory you then decide, which implementer to choose. This is known as a factory design pattern:

   public abstract class AbstractGridManager {
        private LifecicleAlgorithmIntrface lifecicleAlgorithm;
        // ... more private fields

        //Method implemented in concrete Manager implementors 
        abstract public Grid initGrid();

        //Methods common to all implementors
        public Grid calculateNextLifecicle(Grid grid){
            return this.getLifecicleAlgorithm().calculateNextLifecicle(grid);
        }

        public LifecicleAlgorithmIntrface getLifecicleAlgorithm() {
            return lifecicleAlgorithm;
        }
        public void setLifecicleAlgorithm(LifecicleAlgorithmIntrface lifecicleAlgorithm) {
            this.lifecicleAlgorithm = lifecicleAlgorithm;
        }
        // ... more common logic and getters-setters pairs
    }

The concrete implementer only needs to implement the methods declared as abstract, but will have access to the logic implemented in those classes in an abstract class, which are not declared abstract:

public class FileInputGridManager extends AbstractGridManager {

private String filePath;

//Method implemented in concrete Manager implementors 
abstract public Grid initGrid();

public class FileInputGridManager extends AbstractGridManager {

    private String filePath;

    //Method implemented in concrete Manager implementors 
    abstract public Grid initGrid();

    public Grid initGrid(String filePath) {
        List<Cell> cells = new ArrayList<>();
        char[] chars;
        File file = new File(filePath); // for example foo.txt
        // ... more logic
        return grid;
    }
}

Then finally the factory looks something like this:

public class GridManagerFactory {
    public static AbstractGridManager getGridManager(LifecicleAlgorithmIntrface lifecicleAlgorithm, String... args){
        AbstractGridManager manager = null;

        // input from the command line
        if(args.length == 2){
            CommandLineGridManager clManager = new CommandLineGridManager();
            clManager.setWidth(Integer.parseInt(args[0]));
            clManager.setHeight(Integer.parseInt(args[1]));
            // possibly more configuration logic
            ...
            manager = clManager;
        } 
        // input from the file
        else if(args.length == 1){
            FileInputGridManager fiManager = new FileInputGridManager();
            fiManager.setFilePath(args[0]);
            // possibly more method calls from abstract class
            ...
            manager = fiManager ;
        }
        //... more possible concrete implementors
        else{
            manager = new CommandLineGridManager();
        }
        manager.setLifecicleAlgorithm(lifecicleAlgorithm);
        return manager;
    }
}

The receiver of AbstractGridManager would call the methods on him and get the logic, implemented in the concrete descender (and partially in the abstract class methods) without knowing what is the concrete implementation he got. This is also known as inversion of control or dependency injection.

Cross-Origin Request Headers(CORS) with PHP headers

Access-Control-Allow-Headers does not allow * as accepted value, see the Mozilla Documentation here.

Instead of the asterisk, you should send the accepted headers (first X-Requested-With as the error says).

A div with auto resize when changing window width\height

  <!DOCTYPE html>
    <html>
  <head>
  <style> 
   div {

   padding: 20px; 

   resize: both;
  overflow: auto;
   }
    img{
   height: 100%;
    width: 100%;
 object-fit: contain;
 }
 </style>
  </head>
  <body>
 <h1>The resize Property</h1>

 <div>
 <p>Let the user resize both the height and the width of this 1234567891011 div 
   element. 
  </p>
 <p>To resize: Click and drag the bottom right corner of this div element.</p>
  <img src="images/scenery.jpg" alt="Italian ">
  </div>

   <p><b>Note:</b> Internet Explorer does not support the resize property.</p>

 </body>
 </html>

Trigger css hover with JS

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually.


Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

How to access route, post, get etc. parameters in Zend Framework 2

require_once 'lib/Zend/Loader/StandardAutoloader.php';
$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));

$loader->registerNamespace('Http\PhpEnvironment', 'lib/Zend/Http'); 

// Register with spl_autoload:
$loader->register();

$a = new Zend\Http\PhpEnvironment\Request();
print_r($a->getQuery()->get()); exit;

Get properties and values from unknown object

This example trims all the string properties of an object.

public static void TrimModelProperties(Type type, object obj)
{
    var propertyInfoArray = type.GetProperties(
                                    BindingFlags.Public | 
                                    BindingFlags.Instance);
    foreach (var propertyInfo in propertyInfoArray)
    {
        var propValue = propertyInfo.GetValue(obj, null);
        if (propValue == null) 
            continue;
        if (propValue.GetType().Name == "String")
            propertyInfo.SetValue(
                             obj, 
                             ((string)propValue).Trim(), 
                             null);
    }
}

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

If your project has Roslyn references and you are deploying it on an IIS server, you might get unwanted errors on the website as many hosting providers still have not upgraded their servers and hence do not support Roslyn.

To resolve this issue, you will need to remove the Roslyn compiler from the project template. Removing Roslyn shouldn't affect your code's functionality. It worked fine for me and some other projects (C# 4.5.2) on which I worked.

Do the following steps:

  1. Remove from following Nuget Packages using command line shown below (or you can use GUI of Nuget Package manager by Right Clicking on Root Project Solution and removing them).

    PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
    PM> Uninstall-package Microsoft.Net.Compilers
    
  2. Remove the following code from your Web.Config file and restart IIS. (Use this method only if step 1 doesn't solve your problem.)

    <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
    

Numpy how to iterate over columns of array?

Just iterate over the transposed of your array:

for column in array.T:
   some_function(column)

How to execute a file within the python interpreter?

Python 2 + Python 3

exec(open("./path/to/script.py").read(), globals())

This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most scripting environments).

Python 3 exec Documentation

HTML character codes for this ? or this ?

The Big and small black triangles facing the 4 directions can be represented thus:

&#x25B2;

&#x25B4;

&#x25B6;

&#x25B8;

&#x25BA;

&#x25BC;

&#x25BE;

&#x25C0;

&#x25C2;

&#x25C4;

Setting user agent of a java URLConnection

Just for clarification: setRequestProperty("User-Agent", "Mozilla ...") now works just fine and doesn't append java/xx at the end! At least with Java 1.6.30 and newer.

I listened on my machine with netcat(a port listener):

$ nc -l -p 8080

It simply listens on the port, so you see anything which gets requested, like raw http-headers.

And got the following http-headers without setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

And WITH setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

As you can see the user agent was properly set.

Full example:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


public class TestUrlOpener {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/foobar");
        URLConnection hc = url.openConnection();
        hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        System.out.println(hc.getContentType());
    }

}

How to run Java program in command prompt

javac is the Java compiler. java is the JVM and what you use to execute a Java program. You do not execute .java files, they are just source files. Presumably there is .jar somewhere (or a directory containing .class files) that is the product of building it in Eclipse:

java/src/com/mypackage/Main.java
java/classes/com/mypackage/Main.class
java/lib/mypackage.jar

From directory java execute:

java -cp lib/mypackage.jar Main arg1 arg2

Finding child element of parent pure javascript

The children property returns an array of elements, like so:

parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]

There are alternatives to querySelector, like document.getElementsByClassName('parent')[0] if you so desire.


Edit: Now that I think about it, you could just use querySelectorAll to get decendents of parent having a class name of child1:

children = document.querySelectorAll('.parent .child1');

The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

How to add text to a WPF Label in code?

In normal winForms, value of Label object is changed by,

myLabel.Text= "Your desired string";

But in WPF Label control, you have to use .content property of Label control for example,

myLabel.Content= "Your desired string";

Connection string using Windows Authentication

This is shorter and works

<connectionStrings>      
<add name="DBConnection"
             connectionString="data source=SERVER\INSTANCE;
       Initial Catalog=MyDB;Integrated Security=SSPI;"
             providerName="System.Data.SqlClient" />
</connectionStrings> 

Persist Security Info not needed

Declaring a custom android UI element using XML

Thanks a lot for the first answer.

As for me, I had just one problem with it. When inflating my view, i had a bug : java.lang.NoSuchMethodException : MyView(Context, Attributes)

I resolved it by creating a new constructor :

public MyView(Context context, AttributeSet attrs) {
     super(context, attrs);
     // some code
}

Hope this will help !

Converting a double to an int in Javascript without rounding

As @Quentin and @Pointy pointed out in their comments, it's not a good idea to use parseInt() because it is designed to convert a string to an integer. When you pass a decimal number to it, it first converts the number to a string, then casts it to an integer. I suggest you use Math.trunc(), Math.floor(), ~~num, ~~v , num | 0, num << 0, or num >> 0 depending on your needs. This performance test demonstrates the difference in parseInt() and Math.floor() performance. Also, this post explains the difference between the proposed methods.

Converting string to double in C#

Add a class as Public and use it very easily like convertToInt32()

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;

  /// <summary>
  /// Summary description for Common
  /// </summary>
  public static class Common
  {
     public static double ConvertToDouble(string Value) {
        if (Value == null) {
           return 0;
        }
        else {
           double OutVal;
           double.TryParse(Value, out OutVal);

           if (double.IsNaN(OutVal) || double.IsInfinity(OutVal)) {
              return 0;
           }
           return OutVal;
        }
     }
  }

Then Call The Function

double DirectExpense =  Common.ConvertToDouble(dr["DrAmount"].ToString());

Get current clipboard content?

window.clipboardData.getData('Text') will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.

Specify JDK for Maven to use

I say you setup the JAVA_HOME environment variable like Pascal is saying: In Cygwin if you use bash as your shell should be:

export JAVA_HOME=/cygdrive/c/pathtothejdk

It never harms to also prepend the java bin directory path to the PATH environment variable with:

export PATH=${JAVA_HOME}/bin:${PATH}

Also add maven-enforce-plugin to make sure the right JDK is used. This is a good practice for your pom.

<build>
 <plugins>
   <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-enforcer-plugin</artifactId>
      <executions>
        <execution>
          <id>enforce-versions</id>
          <goals>
            <goal>enforce</goal>
          </goals>
          <configuration>
            <rules>
              <requireJavaVersion>
                <version>1.6</version>
              </requireJavaVersion>
            </rules>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Please, see Maven Enforcer plugin – Usage.

"unrecognized selector sent to instance" error in Objective-C

In my case I was using a UIWebView and I passed a NSString in the second parameter instead of a NSURL. So I suspect that wrong class types passed to a functions can cause this error.