Programs & Examples On #Updatecheck

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

There was conflict in java version. Resolved after using 1.8 for maven.

How to disable Google Chrome auto update?

  1. On your Chrome browser's address bar, type in 'about:plugins' and hit ENTER.

  2. Find the plugin called 'Google Update' and click disable.

  3. Restart your browser for the changes to take effect.

Android new Bottom Navigation bar or BottomNavigationView

My original answer dealt with the BottomNavigationView, but now there is a BottomAppBar. I added a section at the top for that with an implementation link.

Bottom App Bar

The BottomAppBar supports a Floating Action Button.

enter image description here

Image from here. See the documentation and this tutorial for help setting up the BottomAppBar.

Bottom Navigation View

The following full example shows how to make a Bottom Navigation View similar to the image in the question. See also Bottom Navigation in the documentation.

enter image description here

Add the design support library

Add this line to your app's build.grade file next to the other support library things.

implementation 'com.android.support:design:28.0.0'

Replace the version number with whatever is current.

Create the Activity layout

The only special thing we have added to the layout is the BottomNavigationView. To change the color of the icon and text when it is clicked, you can use a selector instead of specifying the color directly. This is omitted for simplicity here.

activity_main.xml

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

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bottom_nav_menu"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white" />

</RelativeLayout>

Notice that we used layout_alignParentBottom to actually put it at the bottom.

Define the menu items

The xml above for Bottom Navigation View referred to bottom_nav_menu. This is what defines each item in our view. We will make it now. All you have to do is add a menu resource just like you would for an Action Bar or Toolbar.

bottom_nav_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_recents"
        android:enabled="true"
        android:icon="@drawable/ic_action_recents"
        android:title="Recents"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_favorites"
        android:enabled="true"
        android:icon="@drawable/ic_action_favorites"
        android:title="Favorites"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_nearby"
        android:enabled="true"
        android:icon="@drawable/ic_action_nearby"
        android:title="Nearby"
        app:showAsAction="ifRoom" />
</menu>

You will need to add the appropriate icons to your project. This is not very difficult if you go to File > New > Image Asset and choose Action Bar and Tab Icons as the Icon Type.

Add an item selected listener

There is nothing special happening here. We just add a listener to the Bottom Navigation Bar in our Activity's onCreate method.

public class MainActivity extends AppCompatActivity {

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

        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_recents:
                        Toast.makeText(MainActivity.this, "Recents", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_favorites:
                        Toast.makeText(MainActivity.this, "Favorites", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_nearby:
                        Toast.makeText(MainActivity.this, "Nearby", Toast.LENGTH_SHORT).show();
                        break;

                }
                return true;
            }
        });
    }
}

Need more help?

I learned how to do this watching the following YouTube video. The computer voice is a little strange, but the demonstration is very clear.

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Why is __dirname not defined in node REPL?

In ES6 use:

import path from 'path';
const __dirname = path.resolve();

also available when node is called with --experimental-modules

How do I format a string using a dictionary in python-3.x?

Most answers formatted only the values of the dict.

If you want to also format the key into the string you can use dict.items():

geopoint = {'latitude':41.123,'longitude':71.091}
print("{} {}".format(*geopoint.items()))

Output:

('latitude', 41.123) ('longitude', 71.091)

If you want to format in an arbitry way, that is, not showing the key-values like tuples:

from functools import reduce
print("{} is {} and {} is {}".format(*reduce((lambda x, y: x + y), [list(item) for item in geopoint.items()])))

Output:

latitude is 41.123 and longitude is 71.091

Combine two arrays

Just use:

$output = array_merge($array1, $array2);

That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite proceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.

Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...

A workaround is to recreate the keys.

$output = array_combine($output, $output);

Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)

$output = $array1 + $array2;

All of this can be seen in: http://php.net/manual/en/function.array-merge.php

jQuery .scrollTop(); + animation

To do this, you can set a callback function for the animate command which will execute after the scroll animation has finished.

For example:

var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() { 
   alert("Finished animating");
});

Where that alert code is, you can execute more javascript to add in further animation.

Also, the 'swing' is there to set the easing. Check out http://api.jquery.com/animate/ for more info.

Sending HTTP POST with System.Net.WebClient

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

How to get longitude and latitude of any address?

<?php
$address = 'BTM 2nd Stage, Bengaluru, Karnataka 560076'; // Address
$apiKey = 'api-key'; // Google maps now requires an API key.
// Get JSON results from this request
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false&key='.$apiKey);
$geo = json_decode($geo, true); // Convert the JSON to an array

if (isset($geo['status']) && ($geo['status'] == 'OK')) {
  $latitude = $geo['results'][0]['geometry']['location']['lat']; // Latitude
  $longitude = $geo['results'][0]['geometry']['location']['lng']; // Longitude
}
?>

MySQL: Grant **all** privileges on database

This is old question but I don't think the accepted answer is safe. It's good for creating a super user but not good if you want to grant privileges on a single database.

grant all privileges on mydb.* to myuser@'%' identified by 'mypasswd';
grant all privileges on mydb.* to myuser@localhost identified by 'mypasswd';

% seems to not cover socket communications, that the localhost is for. WITH GRANT OPTION is only good for the super user, otherwise it is usually a security risk.

Update for MySQL 5.7+ seems like this warns about:

Using GRANT statement to modify existing user's properties other than privileges is deprecated and will be removed in future release. Use ALTER USER statement for this operation.

So setting password should be with separate commands. Thanks to comment from @scary-wombat.

ALTER USER 'myuser'@'%' IDENTIFIED BY 'mypassword';
ALTER USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';

Hope this helps.

How to set background color of an Activity to white programmatically?

The best method right now is of course

getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.main_activity_background_color));

Please be aware though, if you have anything set as the background color in Designer, it will overwrite anything you try to set in your code.

Classpath resource not found when running as jar

If you're using Spring framework then reading ClassPathResource into a String is pretty simple using Spring framework's FileCopyUtils:

String data = "";
ClassPathResource cpr = new ClassPathResource("static/file.txt");
try {
    byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
    data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
    LOG.warn("IOException", e);
}

CSS Layout - Dynamic width DIV

This will do what you want. Fixed sides with 50px-width, and the content fills the remaining area.

<div style="width:100%;">
    <div style="width: 50px; float: left;">Left Side</div>
    <div style="width: 50px; float: right;">Right Side</div>
    <div style="margin-left: 50px; margin-right: 50px;">Content Goes Here</div>
</div>

What is the difference between a candidate key and a primary key?

Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table) and the candidate key-> the same as Primary key but the Primary Key chosen by DB administrator's prospective for example(the primary key the least candidate key in size)

DB2 Query to retrieve all table names for a given schema

This should work:

select * from syscat.tables

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

In urlip3 there's no .urlopen, instead try this:

import requests
html = requests.get(url)

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

how do you insert null values into sql server

INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)

Check if a String is in an ArrayList of Strings

    List list1 = new ArrayList();
    list1.add("one");
    list1.add("three");
    list1.add("four");

    List list2 = new ArrayList();
    list2.add("one");
    list2.add("two");
    list2.add("three");
    list2.add("four");
    list2.add("five");


    list2.stream().filter( x -> !list1.contains(x) ).forEach(x -> System.out.println(x));

The output is:

two
five

How to read AppSettings values from a .json file in ASP.NET Core

You can try below code. This is working for me.

public class Settings
{
    private static IHttpContextAccessor _HttpContextAccessor;

    public Settings(IHttpContextAccessor httpContextAccessor)
    {
        _HttpContextAccessor = httpContextAccessor;
    }

    public static void Configure(IHttpContextAccessor httpContextAccessor)
    {
        _HttpContextAccessor = httpContextAccessor;
    }

    public static IConfigurationBuilder Getbuilder()
    {
        var builder = new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile("appsettings.json");
        return builder;
    }

    public static string GetAppSetting(string key)
    {
        //return Convert.ToString(ConfigurationManager.AppSettings[key]);
        var builder = Getbuilder();
        var GetAppStringData = builder.Build().GetValue<string>("AppSettings:" + key);
        return GetAppStringData;
    }

    public static string GetConnectionString(string key="DefaultName")
    {
        var builder = Getbuilder();
        var ConnectionString = builder.Build().GetValue<string>("ConnectionStrings:"+key);
        return ConnectionString;
    }
}

Here I have created one class to get connection string and app settings.

I Startup.cs file you need to register class as below.

public class Startup
{

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
        Settings.Configure(httpContextAccessor);
    }
}

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

AngularJS ng-repeat handle empty list case

You can use ngShow.

<li ng-show="!events.length">No events</li>

See example.

Or you can use ngHide

<li ng-hide="events.length">No events</li>

See example.

For object you can test Object.keys.

How to append text to an existing file in Java?

My answer:

JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";

try 
{
    RandomAccessFile random = new RandomAccessFile(file, "rw");
    long length = random.length();
    random.setLength(length + 1);
    random.seek(random.length());
    random.writeBytes(Content);
    random.close();
} 
catch (Exception exception) {
    //exception handling
}

Launch Image does not show up in my iOS App

I encountered this bug also with my landscape-only app. Following carlodurso's solution works:

  1. tick the "Landscape" box
  2. drag and drop the image to the place.

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

Create an ArrayList of unique values

I use helper class. Not sure it's good or bad

public class ListHelper<T> {
    private final T[] t;

    public ListHelper(T[] t) {
        this.t = t;
    }

    public List<T> unique(List<T> list) {
       Set<T> set = new HashSet<>(list);
        return Arrays.asList(set.toArray(t));
    }
}

Usage and test:

import static org.assertj.core.api.Assertions.assertThat;


public class ListHelperTest {

    @Test
    public void unique() {
        List<String> s = Arrays.asList("abc", "cde", "dfg", "abc");
        List<String> unique = new ListHelper<>(new String[0]).unique(s);
        assertThat(unique).hasSize(3);
    }
}

Or Java8 version:

public class ListHelper<T> {
    public Function<List<T>, List<T>> unique() {
        return l -> l.stream().distinct().collect(Collectors.toList());
    }
}

public class ListHelperTest {
    @Test
    public void unique() {
        List<String> s = Arrays.asList("abc", "cde", "dfg", "abc");
        assertThat(new ListHelper<String>().unique().apply(s)).hasSize(3);
    }
}

regular expression for DOT

Use String.Replace() if you just want to replace the dots from string. Alternative would be to use Pattern-Matcher with StringBuilder, this gives you more flexibility as you can find groups that are between dots. If using the latter, i would recommend that you ignore empty entries with "\\.+".

public static int count(String str, String regex) {
    int i = 0;
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(str);
    while (m.find()) {
        m.group();
        i++;
    }
    return i;
}

public static void main(String[] args) {
    int i = 0, j = 0, k = 0;
    String str = "-.-..-...-.-.--..-k....k...k..k.k-.-";

    // this will just remove dots
    System.out.println(str.replaceAll("\\.", ""));
    // this will just remove sequences of ".." dots
    System.out.println(str.replaceAll("\\.{2}", ""));
    // this will just remove sequences of dots, and gets
    // multiple of dots as 1
    System.out.println(str.replaceAll("\\.+", ""));

    /* for this to be more obvious, consider following */
    System.out.println(count(str, "\\."));
    System.out.println(count(str, "\\.{2}"));
    System.out.println(count(str, "\\.+"));
}

The output will be:

--------kkkkk--
-.--.-.-.---kk.kk.k-.-
--------kkkkk--
21
7
11

JVM property -Dfile.encoding=UTF8 or UTF-8?

Both UTF8 and UTF-8 work for me.

Difference between "char" and "String" in Java

char is a primitive type, and it can hold a single character.

String is instead a reference type, thus a full-blown object. It can hold any number of characters (internally, String objects save them in a char array).

Primitive types in Java have advantages in term of speed and memory footprint. But they are not real objects, so there are some possibilities you lose using them. They cannot be used as Generic type parameters, they could not have methods or fields, and so on.

However, every Java primitive type has a corresponding full-blown object, and the conversion between them is done automagically by the compiler (this is called autoboxing).

You can for example do:

int i=12;
Integer l=i;

The compiler takes care of converting the int to a Integer.

If statement in aspx page

To use C# (C# Script was initialized at 2015) on ASPX page you can make use the following syntax.

Start Tag:- <% End tag:- %> Please make sure that all the C# code must reside inside this <%%> .

Syntax Example:-

  • <%@ Import Namespace="System.Web.UI.WebControls" %> (For importing Namespace) Reference to some basic namespaces for working with ASPX page.

    <%@ Import Namespace="System.Web.UI.WebControls" %> <%@ Import Namespace="System.Diagnostics" %> <%@ Import Namespace="System" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.Web.UI" %> <%@ Import Namespace="System.IO" %>

C# Code:-

`<%
if (Session["New"] != null)
{
    Page.Title = ActionController.GetName(Session["New"].ToString());
}
%>`

Features of C# Script:

  • No need of compilation. Run time execution is occurred like Java Script.

Before using C# script make sure the following things:-

  • You are on WebForm. Not on WebForm with master page.
  • If you are in WebForm with master page make sure that you have written your C# script at Master page file.
  • C# script can be inserted anywhere in the aspx page but after the page meta declaration like

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Profile.master.cs" Inherits="OOSDDemo.Profile" %>

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %> (For WebForm)

Removing Java 8 JDK from Mac

Use /usr/libexec/java_home ; I found these alias and function to be pretty useful in my ~/.profile:

alias java_ls='/usr/libexec/java_home -V 2>&1 | cut -s -d , -f 1 | cut -c 5-'
function java_use() {
    export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    java -version
}

Pandas DataFrame column to list

You can use the Series.to_list method.

For example:

import pandas as pd

df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
                   'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})

print(df['a'].to_list())

Output:

[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]

To drop duplicates you can do one of the following:

>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]

How to read a text file into a string variable and strip newlines?

You could use:

with open('data.txt', 'r') as file:
    data = file.read().replace('\n', '')

Javascript Audio Play on click

Try the below code snippet

<!doctype html>
<html>
  <head>
    <title>Audio</title>
  </head>
  <body>

    <script>
      function play() {
        var audio = document.getElementById("audio");
        audio.play();
      }
    </script>

    <input type="button" value="PLAY" onclick="play()">
    <audio id="audio" src="http://dev.interactive-creation-works.net/1/1.ogg"></audio>

  </body>
</html>

Twitter Bootstrap scrollable table rows and fixed header

Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)

  <table id="tableHeader" class="table" style="table-layout:fixed">
        <thead>
            <tr>
                <th>Col1</th>
                ...
            </tr>
        </thead>
  </table>
  <div style="overflow-y:auto;">
    <table id="tableData" class="table table-condensed" style="table-layout:fixed">
        <tbody>
            <tr>
                <td>data</td>
                ...
            </tr>
        </tbody>
    </table>
 </div>

Demo JSFiddle

The content table div needs overflow-y:auto, for vertical scroll bars. Had to use table-layout:fixed, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.

Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.

    // ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
    $(function () {

        //copy width of header cells to match width of cells with data
        //so they line up properly
        var tdHeader = document.getElementById("tableHeader").rows[0].cells;
        var tdData = document.getElementById("tableData").rows[0].cells;

        for (var i = 0; i < tdData.length; i++)
            tdHeader[i].style.width = tdData[i].offsetWidth + 'px';

    });

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

break/exit script

You could use the stopifnot() function if you want the program to produce an error:

foo <- function(x) {
    stopifnot(x > 500)
    # rest of program
}

IOError: [Errno 13] Permission denied

IOError: [Errno 13] Permission denied: 'juliodantas2015.json'

tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.

Integrating CSS star rating into an HTML form

I'm going to say right off the bat that you will not be able to achieve the look they have with radio buttons with strictly CSS.

You could, however, stick to the list style in the example you posted and replace the anchors with clickable spans that would trigger a javascript event that would in turn save that rating to your database via ajax.

If you went that route you would probably also want to save a cookie to the users machine so that they could not submit over and over again to your database. That would prevent them from submitting more than once at least until they deleted their cookies.

But of course there are many ways to address this problem. This is just one of them. Hope that helps.

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

Button Center CSS

I realize this is a very old question, but I stumbled across this problem today and I got it to work with

<div style="text-align:center;">
    <button>button1</button>
    <button>button2</button>
</div>

Cheers, Mark

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

C++ int to byte array

An int (or any other data type for that matter) is already stored as bytes in memory. So why not just copy the memory directly?

memcpy(arrayOfByte, &x, sizeof x);

A simple elegant one liner that will also work with any other data type.



If you need the bytes reversed you can use std::reverse

memcpy(arrayOfByte, &x, sizeof x);
std::reverse(arrayOfByte, arrayOfByte + sizeof x);

or better yet, just copy the bytes in reverse to begin with

BYTE* p = (BYTE*) &x;
std::reverse_copy(p, p + sizeof x, arrayOfByte);

If you don't want to make a copy of the data at all, and just have its byte representation

BYTE* bytes = (BYTE*) &x;

Magento: get a static block as html in a phtml file

If you have created CMS block named 'block_identifier' from admin panel. Then following will be code to call them in .phtml

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block_identifier')->toHtml(); 
?> 

Character reading from file in Python

Ref: http://docs.python.org/howto/unicode

Reading Unicode from a file is therefore simple:

import codecs
with codecs.open('unicode.rst', encoding='utf-8') as f:
    for line in f:
        print repr(line)

It's also possible to open files in update mode, allowing both reading and writing:

with codecs.open('test', encoding='utf-8', mode='w+') as f:
    f.write(u'\u4500 blah blah blah\n')
    f.seek(0)
    print repr(f.readline()[:1])

EDIT: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII.

If you're trying to convert to an ASCII string, try one of the following:

  1. Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example

  2. Use the unicodedata module's normalize() and the string.encode() method to convert as best you can to the next closest ASCII equivalent (Ref https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python):

    >>> teststr
    u'I don\xe2\x80\x98t like this'
    >>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')
    'I donat like this'
    

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

Solution for me without reinstalling or creating a new project:

Step 1: Change line in build.gradle from:

dependencies {
    classpath 'com.android.tools.build:gradle:0.4'
}

to

dependencies {
    classpath 'com.android.tools.build:gradle:0.5.+'
}

Note: for newer versions of gradle you may need to change it to 0.6.+ instead.

Step 2: In the <YourProject>.iml file, delete the entire<component name="FacetManager">[...]</component> tag.

Step 3 (Maybe not necessary): In the Android SDK manager, install (if not already installed) Android Support Repository under Extras.


Info found here

Trying to get property of non-object - CodeIgniter

To get the value:

$query = $this->db->query("YOUR QUERY");

Then, for single row from(in controller):

$query1 = $query->row();
$data['product'] = $query1;

In view, you can use your own code (above code)

How do I make a WinForms app go Full Screen

To the base question, the following will do the trick (hiding the taskbar)

private void Form1_Load(object sender, EventArgs e)
{
    this.TopMost = true;
    this.FormBorderStyle = FormBorderStyle.None;
    this.WindowState = FormWindowState.Maximized;
}

But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.

Check if an object belongs to a class in Java

If you ever need to do this dynamically, you can use the following:

boolean isInstance(Object object, Class<?> type) {
    return type.isInstance(object);
}

You can get an instance of java.lang.Class by calling the instance method Object::getClass on any object (returns the Class which that object is an instance of), or you can do class literals (for example, String.class, List.class, int[].class). There are other ways as well, through the reflection API (which Class itself is the entry point for).

Apache 13 permission denied in user's home directory

im using CentOS 5.5 and for me it was SElinux messing with it, i forgot to check that out. you can temporary disable it by doing as root

echo 0 > /selinux/enforce

hope it help someone

How to iterate over array of objects in Handlebars?

This fiddle has both each and direct json. http://jsfiddle.net/streethawk707/a9ssja22/.

Below are the two ways of iterating over array. One is with direct json passing and another is naming the json array while passing to content holder.

Eg1: The below example is directly calling json key (data) inside small_data variable.

In html use the below code:

<div id="small-content-placeholder"></div>

The below can be placed in header or body of html:

<script id="small-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#data}}
                <tr>
                    <td>{{username}}
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/data}}
        </tbody>
    </table>
</script>

The below one is on document ready:

var small_source   = $("#small-template").html();
var small_template = Handlebars.compile(small_source);

The below is the json:

var small_data = {
            data: [
                {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" }
            ]
        };

Finally attach the json to content holder:

$("#small-content-placeholder").html(small_template(small_data));

Eg2: Iteration using each.

Consider the below json.

var big_data = [
            {
                name: "users1",
                details: [
                    {username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison1", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            },
            {
                name: "users2",
                details: [
                    {username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
                    {username: "allison2", firstName: "Allison", lastName: "House", email: "[email protected]" },
                    {username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
                  ]
            }
      ];

While passing the json to content holder just name it in this way:

$("#big-content-placeholder").html(big_template({big_data:big_data}));

And the template looks like :

<script id="big-template" type="text/x-handlebars-template">
    <table>
        <thead>
            <th>Username</th>
            <th>email</th>
        </thead>
        <tbody>
            {{#each big_data}}
                <tr>
                    <td>{{name}}
                            <ul>
                                {{#details}}
                                    <li>{{username}}</li>
                                    <li>{{email}}</li>
                                {{/details}}
                            </ul>
                    </td>
                    <td>{{email}}</td>
                </tr>
            {{/each}}
        </tbody>
    </table>
</script>

How to make an empty div take space

it works if you remove floating. http://jsbin.com/izoca/2/edit

with floats it only works if theres some content e.g. &nbsp;

How to replace item in array?

presentPrompt(id,productqty) {
    let alert = this.forgotCtrl.create({
      title: 'Test',
      inputs: [
        {
          name: 'pickqty',
          placeholder: 'pick quantity'
        },
        {
          name: 'state',
          value: 'verified',
          disabled:true,
          placeholder: 'state',

        }
      ],
      buttons: [
        {
          text: 'Ok',
          role: 'cancel',
          handler: data => {

            console.log('dataaaaname',data.pickqty);
            console.log('dataaaapwd',data.state);


          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
                this.cottonLists[i].real_stock = data.pickqty;

            }
          }

          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
              this.cottonLists[i].state = 'verified';   

          }
        }
            //Log object to console again.
            console.log("After update: ", this.cottonLists)
            console.log('Ok clicked');
          }
        },

      ]
    });
    alert.present();
  }

As per your requirement you can change fields and array names.
thats all. Enjoy your coding.

How to fix nginx throws 400 bad request headers on any header testing tools?

normally, Maxim Donnie's method can find the reason. But I encountered one 400 bad request will not log to err_log. I found the reason with the help with tcpdump

Adding elements to a C# array

You can use a generic collection, like List<>

List<string> list = new List<string>();

// add
list.Add("element");

// remove
list.Remove("element");

HTML5 Local storage vs. Session storage

performance wise, my (crude) measurements found no difference on 1000 writes and reads

security wise, intuitively it would seem the localStore might be shut down before the sessionStore, but have no concrete evidence - maybe someone else does?

functional wise, concur with digitalFresh above

Nullable property to entity field, Entity Framework through Code First

Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }

// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }

How do I search for files in Visual Studio Code?

For windows. if Ctrl+p doesn't always work use Ctrl+shift+n instead.

Count of "Defined" Array Elements

Loop and count in all browsers:

var cnt = 0;
for (var i = 0; i < arr.length; i++) {
    if (arr[i] !== undefined) {
        ++cnt;
    }
}

In modern browsers:

var cnt = 0;
arr.foreach(function(val) {
    if (val !== undefined) { ++cnt; }
})

How to save a bitmap on internal storage

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}

ActiveMQ or RabbitMQ or ZeroMQ or

Edit: My initial answer had a strong focus on AMQP. I decided to rewrite it to offer a wider view on the topic.

These 3 messaging technologies have different approaches on building distributed systems :

RabbitMQ is one of the leading implementation of the AMQP protocol (along with Apache Qpid). Therefore, it implements a broker architecture, meaning that messages are queued on a central node before being sent to clients. This approach makes RabbitMQ very easy to use and deploy, because advanced scenarios like routing, load balancing or persistent message queuing are supported in just a few lines of code. However, it also makes it less scalable and “slower” because the central node adds latency and message envelopes are quite big.

ZeroMq is a very lightweight messaging system specially designed for high throughput/low latency scenarios like the one you can find in the financial world. Zmq supports many advanced messaging scenarios but contrary to RabbitMQ, you’ll have to implement most of them yourself by combining various pieces of the framework (e.g : sockets and devices). Zmq is very flexible but you’ll have to study the 80 pages or so of the guide (which I recommend reading for anybody writing distributed system, even if you don’t use Zmq) before being able to do anything more complicated than sending messages between 2 peers.

ActiveMQ is in the middle ground. Like Zmq, it can be deployed with both broker and P2P topologies. Like RabbitMQ, it’s easier to implement advanced scenarios but usually at the cost of raw performance. It’s the Swiss army knife of messaging :-).

Finally, all 3 products:

  • have client apis for the most common languages (C++, Java, .Net, Python, Php, Ruby, …)
  • have strong documentation
  • are actively supported

How to check if a string is numeric?

Many options explored at http://www.coderanch.com/t/405258/java/java/String-IsNumeric

One more is

public boolean isNumeric(String s) {  
    return s != null && s.matches("[-+]?\\d*\\.?\\d+");  
}  

Might be overkill but Apache Commons NumberUtils seems to have some helpers as well.

Android add placeholder text to EditText

In Android Studio you can add Hint (Place holder) through GUI. First select EditText field on designer view. Then Click on Component Tree Left side of IDE (Normally it's there, but it may be there minimized) There you can see Properties of selected EditText. Find Hint field as below Image

enter image description here

There you can add Hint(Place holder) to EditText

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

What is the use of ByteBuffer in Java?

Here is a great article explaining ByteBuffer benefits. Following are the key points in the article:

  • First advantage of a ByteBuffer irrespective of whether it is direct or indirect is efficient random access of structured binary data (e.g., low-level IO as stated in one of the answers). Prior to Java 1.4, to read such data one could use a DataInputStream, but without random access.

Following are benefits specifically for direct ByteBuffer/MappedByteBuffer. Note that direct buffers are created outside of heap:

  1. Unaffected by gc cycles: Direct buffers won't be moved during garbage collection cycles as they reside outside of heap. TerraCota's BigMemory caching technology seems to rely heavily on this advantage. If they were on heap, it would slow down gc pause times.

  2. Performance boost: In stream IO, read calls would entail system calls, which require a context-switch between user to kernel mode and vice versa, which would be costly especially if file is being accessed constantly. However, with memory-mapping this context-switching is reduced as data is more likely to be found in memory (MappedByteBuffer). If data is available in memory, it is accessed directly without invoking OS, i.e., no context-switching.

Note that MappedByteBuffers are very useful especially if the files are big and few groups of blocks are accessed more frequently.

  1. Page sharing: Memory mapped files can be shared between processes as they are allocated in process's virtual memory space and can be shared across processes.

How to display my application's errors in JSF?

Remember that:

FacesContext context = FacesContext.getCurrentInstance();
context.addMessage( null, new FacesMessage( "The message to display in client" ));            

is also valid, because when null is specified as first parameter, it is applied to the whole form.

More info: coreservlets.com //Outdated

Head and tail in one line

Under Python 3.x, you can do this nicely:

>>> head, *tail = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

A new feature in 3.x is to use the * operator in unpacking, to mean any extra values. It is described in PEP 3132 - Extended Iterable Unpacking. This also has the advantage of working on any iterable, not just sequences.

It's also really readable.

As described in the PEP, if you want to do the equivalent under 2.x (without potentially making a temporary list), you have to do this:

it = iter(iterable)
head, tail = next(it), list(it)

As noted in the comments, this also provides an opportunity to get a default value for head rather than throwing an exception. If you want this behaviour, next() takes an optional second argument with a default value, so next(it, None) would give you None if there was no head element.

Naturally, if you are working on a list, the easiest way without the 3.x syntax is:

head, tail = seq[0], seq[1:]

What is javax.inject.Named annotation supposed to be used for?

The primary role of the @Named annotation is to define a bean for the purpose of resolving EL statements within the application, usually through JSF EL resolvers. Injection can be performed using names but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.

Do Git tags only apply to the current branch?

We can create a tag for some past commit:

git tag [tag_name] [reference_of_commit]

eg:

git tag v1.0 5fcdb03

In R, how to find the standard error of the mean?

The standard error (SE) is just the standard deviation of the sampling distribution. The variance of the sampling distribution is the variance of the data divided by N and the SE is the square root of that. Going from that understanding one can see that it is more efficient to use variance in the SE calculation. The sd function in R already does one square root (code for sd is in R and revealed by just typing "sd"). Therefore, the following is most efficient.

se <- function(x) sqrt(var(x)/length(x))

in order to make the function only a bit more complex and handle all of the options that you could pass to var, you could make this modification.

se <- function(x, ...) sqrt(var(x, ...)/length(x))

Using this syntax one can take advantage of things like how var deals with missing values. Anything that can be passed to var as a named argument can be used in this se call.

How do I use modulus for float/double?

You probably had a typo when you first ran it.

evaluating 0.5 % 0.3 returns '0.2' (A double) as expected.

Mindprod has a good overview of how modulus works in Java.

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

I had the same problem, in my case handler was in two places:

<system.web>
...
<httpHandlers>
 <add verb="*" path="*.ashx" type="ApplicArt.Extranet2.Controller.FrontController, ApplicArt.Extranet2.Web.UI" />
  </httpHandlers>
</system.web>

<system.webServer>
<handlers>
   ...
  <add name="FrontController" verb="*" path="*.ashx" type="ApplicArt.Extranet2.Controller.FrontController, ApplicArt.Extranet2.Web.UI"/>
</handlers>
</system.webServer>

And when I removed my handler from [system.webServer] my problem disappeared.

How can I do an OrderBy with a dynamic string parameter?

In one answer above:

The simplest & the best solution:

mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s));

There is an syntax error, ,null must be added:

mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s,null));

How to send email attachments?

The simplest code I could get to is:

#for attachment email
from django.core.mail import EmailMessage

    def attachment_email(request):
            email = EmailMessage(
            'Hello', #subject
            'Body goes here', #body
            '[email protected]', #from
            ['[email protected]'], #to
            ['[email protected]'], #bcc
            reply_to=['[email protected]'],
            headers={'Message-ID': 'foo'},
            )

            email.attach_file('/my/path/file')
            email.send()

It was based on the official Django documentation

Create a directory if it does not exist and then create the files in that directory as well

Using java.nio.Path it would be quite simple -

public static Path createFileWithDir(String directory, String filename) {
        File dir = new File(directory);
        if (!dir.exists()) dir.mkdirs();
        return Paths.get(directory + File.separatorChar + filename);
    }

Source file not compiled Dev C++

This maybe because the c compiler is designed to work in linux.I had this problem too and to fix it go to tools and select compiler options.In the box click on programs

Now you will see a tab with gcc and make and the respective path to it.Edit the gcc and make path to use mingw32-c++.exe and mingw32-make.exe respectively.Now it will work.

The Answer

The reason was that you were using compilers built for linux.

How to remove spaces from a string using JavaScript?

_x000D_
_x000D_
var a = b = " /var/www/site/Brand new   document.docx ";_x000D_
_x000D_
console.log( a.split(' ').join('') );_x000D_
console.log( b.replace( /\s/g, '') ); 
_x000D_
_x000D_
_x000D_

Two ways of doing this!

Set bootstrap modal body height by percentage

Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.

I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.

If you just want the content to scroll, you could leave out the part that limits the size of the modal body.

/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
  margin: 2.5vh auto;
}

/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
  max-height: 95vh;
  overflow: scroll;
}

/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
  max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
  max-height: 69vh;
}

Bootstrap: adding gaps between divs

Adding a padding between the divs to simulate a gap might be a hack, but why not use something Bootstrap provides. It's called offsets. But again, you can define a class in your custom.css (you shouldn't edit the core stylesheet anyway) file and add something like .gap. However, .col-md-offset-* does the job most of the times for me, allowing me to precisely leave a gap between the divs.

As for vertical spacing, unfortunately, there isn't anything set built-in like that in Bootstrap 3, so you will have to invent your own custom class to do that. I'd usually do something like .top-buffer { margin-top:20px; }. This does the trick, and obviously, it doesn't have to be 20px, it can be anything you like.

Run Button is Disabled in Android Studio

I just clicked on the debug icon and it started working.

enter image description here

How do you overcome the svn 'out of date' error?

I did this and it worked for me:
1. Take a back-up of your file. You can simply copy your code to a text file.
2. Right Click the file you want to commit >> Team >> Show History. 3. In "Show History" Panel you will see all the revisions of that file. Right click on latest revision of the file >> Get Revision: It will override your local changes.
4. Now, merge your code with the latest file with the back-up file (step#1).
5. Synchronise and Commit the newly merged file.

Set NOW() as Default Value for datetime datatype?

EUREKA !!!


For all those who lost heart trying to set a default DATETIME value in MySQL, I know exactly how you feel/felt. So here it is:

`ALTER TABLE  `table_name` CHANGE `column_name` DATETIME NOT NULL DEFAULT 0

Carefully observe that I haven't added single quotes/double quotes around the 0.


Important update:

This answer was posted long back. Back then, it worked on my (probably latest) installation of MySQL and I felt like sharing it. Please read the comments below before you decide to use this solution now.

What does "for" attribute do in HTML <label> tag?

It labels whatever input is the parameter for the for attribute.

_x000D_
_x000D_
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
_x000D_
_x000D_

Displaying a message in iOS which has the same functionality as Toast in Android

This is how I have done in Swift 3.0. I created UIView extension and calling the self.view.showToast(message: "Message Here", duration: 3.0) and self.view.hideToast()

extension UIView{
var showToastTag :Int {return 999}

//Generic Show toast
func showToast(message : String, duration:TimeInterval) {

    let toastLabel = UILabel(frame: CGRect(x:0, y:0, width: (self.frame.size.width)-60, height:64))

    toastLabel.backgroundColor = UIColor.gray
    toastLabel.textColor = UIColor.black
    toastLabel.numberOfLines = 0
    toastLabel.layer.borderColor = UIColor.lightGray.cgColor
    toastLabel.layer.borderWidth = 1.0
    toastLabel.textAlignment = .center;
    toastLabel.font = UIFont(name: "HelveticaNeue", size: 17.0)
    toastLabel.text = message
    toastLabel.center = self.center
    toastLabel.isEnabled = true
    toastLabel.alpha = 0.99
    toastLabel.tag = showToastTag
    toastLabel.layer.cornerRadius = 10;
    toastLabel.clipsToBounds  =  true
    self.addSubview(toastLabel)

    UIView.animate(withDuration: duration, delay: 0.1, options: .curveEaseOut, animations: {
        toastLabel.alpha = 0.95
    }, completion: {(isCompleted) in
        toastLabel.removeFromSuperview()
    })
}

//Generic Hide toast
func hideToast(){
    if let view = self.viewWithTag(self.showToastTag){
        view.removeFromSuperview()
    }
  }
}

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

I've investigated this issue, referring to the LayoutInflater docs and setting up a small sample demonstration project. The following tutorials shows how to dynamically populate a layout using LayoutInflater.

Before we get started see what LayoutInflater.inflate() parameters look like:

  • resource: ID for an XML layout resource to load (e.g., R.layout.main_page)
  • root: Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
  • attachToRoot: Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

  • Returns: The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.

Now for the sample layout and code.

Main layout (main.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</LinearLayout>

Added into this container is a separate TextView, visible as small red square if layout parameters are successfully applied from XML (red.xml):

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:background="#ff0000"
    android:text="red" />

Now LayoutInflater is used with several variations of call parameters

public class InflaterTest extends Activity {

    private View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(R.layout.main);
      ViewGroup parent = (ViewGroup) findViewById(R.id.container);

      // result: layout_height=wrap_content layout_width=match_parent
      view = LayoutInflater.from(this).inflate(R.layout.red, null);
      parent.addView(view);

      // result: layout_height=100 layout_width=100
      view = LayoutInflater.from(this).inflate(R.layout.red, null);
      parent.addView(view, 100, 100);

      // result: layout_height=25dp layout_width=25dp
      // view=textView due to attachRoot=false
      view = LayoutInflater.from(this).inflate(R.layout.red, parent, false);
      parent.addView(view);

      // result: layout_height=25dp layout_width=25dp 
      // parent.addView not necessary as this is already done by attachRoot=true
      // view=root due to parent supplied as hierarchy root and attachRoot=true
      view = LayoutInflater.from(this).inflate(R.layout.red, parent, true);
    }
}

The actual results of the parameter variations are documented in the code.

SYNOPSIS: Calling LayoutInflater without specifying root leads to inflate call ignoring the layout parameters from the XML. Calling inflate with root not equal null and attachRoot=true does load the layout parameters, but returns the root object again, which prevents further layout changes to the loaded object (unless you can find it using findViewById()). The calling convention you most likely would like to use is therefore this one:

loadedView = LayoutInflater.from(context)
                .inflate(R.layout.layout_to_load, parent, false);

To help with layout issues, the Layout Inspector is highly recommended.

How to convert from int to string in objective c: example code

If you just need an int to a string as you suggest, I've found the easiest way is to do as below:

[NSString stringWithFormat:@"%d",numberYouAreTryingToConvert]

JQuery - how to select dropdown item based on value

$('#mySelect').val('fg');...........

Inline <style> tags vs. inline css properties

There can be different reasons for choosing one way over the other.

  • If you need to specify css to elements that are generated programmatically (for example modifying css for images of different sizes), it can be more maintainable to use inline css.
  • If some css is valid only for the current page, you should rather use the script tag than a separate .css file. It is good if the browser doesn't have to do too many http requests.

Otherwise, as stated, it is better to use a separate css file.

How do you execute an arbitrary native command from a string?

Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).

http://connect.microsoft.com/PowerShell/feedback/details/376207/

They suggest using --% as a way to force PowerShell to stop trying to interpret the text to the right.

For example:

MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj

Redirect from a view to another view

It's because your statement does not produce output.

Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.

If you want to execute methods that don't directly produce output, you do:

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

This is also true for rendering partials like:

@{ Html.RenderPartial("_MyPartial"); }

PHP: If internet explorer 6, 7, 8 , or 9

Here's a little php function I wrote that uses the regex directly from MSFT's suggested javascript sniffing code from this article: http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx

/**
* Returns the version of Internet Explorer or false
*/
function isIE(){

    $isIE = preg_match("/MSIE ([0-9]{1,}[\.0-9]{0,})/",$_SERVER['HTTP_USER_AGENT'],$version);
    if($isIE){
        return $version[1];
    }
    return $isIE;

}

How do I use method overloading in Python?

You can also use pythonlangutil:

from pythonlangutil.overload import Overload, signature

class A:
    @Overload
    @signature()
    def stackoverflow(self):    
        print 'first method'

    @stackoverflow.overload
    @signature("int")
    def stackoverflow(self, i):
        print 'second method', i

How to use Python's pip to download and keep the zipped files for a package?

Use pip download <package1 package2 package n> to download all the packages including dependencies

Use pip install --no-index --find-links . <package1 package2 package n> to install all the packages including dependencies. It gets all the files from CWD. It will not download anything

How do I make a branch point at a specific commit?

You can make master point at 1258f0d0aae this way:

git checkout master
git reset --hard 1258f0d0aae

But you have to be careful about doing this. It may well rewrite the history of that branch. That would create problems if you have published it and other people are working on the branch.

Also, the git reset --hard command will throw away any uncommitted changes (i.e. those just in your working tree or the index).

You can also force an update to a branch with:

git branch -f master 1258f0d0aae

... but git won't let you do that if you're on master at the time.

Inserting line breaks into PDF

You state that

2 is the height of the multi-line text box

No it's not. 2 is the distance between lines of text.

I don't think there is a real way for calculating the height of the actual resulting text box, unless you use GetY() and then subtract the original Y value used in your SetXY() statement for placing the Multicell in the first place.

python BeautifulSoup parsing table

Updated Answer

If a programmer is interested in only parsing a table from a webpage, they can utilize the pandas method pandas.read_html.

Let's say we want to extract the GDP data table from the website: https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries

Then following codes does the job perfectly (No need of beautifulsoup and fancy html):

import pandas as pd
import requests

url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"

r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
df = df_list[0]
df.head()

Output

First five lines of the table from the Website

print call stack in C or C++

Is there any way to dump the call stack in a running process in C or C++ every time a certain function is called?

No there is not, although platform-dependent solutions might exist.

How to find specified name and its value in JSON-string from Java?

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";

  String age;

  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

Why are elementwise additions much faster in separate loops than in a combined loop?

Imagine you are working on a machine where n was just the right value for it only to be possible to hold two of your arrays in memory at one time, but the total memory available, via disk caching, was still sufficient to hold all four.

Assuming a simple LIFO caching policy, this code:

for(int j=0;j<n;j++){
    a[j] += b[j];
}
for(int j=0;j<n;j++){
    c[j] += d[j];
}

would first cause a and b to be loaded into RAM and then be worked on entirely in RAM. When the second loop starts, c and d would then be loaded from disk into RAM and operated on.

the other loop

for(int j=0;j<n;j++){
    a[j] += b[j];
    c[j] += d[j];
}

will page out two arrays and page in the other two every time around the loop. This would obviously be much slower.

You are probably not seeing disk caching in your tests but you are probably seeing the side effects of some other form of caching.


There seems to be a little confusion/misunderstanding here so I will try to elaborate a little using an example.

Say n = 2 and we are working with bytes. In my scenario we thus have just 4 bytes of RAM and the rest of our memory is significantly slower (say 100 times longer access).

Assuming a fairly dumb caching policy of if the byte is not in the cache, put it there and get the following byte too while we are at it you will get a scenario something like this:

  • With

    for(int j=0;j<n;j++){
     a[j] += b[j];
    }
    for(int j=0;j<n;j++){
     c[j] += d[j];
    }
    
  • cache a[0] and a[1] then b[0] and b[1] and set a[0] = a[0] + b[0] in cache - there are now four bytes in cache, a[0], a[1] and b[0], b[1]. Cost = 100 + 100.

  • set a[1] = a[1] + b[1] in cache. Cost = 1 + 1.
  • Repeat for c and d.
  • Total cost = (100 + 100 + 1 + 1) * 2 = 404

  • With

    for(int j=0;j<n;j++){
     a[j] += b[j];
     c[j] += d[j];
    }
    
  • cache a[0] and a[1] then b[0] and b[1] and set a[0] = a[0] + b[0] in cache - there are now four bytes in cache, a[0], a[1] and b[0], b[1]. Cost = 100 + 100.

  • eject a[0], a[1], b[0], b[1] from cache and cache c[0] and c[1] then d[0] and d[1] and set c[0] = c[0] + d[0] in cache. Cost = 100 + 100.
  • I suspect you are beginning to see where I am going.
  • Total cost = (100 + 100 + 100 + 100) * 2 = 800

This is a classic cache thrash scenario.

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

This works with me :
1- select the cells which shall be be affected by the drop down list .
2- home -> conditional formating -> new rule .
3- format only cells that contain .
4- in format only cells with ... select specific text , in formatting rule "= select Elementary from your drop down list"
if drop list in another sheet then when select Elementary we see "=Sheet3!$F$2" in the new rule , with your own sheet and cell number.
5- format -> fill -> select color -> ok.
6-ok .
do the same for each element in drop down list then you will see the magic !

How to create an array of object literals in a loop?

You can do something like that in ES6.

new Array(10).fill().map((e,i) => {
   return {idx: i}
});

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

Android custom Row Item for ListView

you can follow BaseAdapter and create your custome Xml file and bind it with you BaseAdpter and populate it with Listview see here need to change xml file as Require.

C# Creating and using Functions

you have to make you're function static like this

namespace Add_Function
{
  class Program
  {
    public static void(string[] args)
    {
       int a;
       int b;
       int c;

       Console.WriteLine("Enter value of 'a':");
       a = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Enter value of 'b':");
       b = Convert.ToInt32(Console.ReadLine());

       //why can't I not use it this way?
       c = Add(a, b);
       Console.WriteLine("a + b = {0}", c);
    }
    public static int Add(int x, int y)
    {
        int result = x + y;
        return result;
     }
  }
}

you can do Program.Add instead of Add you also can make a new instance of Program by going like this

Program programinstance = new Program();

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

maybe you have code like this before the jquery:

var $jq=jQuery.noConflict();
$jq('ul.menu').lavaLamp({
    fx: "backout", 
    speed: 700
});

and them was Conflict

you can change $ to (jQuery)

Where value in column containing comma delimited values

select *
from YourTable
where ','+replace(col, ' ', '')+',' like '%,Cat,%'

How to remove default chrome style for select Input?

Are you talking about when you click on an input box, rather than just hover over it? This fixed it for me:

input:focus {
   outline: none;
   border: specify yours;
}

Sort ArrayList of custom Objects by property

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

Since

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

Byte Array in Python

In Python 3, we use the bytes object, also known as str in Python 2.

# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

I find it more convenient to use the base64 module...

# Python 3
key = base64.b16decode(b'130000000800')

# Python 2
key = base64.b16decode('130000000800')

You can also use literals...

# Python 3
key = b'\x13\0\0\0\x08\0'

# Python 2
key = '\x13\0\0\0\x08\0'

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

Change httpd.conf file as follows:

from

<Directory />
    AllowOverride none
    Require all denied
</Directory>

to

<Directory />
    AllowOverride none
    Require all granted
</Directory>

jQuery Ajax requests are getting cancelled without being sent

I had a similar problem. In my case, I'm trying to use a web service on a apache server + django (the service was written by myself). I was having the same output as you: Chrome says it was cancelled while FF does it okay. If I tried to access the service directly on the the browser instead of ajax, it would work as well. Googling around, I found out that some newer versions of apache weren't setting the length of the response correctly in the response headers, so I did this manually. With django, all I had to do was:

response['Content-Length'] = len(content)

If you have control over the service you are trying to access, find out how to modify the response header in the platform you are using, otherwise you'd have to contact the service provider to fix this issue. Apparently, FF and many others browsers are able to handle this situation correctly, but Chrome designers decided to do it as specified.

How to Delete node_modules - Deep Nested Folder in Windows

simple just run for windows I haven't tested it for other operating systems

rm -r node_modules

in fact, you can delete any folder with this.

like rm -r AnyFolderWhichIsNotDeletableFromShiftDeleteOrDelete.

just open the gitbash move to root of the folder and run this command

Hope this will help.

Thanks, Ajay Kotnala

Ignore cells on Excel line graph

Not for blanks in the middle of a range, but this works for a complex chart from a start date until infinity (ie no need to adjust the chart's data source each time informatiom is added), without showing any lines for dates that have not yet been entered. As you add dates and data to the spreadsheet, the chart expands. Without it, the chart has a brain hemorrhage.

So, to count a complex range of conditions over an extended period of time but only if the date of the events is not blank :

=IF($B6<>"",(COUNTIF($O6:$O6,Q$5)),"") returns “#N/A” if there is no date in column B.

In other words, "count apples or oranges or whatever in column O (as determined by what is in Q5) but only if column B (the dates) is not blank". By returning “#N/A”, the chart will skip the "blank" rows (blank as in a zero value or rather "#N/A").

From that table of returned values you can make a chart from a date in the past to infinity

Docker is in volume in use, but there aren't any Docker containers

I am fairly new to Docker. I was cleaning up some initial testing mess and was not able to remove a volume either. I had stopped all the running instances, performed a docker rmi -f $(docker image ls -q), but still received the Error response from daemon: unable to remove volume: remove uuid: volume is in use.

I did a docker system prune and it cleaned up what was needed to remove the last volume:

[0]$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Containers:
... about 15 containers UUID's truncated

Total reclaimed space: 2.273MB
[0]$ docker volume ls
DRIVER              VOLUME NAME
local              uuid
[0]$ docker volume rm uuid
uuid
[0]$

docker system prune

The client and daemon API must both be at least 1.25 to use this command. Use the docker version command on the client to check your client and daemon API versions.

Using JQuery to check if no radio button in a group has been checked

if (!$("input[name='html_elements']:checked").val()) {
   alert('Nothing is checked!');
}
else {
  alert('One of the radio buttons is checked!');
}

Rails 4: List of available datatypes

Rails4 has some added datatypes for Postgres.

For example, railscast #400 names two of them:

Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.

Besides, you can also use cidr, inet and macaddr. For more information:

https://blog.engineyard.com/2013/new-in-rails-4

How to use mod operator in bash?

This might be off-topic. But for the wget in for loop, you can certainly do

curl -O http://example.com/search/link[1-600]

Styling Form with Label above Inputs

There is no need to add any extra div wrapper as others suggest.

The simplest way is to wrap your input element inside a related label tag and set input style to display:block.

Bonus point earned: now you don't need to set the labels for attribute. Because every label target the nested input.

<form name="message" method="post">
    <section>
        <label class="left">
            Name
            <input id="name" type="text" name="name">
        </label>
        <label class="right">
            Email
            <input id="email" type="text" name="email">
        </label>
    </section>
</form>

https://jsfiddle.net/Tomanek1/sguh5k17/15/

Comparing two NumPy arrays for equality, element-wise

Now use np.array_equal. From documentation:

np.array_equal([1, 2], [1, 2])
True
np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
np.array_equal([1, 2], [1, 2, 3])
False
np.array_equal([1, 2], [1, 4])
False

Completely removing phpMyAdmin

If your system is using dpkg and apt (debian, ubuntu, etc), try running the following commands in that order (be careful with the sudo rm commands):

sudo apt-get -f install
sudo dpkg -P phpmyadmin  
sudo rm -vf /etc/apache2/conf.d/phpmyadmin.conf
sudo rm -vfR /usr/share/phpmyadmin
sudo service apache2 restart

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

use labelpad parameter:

pl.xlabel("...", labelpad=20)

or set it after:

ax.xaxis.labelpad = 20

What is cardinality in Databases?

A source of confusion may be the use of the word in two different contexts - data modelling and database query optimization.

In data modelling terms, cardinality is how one table relates to another.

  • 1-1 (one row in table A relates to one row in tableB)
  • 1-Many (one row in table A relates to many rows in tableB)
  • Many-Many (Many rows in table A relate to many rows in tableB)

There are also optional participation conditions to the above (where a row in one table doesn't have to relate to the other table at all).

See Wikipedia on Cardinality (data modelling).


When talking about database query optimization, cardinality refers to the data in a column of a table, specifically how many unique values are in it. This statistic helps with planning queries and optimizing the execution plans.

See Wikipedia on Cardinality (SQL statements).

How to Change Font Size in drawString Java

Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);

You can also use TextAttribute.

Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);

g.setFont(myFont);

The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

Pdf.js: rendering a pdf file using a base64 file source instead of url

Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS

_x000D_
_x000D_
        Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
_x000D_
        convertDataURIToBinary: function(dataURI) {_x000D_
          var BASE64_MARKER = ';base64,',_x000D_
            base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
            base64 = dataURI.substring(base64Index),_x000D_
            raw = window.atob(base64),_x000D_
            rawLength = raw.length,_x000D_
            array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
_x000D_
          for (var i = 0; i < rawLength; i++) {_x000D_
            array[i] = raw.charCodeAt(i);_x000D_
          }_x000D_
          return array;_x000D_
        },
_x000D_
_x000D_
_x000D_

Where does the slf4j log file get saved?

The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)

-Dlogging.config={file_location}\log4j2.xml 

or this:

-Dlog4j.configurationFile={file_location}\log4j2.xml

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

HTML/CSS Approach

If you are looking for an option that does not require much JavaScript (and and all the problems that come with it, such as rapid scroll event calls), it is possible to gain the same behavior by adding a wrapper <div> and a couple of styles. I noticed much smoother scrolling (no elements lagging behind) when I used the following approach:

JS Fiddle

HTML

<div id="wrapper">
  <div id="fixed">
    [Fixed Content]
  </div><!-- /fixed -->
  <div id="scroller">
    [Scrolling Content]
  </div><!-- /scroller -->
</div><!-- /wrapper -->

CSS

#wrapper { position: relative; }
#fixed { position: fixed; top: 0; right: 0; }
#scroller { height: 100px; overflow: auto; }

JS

//Compensate for the scrollbar (otherwise #fixed will be positioned over it).
$(function() {
  //Determine the difference in widths between
  //the wrapper and the scroller. This value is
  //the width of the scroll bar (if any).
  var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;

  //Set the right offset
  $('#fixed').css('right', offset + 'px');?
});

Of course, this approach could be modified for scrolling regions that gain/lose content during runtime (which would result in addition/removal of scrollbars).

How to pad a string with leading zeros in Python 3

Since python 3.6 you can use fstring :

>>> length = 1
>>> print(f'length = {length:03}')
length = 001

How to Exit a Method without Exiting the Program?

The basic problem here is that you are mistaking System.Environment.Exit for return.

Styling mat-select in Angular Material

For Angular9+, according to this, you can use:

.mat-select-panel {
    background: red;
    ....
}

Demo


Angular Material uses mat-select-content as class name for the select list content. For its styling I would suggest four options.

1. Use ::ng-deep:

Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

CSS:

::ng-deep .mat-select-content{
    width:2000px;
    background-color: red;
    font-size: 10px;   
}

DEMO


2. Use ViewEncapsulation

... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.

None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:

Typscript:

  import {ViewEncapsulation } from '@angular/core';
  ....
  @Component({
        ....
        encapsulation: ViewEncapsulation.None
 })  

CSS

.mat-select-content{
    width:2000px;
    background-color: red;
    font-size: 10px;
}

DEMO


3. Set class style in style.css

This time you have to 'force' styles with !important too.

style.css

 .mat-select-content{
   width:2000px !important;
   background-color: red !important;
   font-size: 10px !important;
 } 

DEMO


4. Use inline style

<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>

DEMO

Which language uses .pde extension?

Software application written with Arduino, an IDE used for prototyping electronics; contains source code written in the Arduino programming language; enables developers to control the electronics on an Arduino circuit board.

To avoid file association conflicts with the Processing software, Arduino changed the Sketch file extension to .INO with the version 1.0 release. Therefore, while Arduino can still open ".pde" files, the ".ino" file extension should be used instead.

Each PDE file is stored in its own folder when saved from the Processing IDE. It is saved with any other program assets, such as images. The project folder and PDE filename prefix have the same name. When the PDE file is run, it is opened in a Java display window, which renders and runs the resulting program.

Processing is commonly used in educational settings for teaching basic programming skills in a visual environment.

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

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

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

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

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

  • replace the BEFORE functionality;

  • replace the FOR EACH ROW functionality.

My attempt at solving these is below:

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

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

This is how the above works:

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

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

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

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

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

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

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

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

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

Display List in a View MVC

Your action method considers model type asList<string>. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>. You can solve this problem with changing the model in your view to List<string>.

But, the best approach would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you haven't to change model type in your view.

But, in my opinion your models are not correctly implemented. I suggest you to change it as:

public class Team
{
    public int Position { get; set; }
    public string HomeGround {get; set;}
    public string NickName {get; set;}
    public int Founded { get; set; }
    public string Name { get; set; }
}

Then you must change your action method as:

public ActionResult Index()
{
    var model = new List<Team>();

    model.Add(new Team { Name = "MU"});
    model.Add(new Team { Name = "Chelsea"});
    ...

    return View(model);
}

And, your view:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}

GIT commit as different user without email / or only email

It is all dependent on how you commit.

For example:

git commit -am "Some message"

will use your ~\.gitconfig username. In other words, if you open that file you should see a line that looks like this:

[user]
    email = [email protected]

That would be the email you want to change. If your doing a pull request through Bitbucket or Github etc. you would be whoever you're logged in as.

Find the files existing in one directory but not in the other

Another (maybe faster for large directories) approach:

$ find dir1 | sed 's,^[^/]*/,,' | sort > dir1.txt && find dir2 | sed 's,^[^/]*/,,' | sort > dir2.txt
$ diff dir1.txt dir2.txt

The sed command removes the first directory component thanks to Erik`s post)

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

If there is not substantial history on one end (aka if it is just a single readme commit on the github end), I often find it easier to manually copy the readme to my local repo and do a git push -f to make my version the new root commit.

I find it is slightly less complicated, doesn't require remembering an obscure flag, and keeps the history a bit cleaner.

UTF-8 problems while reading CSV file with fgetcsv

Now I got it working (after removing the header command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.

Furthermore, I used SET NAMES 'utf8' for the database. Now it is also correct in the database.

How to increase application heap size in Eclipse?

Find the Run button present on the top of the Eclipse, then select Run Configuration -> Arguments, in VM arguments section just mention the heap size you want to extend as below:

-Xmx1024m

Enable binary mode while restoring a Database from an SQL dump

zcat /path/to/file.sql.gz | mysql -u 'root' -p your_database

How to turn off Wifi via ADB?

adb shell "svc wifi enable"

This worked & it makes action in background without opening related option !!

I want to declare an empty array in java and then I want do update it but the code is not working

So the issue is in your array declaration you are declaring an empty array with the empty curly braces{} instead of an array that allows slots.

Roughly speaking, there can be three types of inputs :

 1. int array[] = null; #Does not point to any memory locations so is a null arrau
 2. int array[] = {) which is sort of equivalent to int array[] = new int[0];
 3. int array[] = new int[n] where n is some number indicating the number of 
memory locations in the array

JPA: How to get entity based on field value other than ID?

Using CrudRepository and JPA query works for me:

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

public interface TokenCrudRepository extends CrudRepository<Token, Integer> {

 /**
 * Finds a token by using the user as a search criteria.
 * @param user
 * @return  A token element matching with the given user.
 */
    @Query("SELECT t FROM Token t WHERE LOWER(t.user) = LOWER(:user)")
    public Token find(@Param("user") String user);

}

and you invoke the find custom method like this:

public void destroyCurrentToken(String user){
    AbstractApplicationContext context = getContext();

    repository = context.getBean(TokenCrudRepository.class);

    Token token = ((TokenCrudRepository) repository).find(user);

    int idToken = token.getId();

    repository.delete(idToken);

    context.close();
}

How to run ssh-add on windows?

One could install Git for Windows and subsequently run ssh-add:

Step 3: Add your key to the ssh-agent

To configure the ssh-agent program to use your SSH key:

If you have GitHub for Windows installed, you can use it to clone repositories and not deal with SSH keys. It also comes with the Git Bash tool, which is the preferred way of running git commands on Windows.

  1. Ensure ssh-agent is enabled:

    • If you are using Git Bash, turn on ssh-agent:

      # start the ssh-agent in the background
      ssh-agent -s
      # Agent pid 59566
      
    • If you are using another terminal prompt, such as msysgit, turn on ssh-agent:

      # start the ssh-agent in the background
      eval $(ssh-agent -s)
      # Agent pid 59566
      
  2. Add your SSH key to the ssh-agent:

    ssh-add ~/.ssh/id_rsa
    

Use tnsnames.ora in Oracle SQL Developer

This helped me:

Posted: 8/12/2011 4:54

Set tnsnames directory tools->Preferences->Database->advanced->Tnsnames Directory

https://forums.oracle.com/forums/thread.jspa?messageID=10020012&#10020012

What's the best way to break from nested loops in JavaScript?

Here are five ways to break out of nested loops in JavaScript:

1) Set parent(s) loop to the end

for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
        {
            i = 5;
            break;
        }
    }
}

2) Use label

exit_loops:
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
            break exit_loops;
    }
}

3) Use variable

var exit_loops = false;
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
        {
            exit_loops = true;
            break;
        }
    }
    if (exit_loops)
        break;
}

4) Use self executing function

(function()
{
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
             if (j === 2)
                 return;
        }
    }
})();

5) Use regular function

function nested_loops()
{
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
             if (j === 2)
                 return;
        }
    }
}
nested_loops();

Git undo local branch delete

You can use git reflog to find the SHA1 of the last commit of the branch. From that point, you can recreate a branch using

git branch branchName <sha1>

Edit: As @seagullJS says, the branch -D command tells you the sha1, so if you haven't closed the terminal yet it becomes real easy. For example this deletes and then immediately restores a branch named master2:

user@MY-PC /C/MyRepo (master)
$ git branch -D master2
Deleted branch master2 (was 130d7ba).    <-- This is the SHA1 we need to restore it!

user@MY-PC /C/MyRepo (master)
$ git branch master2 130d7ba

Table variable error: Must declare the scalar variable "@temp"

You've declared @TEMP but in your insert statement used @temp. Case sensitive variable names.

Change @temp to @TEMP

setting system property

System.setProperty("gate.home", "/some/directory"); 

After that you can retrieve its value later by calling

String value =  System.getProperty("gate.home");

How to run Unix shell script from Java code?

I think with

System.getProperty("os.name"); 

Checking the operating system on can manage the shell/bash scrips if such are supported. if there is need to make the code portable.

ASP.NET GridView RowIndex As CommandArgument

with paging you need to do some calculation

int index = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

jquery append div inside div with id and manipulate

It's just the wrong order

var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$('#box').append(e);    
e.attr('id', 'myid');

Append first and then access/set attr.

Cluster analysis in R: determine the optimal number of clusters

In order to determine optimal k-cluster in clustering methods. I usually using Elbow method accompany by Parallel processing to avoid time-comsuming. This code can sample like this:

Elbow method

elbow.k <- function(mydata){
dist.obj <- dist(mydata)
hclust.obj <- hclust(dist.obj)
css.obj <- css.hclust(dist.obj,hclust.obj)
elbow.obj <- elbow.batch(css.obj)
k <- elbow.obj$k
return(k)
}

Running Elbow parallel

no_cores <- detectCores()
    cl<-makeCluster(no_cores)
    clusterEvalQ(cl, library(GMD))
    clusterExport(cl, list("data.clustering", "data.convert", "elbow.k", "clustering.kmeans"))
 start.time <- Sys.time()
 elbow.k.handle(data.clustering))
 k.clusters <- parSapply(cl, 1, function(x) elbow.k(data.clustering))
    end.time <- Sys.time()
    cat('Time to find k using Elbow method is',(end.time - start.time),'seconds with k value:', k.clusters)

It works well.

Python Set Comprehension

primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}

I simplified the test a bit - if all(x%y instead of if not any(not x%y

I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.

pairs = {(x, x+2) for x in primes if x+2 in primes}

Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.

How to add Class in <li> using wp_nav_menu() in Wordpress?

You can't add a class directly to the LIs very easily, but is there any reason not to target them in a slightly different but equally specific way (by their parent ul)?

You can set the class or ID of the menu with the menu_class and menu_id parameters (affixed to the UL parent of the LIs) and then target the li's via CSS that way, like so:

<?php wp_nav_menu('menu_id=mymenu'); ?>

And for CSS:

ul#mymenu li {
    /* your styles here */
}

Edit: At the time of writing in 2013 this was the easiest way to add it, but updates since then have added the feature to add CSS classes directly in the admin navigation editor. See more recent answers for details.

Git - What is the difference between push.default "matching" and "simple"

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

Adjust UILabel height depending on the text

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cellIdentifier = @"myCell";
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    cell.myUILabel.lineBreakMode = UILineBreakModeWordWrap;        
    cell.myUILabel.numberOfLines = 0;
    cell.myUILabel.text = @"Some very very very very long text....."
    [cell.myUILabel.criterionDescriptionLabel sizeToFit];    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    CGFloat rowHeight = cell.myUILabel.frame.size.height + 10;

    return rowHeight;    
}

Practical uses of git reset --soft?

You can use git reset --soft to change the version you want to have as parent for the changes you have in your index and working tree. The cases where this is useful are rare. Sometimes you might decide that the changes you have in your working tree should belong onto a different branch. Or you can use this as a simple way to collapse several commits into one (similar to squash/fold).

See this answer by VonC for a practical example: Squash the first two commits in Git?

Linux : Search for a Particular word in a List of files under a directory

You can use this command:

grep -rn "string" *

n for showing line number with the filename r for recursive

Convert a row of a data frame to vector

When you extract a single row from a data frame you get a one-row data frame. Convert it to a numeric vector:

as.numeric(df[1,])

As @Roland suggests, unlist(df[1,]) will convert the one-row data frame to a numeric vector without dropping the names. Therefore unname(unlist(df[1,])) is another, slightly more explicit way to get to the same result.

As @Josh comments below, if you have a not-completely-numeric (alphabetic, factor, mixed ...) data frame, you need as.character(df[1,]) instead.

Mongoose: Get full list of users

There was the very easy way to list your data :

server.get('/userlist' , function (req , res) {
 User.find({}).then(function (users) {
 res.send(users);
 });
});

PHP combine two associative arrays into one array

I stumbled upon this question trying to identify a clean way to join two assoc arrays.

I was trying to join two different tables that didn't have relationships to each other.

This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge() +1 to him.

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
        $ResidentialData = $pdo->prepare($sql);
        $ResidentialData->execute(array($lapi));
        $ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
        $CommercialData = $pdo->prepare($sql);
        $CommercialData->execute(array($lapi));
        $CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);

        $Prospects = array_merge($ResidentialProspects,$CommercialProspects);
        echo '<pre>';
        var_dump($Prospects);
        echo '</pre>';

Maybe this will help someone else out.

auto create database in Entity Framework Core

My answer is very similar to Ricardo's answer, but I feel that my approach is a little more straightforward simply because there is so much going on in his using function that I'm not even sure how exactly it works on a lower level.

So for those who want a simple and clean solution that creates a database for you where you know exactly what is happening under the hood, this is for you:

public Startup(IHostingEnvironment env)
{
    using (var client = new TargetsContext())
    {
        client.Database.EnsureCreated();
    }
}

This pretty much means that within the DbContext that you created (in this case, mine is called TargetsContext), you can use an instance of the DbContext to ensure that the tables defined with in the class are created when Startup.cs is run in your application.

How to play or open *.mp3 or *.wav sound file in c++ program?

I would use FMOD to do this for your game. It has the ability to play any file mostly for sounds and is pretty simple to implement in C++. using FMOD and Dir3ect X together can be powerful and not that difficult. If you are familiar with Singleton classes I would create a Singleton class of a sound manager in your win main cpp and then have access to it whenever to load or play new music or sound effects. here's an audio manager example

    #pragma once

#ifndef H_AUDIOMANAGER
#define H_AUDIOMANAGER

#include <string>
#include <Windows.h>
#include "fmod.h"
#include "fmod.hpp"
#include "fmod_codec.h"
#include "fmod_dsp.h"
#include "fmod_errors.h"
#include "fmod_memoryinfo.h"
#include "fmod_output.h"

class AudioManager
{
public:
    // Destructor
    ~AudioManager(void);

    void Initialize(void);  // Initialize sound components
    void Shutdown(void);    // Shutdown sound components

    // Singleton instance manip methods
    static AudioManager* GetInstance(void);
    static void DestroyInstance(void);

    // Accessors
    FMOD::System* GetSystem(void)
        {return soundSystem;}

    // Sound playing
    void Play(FMOD::Sound* sound);  // Play a sound/music with default channel
    void PlaySFX(FMOD::Sound* sound);   // Play a sound effect with custom channel
    void PlayBGM(FMOD::Sound* sound);   // Play background music with custom channel

    // Volume adjustment methods
    void SetBGMVolume(float volume);
    void SetSFXVolume(float volume);

private:
    static AudioManager* instance;  // Singleton instance
    AudioManager(void);  // Constructor

    FMOD::System* soundSystem;  // Sound system object
    FMOD_RESULT result;
    FMOD::Channel* bgmChannel;  // Channel for background music
    static const int numSfxChannels = 4;
    FMOD::Channel* sfxChannels[numSfxChannels]; // Channel for sound effects
};

#endif

SQL - How to find the highest number in a column?

select * from tablename order by ID DESC

that will give you row with id 22

ggplot combining two plots from different data.frames

As Baptiste said, you need to specify the data argument at the geom level. Either

#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) + 
    geom_point() +
    geom_step(data = df2)
)

or

#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) + 
      geom_point(data = df1) +
      geom_step(data = df2)
)

Xml serialization - Hide null values

I prefer creating my own xml with no auto-generated tags. In this I can ignore creating the nodes with null values:

public static string ConvertToXML<T>(T objectToConvert)
    {
        XmlDocument doc = new XmlDocument();
        XmlNode root = doc.CreateNode(XmlNodeType.Element, objectToConvert.GetType().Name, string.Empty);
        doc.AppendChild(root);
        XmlNode childNode;

        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        foreach (PropertyDescriptor prop in properties)
        {
            if (prop.GetValue(objectToConvert) != null)
            {
                childNode = doc.CreateNode(XmlNodeType.Element, prop.Name, string.Empty);
                childNode.InnerText = prop.GetValue(objectToConvert).ToString();
                root.AppendChild(childNode);
            }
        }            

        return doc.OuterXml;
    }

ExpressJS - throw er Unhandled error event

In my case I've had to run vagrant reload as well. Even with no node processes running my express app in my virtual machine I was still getting this error until reloading the vagrant box.

GetElementByID - Multiple IDs

The best way to do it, is to define a function, and pass it a parameter of the ID's name that you want to grab from the DOM, then every time you want to grab an ID and store it inside an array, then you can call the function

<p id="testing">Demo test!</p>

function grabbingId(element){
    var storeId = document.getElementById(element);

    return storeId;
}


grabbingId("testing").syle.color = "red";

How to change the height of a div dynamically based on another div using css?

#container-of-boxes {
    display: table;
    width: 1158px;
}
#box-1 {
    width: 578px;
}
#box-2 {
    width: 386px;
}
#box-3 {
    width: 194px;
}
#box-1, #box-2, #box-3 {
    min-height: 210px;
    padding-bottom: 20px;
    display: table-cell;
    height: auto;
    overflow: hidden;
}
  • The container must have display:table
  • The boxes inside container must be: display:table-cell
  • Don't put floats.

how to draw a rectangle in HTML or CSS?

To mimic the rectangle with fixed position on facebook, try something like this:

<div id="rectangle"></div>

CSS

#rectangle {
    width:100%;
    height:60px;
    background:#00f;
    position:fixed;
    top:0;
    left:0;
}

What is the maximum float in Python?

If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931

>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)

Retrieving subfolders names in S3 bucket from boto3

The following works for me... S3 objects:

s3://bucket/
    form1/
       section11/
          file111
          file112
       section12/
          file121
    form2/
       section21/
          file211
          file112
       section22/
          file221
          file222
          ...
      ...
   ...

Using:

from boto3.session import Session
s3client = session.client('s3')
resp = s3client.list_objects(Bucket=bucket, Prefix='', Delimiter="/")
forms = [x['Prefix'] for x in resp['CommonPrefixes']] 

we get:

form1/
form2/
...

With:

resp = s3client.list_objects(Bucket=bucket, Prefix='form1/', Delimiter="/")
sections = [x['Prefix'] for x in resp['CommonPrefixes']] 

we get:

form1/section11/
form1/section12/

Python strftime - date without leading 0?

Some platforms may support width and precision specification between % and the letter (such as 'd' for day of month), according to http://docs.python.org/library/time.html -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

How to utilize date add function in Google spreadsheet?

Using pretty much the same approach as used by Burnash, for the final result you can use ...

=regexextract(A1,"[0-9]+")+A2

where A1 houses the string with text and number and A2 houses the date of interest

How to reset the state of a Redux store?

My take to keep Redux from referencing to the same variable of the initial state:

// write the default state as a function
const defaultOptionsState = () => ({
  option1: '',
  option2: 42,
});

const initialState = {
  options: defaultOptionsState() // invoke it in your initial state
};

export default (state = initialState, action) => {

  switch (action.type) {

    case RESET_OPTIONS:
    return {
      ...state,
      options: defaultOptionsState() // invoke the default function to reset this part of the state
    };

    default:
    return state;
  }
};

How do you give iframe 100% height

You can do it with CSS:

<iframe style="position: absolute; height: 100%; border: none"></iframe>

Be aware that this will by default place it in the upper-left corner of the page, but I guess that is what you want to achieve. You can position with the left,right, top and bottom CSS properties.

Trying to use fetch and pass in mode: no-cors

So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:

  1. In your Laravel project, run command php artisan make:middleware Cors. This will create app/Http/Middleware/Cors.php for you.
  2. Add the following code inside the handles function in Cors.php:

    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    
  3. In app/Http/kernel.php, add the following entry in $routeMiddleware array:

    ‘cors’ => \App\Http\Middleware\Cors::class
    

    (There would be other entries in the array like auth, guest etc. Also make sure you're doing this in app/Http/kernel.php because there is another kernel.php too in Laravel)

  4. Add this middleware on route registration for all the routes where you want to allow access, like this:

    Route::group(['middleware' => 'cors'], function () {
        Route::get('getData', 'v1\MyController@getData');
        Route::get('getData2', 'v1\MyController@getData2');
    });
    
  5. In Vue front-end, make sure you call this API in mounted() function and not in data(). Also make sure you use http:// or https:// with the URL in your fetch() call.

Full credits to Pete Houston's blog article.

Prevent Default on Form Submit jQuery

$(document).ready(function(){
    $("#form_id").submit(function(){
        return condition;
    });
});

how to compare two elements in jquery

You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.

Assuming:

<div id="a" class="a"></div>

this:

$('div.a')[0] == $('div#a')[0]

returns true.

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

In typescript, if you want to use the node.js package cors

/**
* app.ts
* If you use the cors library
*/

import * as express from "express";
[...]
import * as cors from 'cors';

class App {
   public express: express.Application;

   constructor() {
       this.express = express();
       [..]
       this.handleCORSErrors();
   }

   private handleCORSErrors(): any {
       const corsOptions: cors.CorsOptions = {
           origin: 'http://example.com',
           optionsSuccessStatus: 200
       };
       this.express.use(cors(corsOptions));
   }
}

export default new App().express;

If you don't want to use third part libraries for cors error handling, you need to change the handleCORSErrors() method.

/**
* app.ts
* If you do not use the cors library
*/

import * as express from "express";
[...]

class App {
   public express: express.Application;

   constructor() {
       this.express = express();
       [..]
       this.handleCORSErrors();
   }

   private handleCORSErrors(): any {
       this.express.use((req, res, next) => {
           res.header("Access-Control-Allow-Origin", "*");
           res.header(
               "Access-Control-ALlow-Headers",
               "Origin, X-Requested-With, Content-Type, Accept, Authorization"
           );
           if (req.method === "OPTIONS") {
               res.header(
                   "Access-Control-Allow-Methods",
                   "PUT, POST, PATCH, GET, DELETE"
               );
               return res.status(200).json({});
           } 
           next(); // send the request to the next middleware
       });
    }
}

export default new App().express;

For using the app.ts file

/**
* server.ts
*/
import * as http from "http";
import app from "./app";

const server: http.Server = http.createServer(app);

const PORT: any = process.env.PORT || 3000;
server.listen(PORT);

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

You can use JavaScript as well, in case the textfield is dithered.

WebDriver driver=new FirefoxDriver();
driver.get("http://localhost/login.do");
driver.manage().window().maximize();
RemoteWebDriver r=(RemoteWebDriver) driver;
String s1="document.getElementById('username').value='admin'";
r.executeScript(s1);

Creating an instance using the class name and calling constructor

If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.

// Get Class instance
Class<?> clazz = Class.forName("myPackage.MyClass");

// Get the private constructor.
Constructor<?> cons = clazz.getDeclaredConstructor();

// Since it is private, make it accessible.
cons.setAccessible(true);

// Create new object. 
Object obj = cons.newInstance();

This only works for classes that implement singleton pattern using a private constructor.

ADB - Android - Getting the name of the current activity

dumpsys window windows gives more detail about the current activity:

adb shell "dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'"
  mCurrentFocus=Window{41d2c970 u0 com.android.launcher/com.android.launcher2.Launcher}
  mFocusedApp=AppWindowToken{4203c170 token=Token{41b77280 ActivityRecord{41b77a28 u0 com.android.launcher/com.android.launcher2.Launcher t3}}}

However in order to find the process ID (e.g. to kill the current activity), use dumpsys activity, and grep on "top-activity":

adb shell "dumpsys activity | grep top-activity"
    Proc # 0: fore  F/A/T  trm: 0 3074:com.android.launcher/u0a8 (top-activity)

adb shell "kill 3074"

How do I get the parent directory in Python?

Update from Python 3.4

Use the pathlib module.

from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent)

Old answer

Try this:

import os.path
print os.path.abspath(os.path.join(yourpath, os.pardir))

where yourpath is the path you want the parent for.

How to uncheck checked radio button

You might consider adding an additional radio button to each group labeled 'none' or the like. This can create a consistent user experience without complicating the development process.

How to get on scroll events?

// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {
  ...
}

or

<div (scroll)="onScroll($event)"></div>

How to copy a file to multiple directories using the gnu cp command

If all your target directories match a path expression — like they're all subdirectories of path/to — then just use find in combination with cp like this:

find ./path/to/* -type d -exec cp [file name] {} \;

That's it.

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

There is a difference.

When the ^ character appears outside of [] matches the beginning of the line (or string). When the ^ character appears inside the [], it matches any character not appearing inside the [].

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

add in project root path google-services.json

dependencies {
compile 'com.android.support:support-v4:25.0.1'
**compile 'com.google.firebase:firebase-ads:9.0.2'**
compile files('libs/StartAppInApp-3.5.0.jar')
compile 'com.android.support:multidex:1.0.1'
  }
apply plugin: 'com.google.gms.google-services'

ng-if check if array is empty

post.capabilities.items will still be defined because it's an empty array, if you check post.capabilities.items.length it should work fine because 0 is falsy.

Angular 2 'component' is not a known element

I had the same problem with Angular CLI: 10.1.5 The code works fine, but the error was shown in the VScode v1.50

Resolved by killing the terminal (ng serve) and restarting VScode.

Special characters like @ and & in cURL POST data

cURL > 7.18.0 has an option --data-urlencode which solves this problem. Using this, I can simply send a POST request as

curl -d name=john --data-urlencode passwd=@31&3*J https://www.mysite.com

Skip to next iteration in loop vba

I use Goto

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x

Convert Int to String in Swift

Convert Unicode Int to String

For those who want to convert an Int to a Unicode string, you can do the following:

let myInteger: Int = 97

// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
    return ""
}

// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)

// results
print(myString) // a

Or alternatively:

let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
    let myString = String(myUnicodeScalar)
}