Programs & Examples On #Nstoolbar

NSToolbar and NSToolbarItem provide the mechanism for a titled window to display a toolbar just below its title bar.

How do I select text nodes with jQuery?

For me, plain old .contents() appeared to work to return the text nodes, just have to be careful with your selectors so that you know they will be text nodes.

For example, this wrapped all the text content of the TDs in my table with pre tags and had no problems.

jQuery("#resultTable td").content().wrap("<pre/>")

JPA OneToMany not deleting child

JPA's behaviour is correct (meaning as per the specification): objects aren't deleted simply because you've removed them from a OneToMany collection. There are vendor-specific extensions that do that but native JPA doesn't cater for it.

In part this is because JPA doesn't actually know if it should delete something removed from the collection. In object modeling terms, this is the difference between composition and "aggregation*.

In composition, the child entity has no existence without the parent. A classic example is between House and Room. Delete the House and the Rooms go too.

Aggregation is a looser kind of association and is typified by Course and Student. Delete the Course and the Student still exists (probably in other Courses).

So you need to either use vendor-specific extensions to force this behaviour (if available) or explicitly delete the child AND remove it from the parent's collection.

I'm aware of:

How to copy files from host to Docker container?

My favorite method:

CONTAINERS:

CONTAINER_ID=$(docker ps | grep <string> | awk '{ print $1 }' | xargs docker inspect -f '{{.Id}}')

file.txt

mv -f file.txt /var/lib/docker/devicemapper/mnt/$CONTAINER_ID/rootfs/root/file.txt

or

mv -f file.txt /var/lib/docker/aufs/mnt/$CONTAINER_ID/rootfs/root/file.txt

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

Get filename and path from URI from mediastore

I do this with a one liner:

val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)

Which in the onActivityResult looks like:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGE_PICKER ) {
        data?.data?.let { imgUri: Uri ->
            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imgUri)
        }
    }
}

nodejs mongodb object id to string

Access the property within the object id like that user._id.$oid.

Why does Node.js' fs.readFile() return a buffer instead of string?

The data variable contains a Buffer object. Convert it into ASCII encoding using the following syntax:

data.toString('ascii', 0, data.length)

Asynchronously:

fs.readFile('test.txt', 'utf8', function (error, data) {
    if (error) throw error;
    console.log(data.toString());
});

HTML5 form validation pattern alphanumeric with spaces?

To avoid an input with only spaces, use: "[a-zA-Z0-9]+[a-zA-Z0-9 ]+".

eg: abc | abc aBc | abc 123 AbC 938234

To ensure, for example, that a first AND last name are entered, use a slight variation like

"[a-zA-Z]+[ ][a-zA-Z]+"

eg: abc def

Catching FULL exception message

The following worked well for me

try {
    asdf
} catch {
    $string_err = $_ | Out-String
}

write-host $string_err

The result of this is the following as a string instead of an ErrorRecord object

asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+     asdf
+     ~~~~
    + CategoryInfo          : ObjectNotFound: (asdf:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

How to check if a query string value is present via JavaScript?

I've used this library before which does a pretty good job of what you're after. Specifically:-

qs.contains(name)
    Returns true if the querystring has a parameter name, else false.

    if (qs2.contains("name1")){ alert(qs2.get("name1"));}

How to check if an element is in an array

Here is my little extension I just wrote to check if my delegate array contains a delegate object or not (Swift 2). :) It Also works with value types like a charm.

extension Array
{
    func containsObject(object: Any) -> Bool
    {
        if let anObject: AnyObject = object as? AnyObject
        {
            for obj in self
            {
                if let anObj: AnyObject = obj as? AnyObject
                {
                    if anObj === anObject { return true }
                }
            }
        }
        return false
    }
}

If you have an idea how to optimize this code, than just let me know.

Animate the transition between fragments

Android SDK implementation of FragmentTransaction wants an Animator while support library wants an Animation, don't ask me why but after strangeluk's comment I looked into android 4.0.3 code and support library. Android SDK uses loadAnimator() and support library uses loadAnimation()

How do I decrease the size of my sql server log file?

  1. Ensure the database's backup mode is set to Simple (see here for an overview of the different modes). This will avoid SQL Server waiting for a transaction log backup before reusing space.

  2. Use dbcc shrinkfile or Management Studio to shrink the log files.

Step #2 will do nothing until the backup mode is set.

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

I'm Using the fix, Because Using Knockout in MVC5 views.

On action

return Json(ModelHelper.GetJsonModel<Core_User>(viewModel));

function

   public static TEntity GetJsonModel<TEntity>(TEntity Entity) where TEntity : class
    {
        TEntity Entity_ = Activator.CreateInstance(typeof(TEntity)) as TEntity;
        foreach (var item in Entity.GetType().GetProperties())
        {
            if (item.PropertyType.ToString().IndexOf("Generic.ICollection") == -1 && item.PropertyType.ToString().IndexOf("SaymenCore.DAL.") == -1)
                item.SetValue(Entity_, Entity.GetPropValue(item.Name));
        }
        return Entity_;  
    }

Print page numbers on pages when printing html

   **@page {
            margin-top:21% !important; 
            @top-left{
            content: element(header);

            }

            @bottom-left {
            content: element(footer
 }
 div.header {

            position: running(header);

            }
            div.footer {

            position: running(footer);
            border-bottom: 2px solid black;


            }
           .pagenumber:before {
            content: counter(page);
            }
            .pagecount:before {
            content: counter(pages);
            }      
 <div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
                <span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
            </div >**

"’" showing on page instead of " ' "

This sometimes happens when a string is converted from Windows-1252 to UTF-8 twice.

We had this in a Zend/PHP/MySQL application where characters like that were appearing in the database, probably due to the MySQL connection not specifying the correct character set. We had to:

  1. Ensure Zend and PHP were communicating with the database in UTF-8 (was not by default)

  2. Repair the broken characters with several SQL queries like this...

    UPDATE MyTable SET 
    MyField1 = CONVERT(CAST(CONVERT(MyField1 USING latin1) AS BINARY) USING utf8),
    MyField2 = CONVERT(CAST(CONVERT(MyField2 USING latin1) AS BINARY) USING utf8);
    

    Do this for as many tables/columns as necessary.

You can also fix some of these strings in PHP if necessary. Note that because characters have been encoded twice, we actually need to do a reverse conversion from UTF-8 back to Windows-1252, which confused me at first.

mb_convert_encoding('’', 'Windows-1252', 'UTF-8');    // returns ’

PowerShell - Start-Process and Cmdline Switches

you are going to want to separate your arguments into separate parameter

$msbuild = "C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe"
$arguments = "/v:q /nologo"
start-process $msbuild $arguments 

PowerShell script to return members of multiple security groups

This will give you a list of a single group, and the members of each group.

param
(   
    [Parameter(Mandatory=$true,position=0)]
    [String]$GroupName
)

import-module activedirectory

# optional, add a wild card..
# $groups = $groups + "*"

$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name

ForEach ($Group in $Groups)
   {write-host " "
    write-host "$($group.name)"
    write-host "----------------------------"

    Get-ADGroupMember -identity $($groupname) -recursive | Select-Object samaccountname

 }
write-host "Export Complete"

If you want the friendly name, or other details, add them to the end of the select-object query.

How do you join on the same table, twice, in mysql?

Read this and try, this will help you:

Table1

column11,column12,column13,column14

Table2

column21,column22,column23,column24


SELECT table1.column11,table1.column12,table2asnew1.column21,table2asnew2.column21 
FROM table1 INNER JOIN table2 AS table2asnew1 ON table1.column11=table2asnew1.column21  INNER TABLE table2 as table2asnew2 ON table1.column12=table2asnew2.column22

table2asnew1 is an instance of table 2 which is matched by table1.column11=table2asnew1.column21

and

table2asnew2 is another instance of table 2 which is matched by table1.column12=table2asnew2.column22

Understanding ibeacon distancing

The iBeacon output power is measured (calibrated) at a distance of 1 meter. Let's suppose that this is -59 dBm (just an example). The iBeacon will include this number as part of its LE advertisment.

The listening device (iPhone, etc), will measure the RSSI of the device. Let's suppose, for example, that this is, say, -72 dBm.

Since these numbers are in dBm, the ratio of the power is actually the difference in dB. So:

ratio_dB = txCalibratedPower - RSSI

To convert that into a linear ratio, we use the standard formula for dB:

ratio_linear = 10 ^ (ratio_dB / 10)

If we assume conservation of energy, then the signal strength must fall off as 1/r^2. So:

power = power_at_1_meter / r^2. Solving for r, we get:

r = sqrt(ratio_linear)

In Javascript, the code would look like this:

function getRange(txCalibratedPower, rssi) {
    var ratio_db = txCalibratedPower - rssi;
    var ratio_linear = Math.pow(10, ratio_db / 10);

    var r = Math.sqrt(ratio_linear);
    return r;
}

Note, that, if you're inside a steel building, then perhaps there will be internal reflections that make the signal decay slower than 1/r^2. If the signal passes through a human body (water) then the signal will be attenuated. It's very likely that the antenna doesn't have equal gain in all directions. Metal objects in the room may create strange interference patterns. Etc, etc... YMMV.

"Unknown class <MyClass> in Interface Builder file" error at runtime

In my case, I have XCode6, the specified class .m file end up in the wrong place in build phase - It should have been under Compile Sources, but end up in the Copy Bundle Resources

How to show live preview in a small popup of linked page on mouse over on link?

HTML structure

<div id="app">
<div class="box">
    <div class="title">How to preview link with iframe and javascript?</div>
    <div class="note"><small>Note: Click to every link on content below to preview</small></div>
    <div id="content">
        We'll first attach all the events to all the links for which we want to <a href="https://htmlcssdownload.com/">preview</a> with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.
    </div>
    <h3>Preview the link</h3>
    <div id="result"></div>
</div>

We'll first attach all the events to all the links for which we want to preview with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.

<script type="text/javascript">
(()=>{
    let content = document.getElementById('content');
    let links = content.getElementsByTagName('a');
    for (let index = 0; index < links.length; index++) {
        const element = links[index];
        element.addEventListener('click',(e)=>{
            e.preventDefault();
            openDemoLink(e.target.href);
        })
    }

    function openDemoLink(link){

        let div = document.createElement('div');
        div.classList.add('preview_frame');
        
        let frame = document.createElement('iframe');
        frame.src = link;
        
        let close = document.createElement('a');
        close.classList.add('close-btn');
        close.innerHTML = "Click here to close the example";
        close.addEventListener('click', function(e){
            div.remove();
        })
        
        div.appendChild(frame);
        div.appendChild(close);
        
        document.getElementById('result').appendChild(div);
    }
})()

To see detail at How to live preview link

Truncate number to two decimal places without rounding

Roll your own toFixed function: for positive values Math.floor works fine.

function toFixed(num, fixed) {
    fixed = fixed || 0;
    fixed = Math.pow(10, fixed);
    return Math.floor(num * fixed) / fixed;
}

For negative values Math.floor is round of the values. So you can use Math.ceil instead.

Example,

Math.ceil(-15.778665 * 10000) / 10000 = -15.7786
Math.floor(-15.778665 * 10000) / 10000 = -15.7787 // wrong.

Jquery checking success of ajax post

using jQuery 1.8 and above, should use the following:

var request = $.ajax({
    type: 'POST',
    url: 'mmm.php',
    data: { abc: "abcdefghijklmnopqrstuvwxyz" } })
    .done(function(data) { alert("success"+data.slice(0, 100)); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

check out the docs as @hitautodestruct stated.

Use Font Awesome Icon in Placeholder

You can't add an icon and text because you can't apply a different font to part of a placeholder, however, if you are satisfied with just an icon then it can work. The FontAwesome icons are just characters with a custom font (you can look at the FontAwesome Cheatsheet for the escaped Unicode character in the content rule. In the less source code it's found in variables.less The challenge would be to swap the fonts when the input is not empty. Combine it with jQuery like this.

<form role="form">
  <div class="form-group">
    <input type="text" class="form-control empty" id="iconified" placeholder="&#xF002;"/>
  </div>
</form>

With this CSS:

input.empty {
    font-family: FontAwesome;
    font-style: normal;
    font-weight: normal;
    text-decoration: inherit;
}

And this (simple) jQuery

$('#iconified').on('keyup', function() {
    var input = $(this);
    if(input.val().length === 0) {
        input.addClass('empty');
    } else {
        input.removeClass('empty');
    }
});

The transition between fonts will not be smooth, however.

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

You could not iterate or store more data than the length of your array. In this case you could do like this:

for (int i = 0; i <= name.length - 1; i++) {
    // ....
}

Or this:

for (int i = 0; i < name.length; i++) {
    // ...
}

how to display full stored procedure code?

Normally speaking you'd use a DB manager application like pgAdmin, browse to the object you're interested in, and right click your way to "script as create" or similar.

Are you trying to do this... without a management app?

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Quite a few answers here recommend adding the slf4j-simple dependency to your maven pom file. You might want to check for the most current version.

At https://mvnrepository.com/artifact/org.slf4j/slf4j-simple you'll find the latest version of the SLF4J Simple Binding. Pick the one that suites you best (still 1.7.30 from 2019-12 is the stable version as of 2020-10) and include it to your pom.xml.

For your convenience some dependencies are shown here - but they might not be up-to-date when you read this!

Alpha Version of 2019-10

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>2.0.0-alpha1</version>
 </dependency>

Beta Version of Feb 2019

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.8.0-beta4</version>
</dependency>

Stable Version 2019-12

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>1.7.30</version>
</dependency>

I removed the scope test part thanks to the comment below.

Python Requests and persistent sessions

snippet to retrieve json data, password protected

import requests

username = "my_user_name"
password = "my_super_secret"
url = "https://www.my_base_url.com"
the_page_i_want = "/my_json_data_page"

session = requests.Session()
# retrieve cookie value
resp = session.get(url+'/login')
csrf_token = resp.cookies['csrftoken']
# login, add referer
resp = session.post(url+"/login",
                  data={
                      'username': username,
                      'password': password,
                      'csrfmiddlewaretoken': csrf_token,
                      'next': the_page_i_want,
                  },
                  headers=dict(Referer=url+"/login"))
print(resp.json())

Flutter Countdown Timer

doesnt directly answer your question. But helpful for those who want to start something after some time.

Future.delayed(Duration(seconds: 1), () {
            print('yo hey');
          });

How to make remote REST call inside Node.js? any CURL?

To use latest Async/Await features

https://www.npmjs.com/package/request-promise-native

npm install --save request
npm install --save request-promise-native

//code

async function getData (){
    try{
          var rp = require ('request-promise-native');
          var options = {
          uri:'https://reqres.in/api/users/2',
          json:true
        };

        var response = await rp(options);
        return response;
    }catch(error){
        throw error;
    }        
}

try{
    console.log(getData());
}catch(error){
    console.log(error);
}

Datatable select with multiple conditions

I found that having too many and's would return incorrect results (for .NET 1.1 anyway)

DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz' and D ='fred' and E = 'marg'"); 

In my case A was the 12th field in a table and the select was effectively ignoring it.

However if I did

DataRow[] results = table.Select("A = 'foo' AND (B = 'bar' AND C = 'baz' and D ='fred' and E = 'marg')"); 

The filter worked correctly!

How to merge 2 List<T> and removing duplicate values from it in C#

why not simply eg

var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;

oh ... according to the documentation you can leave out the .Distinct()

This method excludes duplicates from the return set

Importing a csv into mysql via command line

Most answers missing an important point like if you have created csv file exported from Microsoft Excel on windows and importing the same in linux environment, you will get unexpected result.

the correct syntax would be

load data local infile 'file.csv' into table table fields terminated by ',' enclosed by '"' lines terminated by '\r\n'

here the difference is '\r\n' as against simply '\n

Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

SQLDataReader Row Count

This will get you the row count, but will leave the data reader at the end.

dataReader.Cast<object>().Count();

How do I escape ampersands in batch files?

From a cmd:

  • & is escaped like this: ^& (based on @Wael Dalloul's answer)
  • % does not need to be escaped

An example:

start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%20and%20percentage+in+cmd^&sourceid=opera^&ie=utf-8^&oe=utf-8

From a batch file

  • & is escaped like this: ^& (based on @Wael Dalloul's answer)
  • % is escaped like this: %% (based on the OPs update)

An example:

start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%%20and%%20percentage+in+batch+file^&sourceid=opera^&ie=utf-8^&oe=utf-8

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

TL;DR: Use __builtin intrinsics instead; they might happen to help.

I was able to make gcc 4.8.4 (and even 4.7.3 on gcc.godbolt.org) generate optimal code for this by using __builtin_popcountll which uses the same assembly instruction, but gets lucky and happens to make code that doesn't have an unexpectedly long loop-carried dependency because of the false dependency bug.

I am not 100% sure of my benchmarking code, but objdump output seems to share my views. I use some other tricks (++i vs i++) to make the compiler unroll loop for me without any movl instruction (strange behaviour, I must say).

Results:

Count: 20318230000  Elapsed: 0.411156 seconds   Speed: 25.503118 GB/s

Benchmarking code:

#include <stdint.h>
#include <stddef.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

uint64_t builtin_popcnt(const uint64_t* buf, size_t len){
  uint64_t cnt = 0;
  for(size_t i = 0; i < len; ++i){
    cnt += __builtin_popcountll(buf[i]);
  }
  return cnt;
}

int main(int argc, char** argv){
  if(argc != 2){
    printf("Usage: %s <buffer size in MB>\n", argv[0]);
    return -1;
  }
  uint64_t size = atol(argv[1]) << 20;
  uint64_t* buffer = (uint64_t*)malloc((size/8)*sizeof(*buffer));

  // Spoil copy-on-write memory allocation on *nix
  for (size_t i = 0; i < (size / 8); i++) {
    buffer[i] = random();
  }
  uint64_t count = 0;
  clock_t tic = clock();
  for(size_t i = 0; i < 10000; ++i){
    count += builtin_popcnt(buffer, size/8);
  }
  clock_t toc = clock();
  printf("Count: %lu\tElapsed: %f seconds\tSpeed: %f GB/s\n", count, (double)(toc - tic) / CLOCKS_PER_SEC, ((10000.0*size)/(((double)(toc - tic)*1e+9) / CLOCKS_PER_SEC)));
  return 0;
}

Compile options:

gcc --std=gnu99 -mpopcnt -O3 -funroll-loops -march=native bench.c -o bench

GCC version:

gcc (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4

Linux kernel version:

3.19.0-58-generic

CPU information:

processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 70
model name  : Intel(R) Core(TM) i7-4870HQ CPU @ 2.50 GHz
stepping    : 1
microcode   : 0xf
cpu MHz     : 2494.226
cache size  : 6144 KB
physical id : 0
siblings    : 1
core id     : 0
cpu cores   : 1
apicid      : 0
initial apicid  : 0
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx rdtscp lm constant_tsc nopl xtopology nonstop_tsc eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm arat pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid xsaveopt
bugs        :
bogomips    : 4988.45
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

Running AMP (apache mysql php) on Android

Here is the App Bit Web Server (PHP,MySQL,PMA)

It can run a variety of CMS like Wordpress, Joomla, Drupal, Prestashop, etc. Besides CMS can also run PHP frameworks like Code Igniter, YII, CakePHP, etc. It is the same as WAMP or LAMP or XAMPP on your computer or laptop, but this is for android devices with lighttpd instead of apache.

Get only the date in timestamp in mysql

You can use date(t_stamp) to get only the date part from a timestamp.

You can check the date() function in the docs

DATE(expr)

Extracts the date part of the date or datetime expression expr.

mysql> SELECT DATE('2003-12-31 01:02:03'); -> '2003-12-31'

Stop mouse event propagation

This solved my problem, from preventign that an event gets fired by a children:

_x000D_
_x000D_
doSmth(){_x000D_
  // what ever_x000D_
}
_x000D_
        <div (click)="doSmth()">_x000D_
            <div (click)="$event.stopPropagation()">_x000D_
                <my-component></my-component>_x000D_
            </div>_x000D_
        </div>
_x000D_
_x000D_
_x000D_

How do I prevent an Android device from going to sleep programmatically?

If you are a Xamarin user, this is the solution:

   protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle); //always call superclass first

        this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);

        LoadApplication(new App());
    }

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

(Not an answer, but a very similar problem) I have Git Gui installed on a Windows system behind a proxy. Issuing 'git clone' from a Linux virtual machine running on the Windows system works, but Git Gui yields the 443 error mentioned in the heading.

To fix this, one must edit %USERPROFILE%\.gitconfig to add an [http] section:

[http]
    postBuffer = 1000000000
    proxy = the.proxy.address:the.proxy.port
    sslcainfo = C:/Users/username/Documents/the.certificate.name.cer

Note that the path to the security certificate file has had its backslashes ('\') replaced by slashes ('/').

What is a good pattern for using a Global Mutex in C#?

A global Mutex is not only to ensure to have only one instance of an application. I personally prefer using Microsoft.VisualBasic to ensure single instance application like described in What is the correct way to create a single-instance WPF application? (Dale Ragan answer)... I found that's easier to pass arguments received on new application startup to the initial single instance application.

But regarding some previous code in this thread, I would prefer to not create a Mutex each time I want to have a lock on it. It could be fine for a single instance application but in other usage it appears to me has overkill.

That's why I suggest this implementation instead:

Usage:

static MutexGlobal _globalMutex = null;
static MutexGlobal GlobalMutexAccessEMTP
{
    get
    {
        if (_globalMutex == null)
        {
            _globalMutex = new MutexGlobal();
        }
        return _globalMutex;
    }
}

using (GlobalMutexAccessEMTP.GetAwaiter())
{
    ...
}   

Mutex Global Wrapper:

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;

namespace HQ.Util.General.Threading
{
    public class MutexGlobal : IDisposable
    {
        // ************************************************************************
        public string Name { get; private set; }
        internal Mutex Mutex { get; private set; }
        public int DefaultTimeOut { get; set; }
        public Func<int, bool> FuncTimeOutRetry { get; set; }

        // ************************************************************************
        public static MutexGlobal GetApplicationMutex(int defaultTimeOut = Timeout.Infinite)
        {
            return new MutexGlobal(defaultTimeOut, ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value);
        }

        // ************************************************************************
        public MutexGlobal(int defaultTimeOut = Timeout.Infinite, string specificName = null)
        {
            try
            {
                if (string.IsNullOrEmpty(specificName))
                {
                    Name = Guid.NewGuid().ToString();
                }
                else
                {
                    Name = specificName;
                }

                Name = string.Format("Global\\{{{0}}}", Name);

                DefaultTimeOut = defaultTimeOut;

                FuncTimeOutRetry = DefaultFuncTimeOutRetry;

                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);

                Mutex = new Mutex(false, Name, out bool createdNew, securitySettings);

                if (Mutex == null)
                {
                    throw new Exception($"Unable to create mutex: {Name}");
                }
            }
            catch (Exception ex)
            {
                Log.Log.Instance.AddEntry(Log.LogType.LogException, $"Unable to create Mutex: {Name}", ex);
                throw;
            }
        }

        // ************************************************************************
        /// <summary>
        /// 
        /// </summary>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public MutexGlobalAwaiter GetAwaiter(int timeOut)
        {
            return new MutexGlobalAwaiter(this, timeOut);
        }

        // ************************************************************************
        /// <summary>
        /// 
        /// </summary>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public MutexGlobalAwaiter GetAwaiter()
        {
            return new MutexGlobalAwaiter(this, DefaultTimeOut);
        }

        // ************************************************************************
        /// <summary>
        /// This method could either throw any user specific exception or return 
        /// true to retry. Otherwise, retruning false will let the thread continue
        /// and you should verify the state of MutexGlobalAwaiter.HasTimedOut to 
        /// take proper action depending on timeout or not. 
        /// </summary>
        /// <param name="timeOutUsed"></param>
        /// <returns></returns>
        private bool DefaultFuncTimeOutRetry(int timeOutUsed)
        {
            // throw new TimeoutException($"Mutex {Name} timed out {timeOutUsed}.");

            Log.Log.Instance.AddEntry(Log.LogType.LogWarning, $"Mutex {Name} timeout: {timeOutUsed}.");
            return true; // retry
        }

        // ************************************************************************
        public void Dispose()
        {
            if (Mutex != null)
            {
                Mutex.ReleaseMutex();
                Mutex.Close();
            }
        }

        // ************************************************************************

    }
}

Awaiter

using System;

namespace HQ.Util.General.Threading
{
    public class MutexGlobalAwaiter : IDisposable
    {
        MutexGlobal _mutexGlobal = null;

        public bool HasTimedOut { get; set; } = false;

        internal MutexGlobalAwaiter(MutexGlobal mutexEx, int timeOut)
        {
            _mutexGlobal = mutexEx;

            do
            {
                HasTimedOut = !_mutexGlobal.Mutex.WaitOne(timeOut, false);
                if (! HasTimedOut) // Signal received
                {
                    return;
                }
            } while (_mutexGlobal.FuncTimeOutRetry(timeOut));
        }

        #region IDisposable Support
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _mutexGlobal.Mutex.ReleaseMutex();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        // ~MutexExAwaiter()
        // {
        //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        //   Dispose(false);
        // }

        // This code added to correctly implement the disposable pattern.
        public void Dispose()
        {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(true);
            // TODO: uncomment the following line if the finalizer is overridden above.
            // GC.SuppressFinalize(this);
        }
        #endregion
    }
}

how to read value from string.xml in android?

**

I hope this code is beneficial

**

String user = getResources().getString(R.string.muser); 

How to display a json array in table format?

var jArr = [
{
    id : "001",
    name : "apple",
    category : "fruit",
    color : "red"
},
{
    id : "002",
    name : "melon",
    category : "fruit",
    color : "green"
},
{
    id : "003",
    name : "banana",
    category : "fruit",
    color : "yellow"
}
]

var tableData = '<table><tr><td>Id</td><td>Name</td><td>Category</td><td>Color</td></tr>';
$.each(jArr, function(index, data) {
 tableData += '<tr><td>'+data.id+'</td><td>'+data.name+'</td><td>'+data.category+'</td><td>'+data.color+'</td></tr>';
});

$('div').html(tableData);

Merging 2 branches together in GIT

merge is used to bring two (or more) branches together.

a little example:

# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"

# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"

# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"

so now there are three separate branches (namely A B and C) with different heads

to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:

# create an octopus merge
$ git merge B C

your history will then look something like this:

…-o-o-x-------A
      |\     /|
      | B---/ |
       \     /
        C---/

if you want to merge across repository/computer borders, have a look at git pull command, e.g. from the pc with branch A (this example will create two new commits):

# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C

How can I connect to a Tor hidden service using cURL in PHP?

You need to set option CURLOPT_PROXYTYPE to CURLPROXY_SOCKS5_HOSTNAME, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7:

curl_setopt($ch, CURLOPT_PROXYTYPE, 7);

How to draw a path on a map using kml file?

There is now a beta available of Google Maps KML Importing Utility.

It is part of the Google Maps Android API Utility Library. As documented it allows loading KML files from streams

KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());

or local resources

KmlLayer layer = new KmlLayer(getMap(), R.raw.kmlFile, getApplicationContext());

After you have created a KmlLayer, call addLayerToMap() to add the imported data onto the map.

layer.addLayerToMap();

Eclipse : Maven search dependencies doesn't work

Eclipse artifact searching depends on repository's index file. It seems you did not download the index file.

Go to Window -> Prefrences -> Maven and check "Download repository index updates on start". Restart Eclipse and then look at the progress view. An index file should be downloading.

After downloading completely, artifact searching will be ready to use.

Maven Settings

UPDATE You also need to rebuild your Maven repository index in 'maven repository view'.

In this view , open 'Global Repositories', right-click 'central', check 'Full Index Enable', and then, click 'Rebuild Index' in the same menu.

A 66M index file will be downloaded.

Maven Repositories -> Rebuild Index

Getting full URL of action in ASP.NET MVC

As Paddy mentioned: if you use an overload of UrlHelper.Action() that explicitly specifies the protocol to use, the generated URL will be absolute and fully qualified instead of being relative.

I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I suggest to write a custom extension method for the sake of readability:

/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
    string actionName, string controllerName, object routeValues = null)
{
    string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;

    return url.Action(actionName, controllerName, routeValues, scheme);
}

You can then simply use it like that in your view:

@Url.AbsoluteAction("Action", "Controller")

Determine the process pid listening on a certain port

netstat -nlp should tell you the PID of what's listening on which port.

How to get/generate the create statement for an existing hive table?

As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE which "shows the CREATE TABLE statement that creates a given table, or the CREATE VIEW statement that creates a given view."

Usage:

SHOW CREATE TABLE myTable;

Center align a column in twitter bootstrap

With bootstrap 3 the best way to go about achieving what you want is ...with offsetting columns. Please see these examples for more detail:
http://getbootstrap.com/css/#grid-offsetting

In short, and without seeing your divs here's an example what might help, without using any custom classes. Just note how the "col-6" is used and how half of that is 3 ...so the "offset-3" is used. Splitting equally will allow the centered spacing you're going for:

<div class="container">
<div class="col-sm-6 col-sm-offset-3">
your centered, floating column
</div></div>

How to rearrange Pandas column sequence?

Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.

In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]: 
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8

Is there a concurrent List in Java's JDK?

You have these options:

  • Collections.synchronizedList(): you can wrap any List implementation (ArrayList, LinkedList or a 3rd-party list). Access to every method (reading and writing) will be protected using synchronized. When using iterator() or enhanced for loop, you must manually synchronize the whole iteration. While iterating, other threads are fully blocked even from reading. You can also synchronize separately for each hasNext and next calls, but then ConcurrentModificationException is possible.

  • CopyOnWriteArrayList: it's expensive to modify, but wait-free to read. Iterators never throw ConcurrentModificationException, they return a snapshot of the list at the moment of iterator creation even if the list is modified by another thread while iterating. Useful for infrequently updated lists. Bulk operations like addAll are preferred for updates - the internal array is copied less many times.

  • Vector: very much like synchronizedList(new ArrayList<>()), but iteration is synchronized too. However, iterators can throw ConcurrentModificationException if the vector is modified by another thread while iterating.

Other options:

  • Collections.unmodifiableList(): lock-free, thread-safe, but non-modifiable
  • List.of & List.copyOf: Another non-modifiable list in Java 9 and later.
  • Queue or Deque might be an alternative if you only add/remove at the ends of the list and iterate the list. There's no access by index and no adding/removing at arbitrary places. They have multiple concurrent implementations with better performance and better concurrent access, but it's beyond the scope of this question. You can also have a look at JCTools, they contain more performant queue implementations specialized for single consumer or single producer.

Detect if a NumPy array contains at least one non-numeric value?

If infinity is a possible value, I would use numpy.isfinite

numpy.isfinite(myarray).all()

If the above evaluates to True, then myarray contains no, numpy.nan, numpy.inf or -numpy.inf values.

numpy.nan will be OK with numpy.inf values, for example:

In [11]: import numpy as np

In [12]: b = np.array([[4, np.inf],[np.nan, -np.inf]])

In [13]: np.isnan(b)
Out[13]: 
array([[False, False],
       [ True, False]], dtype=bool)

In [14]: np.isfinite(b)
Out[14]: 
array([[ True, False],
       [False, False]], dtype=bool)

What is the best IDE for PHP?

I'm always amazed that more people don't use ActiveState Komodo.

It has the best debugging facilities of any PHP IDE I have tried, is a very mature product and has more useful features than you can shake a stick at. Of note, it has a fantastic HTTP inspector, Javascript debugger and Regular Expression Toolkit. You can get it so that it steps through your PHP, then you see your Javascript running, and then see your HTTP traffic going out over the wire!

It also comes in free (Komodo Edit) and open (OpenKomodo versions).

Oh, and if you don't always hack just on PHP, it's designed as a multi-language editor and rocks for Ruby and Python too.

I've been a happy customer for around 5 years.

View HTTP headers in Google Chrome?

I'm not sure about your exact version, but Chrome has a tab "Network" with several items and when I click on them I can see the headers on the right in a tab.

Press F12 on windows or ??I on a mac to bring up the Chrome developer tools.

Chrome developer tools headers tab

How to run an application as "run as administrator" from the command prompt?

See this TechNet article: Runas command documentation

From a command prompt:

C:\> runas /user:<localmachinename>\administrator cmd

Or, if you're connected to a domain:

C:\> runas /user:<DomainName>\<AdministratorAccountName> cmd

Modulo operator in Python

In addition to the other answers, the fmod documentation has some interesting things to say on the subject:

math.fmod(x, y)

Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

What is lazy loading in Hibernate?

Lazy loading allows you to defer the association retrieval or to have a better control over the fetching strategy.

When you use EAGER loading, you define a global fetch plan which cannot be overridden at query time, meaning you are limited to a decision you took while designing your entity model. The EAGER fetching is a code smell, because the fetching strategy is a query-time policy and it might differ from a business use case to another.

The fetching strategy is a very important aspect, as too much EAGER fetching can cause serious performance related issues.

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

How to use a wildcard in the classpath to add multiple jars?

From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

This should work in Java6, not sure about Java5

(If it seems it does not work as expected, try putting quotes. eg: "foo/*")

Android MediaPlayer Stop and Play

To stop the Media Player without the risk of an Illegal State Exception, you must do

  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }

rather than just

try {
       mp.stop();
       mp.release();
       mp=null;
    } 
catch (Exception e) 
    {
      e.printStackTrace();
    }

PNG transparency issue in IE8

Just want to add (since I googled for this problem, and this question popped first) IE6 and other versions render PNG transparency very ugly. If you have PNG image that is alpha transparent (32bit) and want to show it over some complex background, you can never do this simply in IE. But you can display it correctly over a single colour background as long as you set that PNG images (or divs) CSS attribute background-color to be the same as the parents background-color.

So this will render black where image should be alpha transparent, and transparent where alpha byte is 0:

<div style="background-color: white;">    
    <div style="background-image: url(image.png);"/>    
</div>

And this will render correctly (note the background-color attribute in the inner div):

<div style="background-color: white;">    
    <div style="background-color: white; background-image: url(image.png);"/>    
</div>

Complex alternative to this which enables alpha image over a complex background is to use AlphaImageLoader to load up and render image of the certain opacity. This works until you want to change that opacity... Problem in detail and its solution (javascript) can be found HERE.

How to center an element in the middle of the browser window?

I don't think you can do that. You can be in the middle of the document, however you don't know the toolbar layout or the size of the browser controls. Thus you can center in the document, but not in the middle of the browser window.

SVN "Already Locked Error"

I had the same problem, It was solved when I checked the below checkbox

Kubernetes service external ip pending

I created a single node k8s cluster using kubeadm. When i tried PortForward and kubectl proxy, it showed external IP as pending.

$ kubectl get svc -n argocd argocd-server
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)                      AGE
argocd-server   LoadBalancer   10.107.37.153   <pending>     80:30047/TCP,443:31307/TCP   110s

In my case I've patched the service like this:

kubectl patch svc <svc-name> -n <namespace> -p '{"spec": {"type": "LoadBalancer", "externalIPs":["172.31.71.218"]}}'

After this, it started serving over the public IP

$ kubectl get svc argo-ui -n argo
NAME      TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)        AGE
argo-ui   LoadBalancer   10.103.219.8   172.31.71.218   80:30981/TCP   7m50s

How to overlay one div over another div

The new Grid CSS specification provides a far more elegant solution. Using position: absolute may lead to overlaps or scaling issues while Grid will save you from dirty CSS hacks.

Most minimal Grid Overlay example:

HTML

<div class="container">
  <div class="content">This is the content</div>
  <div class="overlay">Overlay - must be placed under content in the HTML</div>
</div>

CSS

.container {
  display: grid;
}

.content, .overlay {
  grid-area: 1 / 1;
}

That's it. If you don't build for Internet Explorer, your code will most probably work.

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

Reliable way to convert a file to a byte[]

Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:

  1. System.IO.File.ReadAllBytes(filename);
  2. File.Exists(filename)
  3. Path.Combine(folderName, resOfThePath);
  4. Path.GetFullPath(path); // converts a relative path to absolute one
  5. Path.GetExtension(path);

Convert string to int array using LINQ

You can shorten JSprangs solution a bit by using a method group instead:

string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ints = s1.Split(';').Select(int.Parse).ToArray();

How to base64 encode image in linux bash / shell

You need to use cat to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.

test="$(cat DSC_0251.JPG | base64)"

However, base64 can read from the file itself:

test=$( base64 DSC_0251.JPG )

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

How do I create a file at a specific path?

f = open("test.py", "a") Will be created in whatever directory the python file is run from.

I'm not sure about the other error...I don't work in windows.

How to use python numpy.savetxt to write strings and float number to an ASCII file?

You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):

num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s") 

The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.

PHP Fatal Error Failed opening required File

Hey I just had this problem and found that I wasn't looking at the folder location closely enough:

I had

require_once /vagrant/public/liberate/**APP**/vendor/autoload.php

What worked was:

require_once /vagrant/public/liberate/vendor/autoload.php

It was very easy (as a beginner) to overlook this very unnoticeable issue. Yes I do realize that the require issue being logged points directly to the issue at hand, but if you are a beginner, like me, these things can be easily overlooked.

FIX:

Have a good look at the debug of ( __ Dir __ '/etc/etc/etc/file.php') then have your file system open in a different window, and map the two directly. If there is even the slightest difference this require will not work and the above error will be spat out.

Count records for every month in a year

This will give you the count per month for 2012;

SELECT MONTH(ARR_DATE) MONTH, COUNT(*) COUNT
FROM table_emp
WHERE YEAR(arr_date)=2012
GROUP BY MONTH(ARR_DATE);

Demo here.

TCPDF ERROR: Some data has already been output, can't send PDF file

Add the function ob_end_clean(); before call the Output function. It worked for me within a custom Wordpress function!

ob_end_clean();
$pdf->Output($pdf_name, 'I');

C# Double - ToString() formatting with two decimal places but no rounding

I use the following:

double x = Math.Truncate(myDoubleValue * 100) / 100;

For instance:

If the number is 50.947563 and you use the following, the following will happen:

- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94

And there's your answer truncated, now to format the string simply do the following:

string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format

C# : assign data to properties via constructor vs. instantiating

Second approach is object initializer in C#

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

The first approach

var albumData = new Album("Albumius", "Artistus", 2013);

explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:

 var albumData = new Album
        {
            Name = "Albumius",
        };

Object initializer would translate into something like:

var albumData; 
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;

Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.

As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018:

If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

public FileContentResult GetImage(int productId) { 
     Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId); 
     if (prod != null) { 
         return File(prod.ImageData, prod.ImageMimeType); 
      } else { 
         return null; 
     } 
}

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

If you need only one upper case and special character then this should work:

@"^(?=.{8,}$)(?=[^A-Z]*[A-Z][^A-Z]*$)\w*\W\w*$"

Rails find_or_create_by more than one attribute?

For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:

# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
  Model.where(attributes).first || Model.create(attributes)
end

Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

I had this issue occurring with mailto: and tel: links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.

Adding target="_blank", as suggested by this discussion of the issue fixed the problem for me.

Fastest way to ping a network range and return responsive hosts?

This script runs on Git Bash (MINGW64) on Windows and return a messages depending of the ping result.

#!/bin/bash
#$1 should be something like "19.62.55"

if [ -z "$1" ]
  then
    echo "No identify of the network supplied, i.e. 19.62.55"
else
    ipAddress=$1

    for i in {1..256} ;do 
    (
        {
        ping -w 5 $ipAddress.$i ; 
        result=$(echo $?);
        } &> /dev/null


        if [ $result = 0 ]; then
            echo Successful Ping From : $ipAddress.$i
        else
            echo Failed Ping From : $ipAddress.$i
        fi &);
    done

fi

Flattening a shallow list in Python

This solution works for arbitrary nesting depths - not just the "list of lists" depth that some (all?) of the other solutions are limited to:

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

It's the recursion which allows for arbitrary depth nesting - until you hit the maximum recursion depth, of course...

Is it possible to disable the network in iOS Simulator?

You could use OHHTTPStubs and stub the network requests to specific URLs to fail.

How do I deal with installing peer dependencies in Angular CLI?

I found that running the npm install command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.

Specifically, I was trying to use ng2-completer

$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.

I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.

cd foo/foo_app
$ npm install ng2-completer --save

In Angular, how do you determine the active route?

in 2020 if you want to set active class on element which has no [routerLink] - you can do simply:

<a
  (click)="bookmarks()"
  [class.active]="router.isActive('/string/path/'+you+'/need', false)" // <== you need this one. second argument 'false' - exact: true/false
  routerLinkActive="active"
  [routerLinkActiveOptions]="{ exact: true }"
>
  bookmarks
</a>

How do I change the title of the "back" button on a Navigation Bar

in Xcode 4.5 using storyboard, by far the easiest solution i've found when the value of the Back button doesn't have to change dynamically is to use the "Back Button" field associated with the Navigation Item of the View Controller to which you want the "Back" button to say something else.

e.g. in the screenshot below, i want the Back button for the view controller(s) that i push to have "Back" as the title of the Back button.

enter image description here

of course, this won't work if you need the back button to say something slightly different each time … there are all of the other solutions here for that.

Android: How can I pass parameters to AsyncTask's onPreExecute()?

1) For me that's the most simple way passing parameters to async task is like this

// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);

Declare and use the async task like here

private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {

    @Override
    protected Void doInBackground(Boolean...pParams) 
    {
        Boolean param1, param2, param3;

        //

          param1=pParams[0];    
          param2=pParams[1];
          param3=pParams[2];    
      ....
}                           

2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.

 /* Generic Async Task    */
interface MyGenericMethod {
    int execute(String param);
}

protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
    public String mParam;                           // member variable to parameterize the function
    @Override
    protected Void doInBackground(MyGenericMethod... params) {
        //  do something here
        params[0].execute("Myparameter");
        return null;
    }       
}

// to start the asynctask do something like that
public void startAsyncTask()
{
    // 
    AsyncTask<MyGenericMethod, Void, Void>  mytest = new testtask().execute(new MyGenericMethod() {
        public int execute(String param) {
            //body
            return 1;
        }
    });     
}

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

Can someone explain mappedBy in JPA and Hibernate?

You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).

Creating Dynamic button with click event in JavaScript

this:

element.setAttribute("onclick", alert("blabla"));

should be:

element.onclick = function () {
  alert("blabla");
}

Because you call alert instead push alert as string in attribute

How to check if a Unix .tar.gz file is a valid file without uncompressing?

You can also check contents of *.tag.gz file using pigz (parallel gzip) to speedup the archive check:

pigz -cvdp number_of_threads /[...]path[...]/archive_name.tar.gz | tar -tv > /dev/null

Where does MAMP keep its php.ini?

Probably the fastest way to access the PHP.ini for the currently loaded version of PHP in MAMP PRO (v.4.2.1):

  1. Open MAMP Pro
  2. Click on "PHP" under the "Languages" section on the sidebar
  3. Tap on the arrow button right next to the drop-down that lets you select the "Default Version" of PHP.

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

aspx page to redirect to a new page

Even if you don't control the server, you can still see the error messages by adding the following line to the Web.config file in your project (bewlow <system.web>):

<customErrors mode="off" />

Ansible - Save registered variable to file

---
- hosts: all
  tasks:
  - name: Gather Version
    debug:
     msg: "The server Operating system is {{ ansible_distribution }} {{ ansible_distribution_major_version }}"
  - name: Write  Version
    local_action: shell echo "This is  {{ ansible_distribution }} {{ ansible_distribution_major_version }}" >> /tmp/output

Comparing boxed Long values 127 and 128

TL;DR

Java caches boxed Integer instances from -128 to 127. Since you are using == to compare objects references instead of values, only cached objects will match. Either work with long unboxed primitive values or use .equals() to compare your Long objects.

Long (pun intended) version

Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.

Java caches Integer objects instances from the range -128 to 127. That said:

  • If you set to N Long variables the value 127 (cached), the same object instance will be pointed by all references. (N variables, 1 instance)
  • If you set to N Long variables the value 128 (not cached), you will have an object instance pointed by every reference. (N variables, N instances)

That's why this:

Long val1 = 127L;
Long val2 = 127L;

System.out.println(val1 == val2);

Long val3 = 128L;
Long val4 = 128L;

System.out.println(val3 == val4);

Outputs this:

true
false

For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true.

On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false on the comparison between them.

That happens solely because you are comparing two Long object references, not long primitive values, with the == operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with == operator.

Changing these variables to primitive long types will prevent this from happening, but in case you need to keep your code using Long objects, you can safely make these comparisons with the following approaches:

System.out.println(val3.equals(val4));                     // true
System.out.println(val3.longValue() == val4.longValue());  // true
System.out.println((long)val3 == (long)val4);              // true

(Proper null checking is necessary, even for castings)

IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.

Reference links:

How to Check byte array empty or not?

.Net V 4.6 OR C # 6.0

Try This

 if (Attachment?.Length > 0)

Create an enum with string values

There a lot of answers, but I don't see any complete solutions. The problem with the accepted answer, as well as enum { this, one }, is that it disperses the string value you happen to be using through many files. I don't really like the "update" either, it's complex and doesn't leverage types as well. I think Michael Bromley's answer is most correct, but it's interface is a bit of a hassle and could do with a type.

I am using TypeScript 2.0.+ ... Here's what I would do

export type Greeting = "hello" | "world";
export const Greeting : { hello: Greeting , world: Greeting } = {
    hello: "hello",
    world: "world"
};

Then use like this:

let greet: Greeting = Greeting.hello

It also has much nicer type / hover-over information when using a helpful IDE. The draw back is you have to write the strings twice, but at least it's only in two places.

MySQL: How to allow remote connection to mysql

After doing all of above I still couldn't login as root remotely, but Telnetting to port 3306 confirmed that MySQL was accepting connections.

I started looking at the users in MySQL and noticed there were multiple root users with different passwords.

select user, host, password from mysql.user;

So in MySQL I set all the passwords for root again and I could finally log in remotely as root.

use mysql;
update user set password=PASSWORD('NEWPASSWORD') where User='root';
flush privileges;

How to create a Restful web service with input parameters?

You can. Try something like this:

@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
    @PathParam("varY") String varY) {
        Todo todo = new Todo();
        todo.setSummary(varX);
        todo.setDescription(varY);
        return todo;
}

Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

I had a similar problem, trying to add a background image with inline css. No need to specify the images folder due to the way asset sync works.

This worked for me:

background-image: url('/assets/image.jpg');

What is the main difference between Collection and Collections in Java?

Collection is an interface from which other class forms like List, Set are derived. Collections (with "S") is a utility class having static methods to simplify work on collection. Ex : Collections.sort()

Bootstrap 3 - 100% height of custom div inside column

I was just looking for a smiliar issue and I found this:

.div{
  height : 100vh;
}

more info

vw: 1/100th viewport width
vh: 1/100th viewport height
vmin: 1/100th of the smallest side
vmax: 1/100th of the largest side

Visual Studio breakpoints not being hit

It might also be (which was the case for my colleague) that you have disabled automatic loading of symbols for whichever reason.

If so, reenable it by opening Tools -> Options -> Debugging -> Symbols and move the radiobutton to "Load all modules, unless excluded"

enter image description here

Getting data-* attribute for onclick event for an html element

User $() to get jQuery object from your link and data() to get your values

<a id="option1" 
   data-id="10" 
   data-option="21" 
   href="#" 
   onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
       Click to do something
</a>

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

Can enums be subclassed to add new elements?

As an aid to understanding why extending an Enum is not reasonable at the language implementation level to consider what would happen if you passed an instance of the extended Enum to a routine that only understands the base Enum. A switch that the compiler promised had all cases covered would in fact not cover those extended Enum values.

This further emphasizes that Java Enum values are not integers such as C's are, for instances: to use a Java Enum as an array index you must explicitly ask for its ordinal() member, to give a java Enum an arbitrary integer value you must add an explicit field for that and reference that named member.

This is not a comment on the OP's desire, just on why Java ain't never going to do it.

How to find path of active app.config file?

If you mean you are only getting a null return when you use NUnit, then you probably need to copy the ConnectionString value the your app.config of your application to the app.config of your test library.

When it is run by the test loader, the test assembly is loaded at runtime and will look in its own app.config (renamed to testAssembly.dll.config at compile time) rather then your applications config file.

To get the location of the assembly you're running, try

System.Reflection.Assembly.GetExecutingAssembly().Location

How can I make grep print the lines below and above each matching line?

grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after, -1 does the same.

PHP: Return all dates between two dates in an array

function createDateRangeArray($start, $end) {
// Modified by JJ Geewax

$range = array();

if (is_string($start) === true) $start = strtotime($start);
if (is_string($end) === true ) $end = strtotime($end);

if ($start > $end) return createDateRangeArray($end, $start);

do {
$range[] = date('Y-m-d', $start);
$start = strtotime("+ 1 day", $start);
}
while($start < $end);

return $range;
} 

Source: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html

How to set an iframe src attribute from a variable in AngularJS

You need also $sce.trustAsResourceUrl or it won't open the website inside the iframe:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
    $scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
    $scope.changeIt = function () {_x000D_
        $scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
    }_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
    <iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
    <br>_x000D_
    <button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

You can catch that exception and return whatever you want from there.

open(target, 'a').close()
scores = {};
try:
    with open(target, "rb") as file:
        unpickler = pickle.Unpickler(file);
        scores = unpickler.load();
        if not isinstance(scores, dict):
            scores = {};
except EOFError:
    return {}

UIImageView aspect fit and center

In swift language we can set content mode of UIImage view like following as:

let newImgThumb = UIImageView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
newImgThumb.contentMode = .scaleAspectFit

How can I wait for 10 second without locking application UI in android

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

As you have to use WITH (NOLOCK) for each table it might be annoying to write it in every FROM or JOIN clause. However it has a reason why it is called a "dirty" read. So you really should know when you do one, and not set it as default for the session scope. Why?

Forgetting a WITH (NOLOCK) might not affect your program in a very dramatic way, however doing a dirty read where you do not want one can make the difference in certain circumstances.

So use WITH (NOLOCK) if the current data selected is allowed to be incorrect, as it might be rolled back later. This is mostly used when you want to increase performance, and the requirements on your application context allow it to take the risk that inconsistent data is being displayed. However you or someone in charge has to weigh up pros and cons of the decision of using WITH (NOLOCK).

Java, How to add library files in netbeans?

In Netbeans 8.2

1. Dowload the binaries from the web source. The Apache Commos are in: [http://commons.apache.org/components.html][1] In this case, you must select the "Logging" in the Components menu and follow the link to downloads in the Releases part. Direct URL: [http://commons.apache.org/proper/commons-logging/download_logging.cgi][2] For me, the correct download was the file: commons-logging-1.2-bin.zip from the Binaries.

2. Unzip downloaded content. Now, you can see several jar files inside the directory created from the zip file.

3. Add the library to the project. Right click in the project, select Properties and click in Libraries (in the left side). Click the button "Add Jar/Folder". Go to the previously unzipped contents and select the properly jar file. Clic in "Open" and click in"Ok". The library has been loaded!

data.frame rows to a list

I was working on this today for a data.frame (really a data.table) with millions of observations and 35 columns. My goal was to return a list of data.frames (data.tables) each with a single row. That is, I wanted to split each row into a separate data.frame and store these in a list.

Here are two methods I came up with that were roughly 3 times faster than split(dat, seq_len(nrow(dat))) for that data set. Below, I benchmark the three methods on a 7500 row, 5 column data set (iris repeated 50 times).

library(data.table)
library(microbenchmark)

microbenchmark(
split={dat1 <- split(dat, seq_len(nrow(dat)))},
setDF={dat2 <- lapply(seq_len(nrow(dat)),
                  function(i) setDF(lapply(dat, "[", i)))},
attrDT={dat3 <- lapply(seq_len(nrow(dat)),
           function(i) {
             tmp <- lapply(dat, "[", i)
             attr(tmp, "class") <- c("data.table", "data.frame")
             setDF(tmp)
           })},
datList = {datL <- lapply(seq_len(nrow(dat)),
                          function(i) lapply(dat, "[", i))},
times=20
) 

This returns

Unit: milliseconds
       expr      min       lq     mean   median        uq       max neval
      split 861.8126 889.1849 973.5294 943.2288 1041.7206 1250.6150    20
      setDF 459.0577 466.3432 511.2656 482.1943  500.6958  750.6635    20
     attrDT 399.1999 409.6316 461.6454 422.5436  490.5620  717.6355    20
    datList 192.1175 201.9896 241.4726 208.4535  246.4299  411.2097    20

While the differences are not as large as in my previous test, the straight setDF method is significantly faster at all levels of the distribution of runs with max(setDF) < min(split) and the attr method is typically more than twice as fast.

A fourth method is the extreme champion, which is a simple nested lapply, returning a nested list. This method exemplifies the cost of constructing a data.frame from a list. Moreover, all methods I tried with the data.frame function were roughly an order of magnitude slower than the data.table techniques.

data

dat <- vector("list", 50)
for(i in 1:50) dat[[i]] <- iris
dat <- setDF(rbindlist(dat))

Terminating a script in PowerShell

Write-Error is for non-terminating errors and throw is for terminating errors

The Write-Error cmdlet declares a non-terminating error. By default, errors are sent in the error stream to the host program to be displayed, along with output.

Non-terminating errors write an error to the error stream, but they do not stop command processing. If a non-terminating error is declared on one item in a collection of input items, the command continues to process the other items in the collection.

To declare a terminating error, use the Throw keyword. For more information, see about_Throw (http://go.microsoft.com/fwlink/?LinkID=145153).

GitHub "fatal: remote origin already exists"

First do a:

git remote rm origin

then

git remote add origin https://github.com/your_user/your_app.git

and voila! Worked for me!

How can I increment a char?

For me i made the fallowing as a test.

string_1="abcd"

def test(string_1):
   i = 0
   p = ""
   x = len(string_1)
   while i < x:
    y = (string_1)[i]
    i=i+1
    s = chr(ord(y) + 1)
    p=p+s

   print(p)

test(string_1)

What is syntax for selector in CSS for next element?

Not exactly. The h1.hc-reform > p means "any p exactly one level underneath h1.hc-reform".

What you want is h1.hc-reform + p. Of course, that might cause some issues in older versions of Internet Explorer; if you want to make the page compatible with older IEs, you'll be stuck with either adding a class manually to the paragraphs or using some JavaScript (in jQuery, for example, you could do something like $('h1.hc-reform').next('p').addClass('first-paragraph')).

More info: http://www.w3.org/TR/CSS2/selector.html or http://css-tricks.com/child-and-sibling-selectors/

How to make Regular expression into non-greedy?

The non-greedy regex modifiers are like their greedy counter-parts but with a ? immediately following them:

*  - zero or more
*? - zero or more (non-greedy)
+  - one or more
+? - one or more (non-greedy)
?  - zero or one
?? - zero or one (non-greedy)

How to access pandas groupby dataframe by key

I was looking for a way to sample a few members of the GroupBy obj - had to address the posted question to get this done.

create groupby object based on some_key column

grouped = df.groupby('some_key')

pick N dataframes and grab their indices

sampled_df_i  = random.sample(grouped.indices, N)

grab the groups

df_list  = map(lambda df_i: grouped.get_group(df_i), sampled_df_i)

optionally - turn it all back into a single dataframe object

sampled_df = pd.concat(df_list, axis=0, join='outer')

Unknown version of Tomcat was specified in Eclipse

Go to "Window -> preferences -> Server -> Runtime Environments"

Remove the existing servers they might not have downloaded completely.

Add new Server

Query to get only numbers from a string

Just a little modification to @Epsicron 's answer

SELECT SUBSTRING(string, PATINDEX('%[0-9]%', string), PATINDEX('%[0-9][^0-9]%', string + 't') - PATINDEX('%[0-9]%', 
                    string) + 1) AS Number
FROM (values ('003Preliminary Examination Plan'),
    ('Coordination005'),
    ('Balance1000sheet')) as a(string)

no need for a temporary variable

Mac OS X and multiple Java versions

I answer lately and I really recommand you to use SDKMAN instead of Homebrew.

With SDKMAN you can install easily different version of JAVA in your mac and switch from on version to another.

Java in your mac

You can also use SDKMAN for ANT, GRADLE, KOTLIN, MAVEN, SCALA, etc...

To install a version in your mac you can run the command sdk install java 15.0.0.j9-adpt cmd

conflicting types error when compiling c program using gcc

To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.

A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.

How do I use a delimiter with Scanner.useDelimiter in Java?

With Scanner the default delimiters are the whitespace characters.

But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:

  1. Using the Scanner method: useDelimiter(String pattern)
  2. Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.

So useDelimiter() methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:

And here is an Example:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    scan.useDelimiter("/");
    // Printing the tokenized Strings
    while(scan.hasNext()){
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();
}

Prints this output:

Anna Mills
Female
18

Interface/enum listing standard mime-type constants

There's also a MediaType class in androidannotations in case you want to use with android! See here.

How to SSH to a VirtualBox guest externally through a host?

Follow below steps to login to your ubuntu VM running in virtual box from the host machine using putty (Without port forwarding):

  1. On Virtualbox manager select the vm, click on settings icon. Then go Networks and enable two adaptors as below:

    • Adaptor 1 (For internet access): Attached to -> NAT, Advanced -> Check the cable connected.
    • Adaptor 2: Attached to -> Host only adaptor, Advanced -> Check the cable connected and Promiscuous mode -> Allow all.
  2. Start the ubuntu vm.

  3. Login to the VM as root.
  4. Edit the file '/etc/network/interfaces' as below and save it:

    auto lo
    iface lo inet loopback
    
    auto eth0
    iface eth0 inet dhcp
    
    auto eth1
    iface eth1 inet dhcp
    
  5. Restart the VM.

  6. Login to the VM and run below command to check the IP allocated to eth1:

    ifconfig
    
  7. Use this IP to open putty session for the VM.

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

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

You can update the value like following

   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }

Angular JS break ForEach

please use some or every instances of ForEach,

Array.prototype.some:
some is much the same as forEach but it break when the callback returns true

Array.prototype.every:
every is almost identical to some except it's expecting false to break the loop.

Example for some:

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

ary.some(function (value, index, _ary) {
    console.log(index + ": " + value);
    return value === "JavaScript";
});

Example for every:

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

ary.every(function(value, index, _ary) {
    console.log(index + ": " + value);
    return value.indexOf("Script") > -1;
});

Find more information
http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/

How to display custom view in ActionBar?

There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .

The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.

Here're the themes:

styles.xml

 <style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowShowWallpaper">true</item>
  </style>

  <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
  </style>

  <style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
    <item name="android:displayOptions">showCustom</item>
    <item name="android:background">#88000000</item>
  </style>

value-v19/styles.xml

 <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

  <style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:

getSupportActionBar().setDisplayShowCustomEnabled(true);

How to scroll to bottom in react?

Using React.createRef()

class MessageBox extends Component {
        constructor(props) {
            super(props)
            this.boxRef = React.createRef()
        }

        scrollToBottom = () => {
            this.boxRef.current.scrollTop = this.boxRef.current.scrollHeight
        }

        componentDidUpdate = () => {
            this.scrollToBottom()
        }

        render() {
            return (
                        <div ref={this.boxRef}></div>
                    )
        }
}

what is the multicast doing on 224.0.0.251?

If you don't have avahi installed then it's probably cups.

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to solve "Fatal error: Class 'MySQLi' not found"?

If you are on Docker...

Inside php-container RUN:

#docker-php-ext-install mysqli

#apachectl restart

Count textarea characters

textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);

You are calling textareaLengthCheck and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:

textarea.addEventListener("keypress",textareaLengthCheck,false);

Aside from that:

var length = textarea.length;

textarea is the actual textarea, not the value. Try this instead:

var length = textarea.value.length;

Combined with the previous suggestion, your function should be:

function textareaLengthCheck() {
    var length = this.value.length;
    // rest of code
};

java - path to trustStore - set property doesn't work?

Both

-Djavax.net.ssl.trustStore=path/to/trustStore.jks

and

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore in javax.net.ssl.trustStore.

How do I delete an item or object from an array using ng-click?

I disagree that you should be calling a method on your controller. You should be using a service for any actual functionality, and you should be defining directives for any functionality for scalability and modularity, as well as assigning a click event which contains a call to the service which you inject into your directive.

So, for instance, on your HTML...

<a class="btn" ng-remove-birthday="$index">Delete</a>

Then, create a directive...

angular.module('myApp').directive('ngRemoveBirthday', ['myService', function(myService){
    return function(scope, element, attrs){
        angular.element(element.bind('click', function(){
            myService.removeBirthday(scope.$eval(attrs.ngRemoveBirthday), scope);  
        };       
    };
}])

Then in your service...

angular.module('myApp').factory('myService', [function(){
    return {
        removeBirthday: function(birthdayIndex, scope){
            scope.bdays.splice(birthdayIndex);
            scope.$apply();
        }
    };
}]);

When you write your code properly like this, you will make it very easy to write future changes without having to restructure your code. It's organized properly, and you're handling custom click events correctly by binding using custom directives.

For instance, if your client says, "hey, now let's make it call the server and make bread, and then popup a modal." You will be able to easily just go to the service itself without having to add or change any of the HTML, and/or controller method code. If you had just the one line on the controller, you'd eventually need to use a service, for extending the functionality to the heavier lifting the client is asking for.

Also, if you need another 'Delete' button elsewhere, you now have a directive attribute ('ng-remove-birthday') you can easily assign to any element on the page. This now makes it modular and reusable. This will come in handy when dealing with the HEAVY web components paradigm of Angular 2.0. There IS no controller in 2.0. :)

Happy Developing!!!

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

Amazon Linux: apt-get: command not found

You need to manually download the apt deb package. Then run dpkg and it should install.

String.Format not work in TypeScript

You can declare it yourself quite easily:

interface StringConstructor {
    format: (formatString: string, ...replacement: any[]) => string;
}

String.format('','');

This is assuming that String.format is defined elsewhere. e.g. in Microsoft Ajax Toolkit : http://www.asp.net/ajaxlibrary/Reference.String-format-Function.ashx

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

You have to name your struct like that:

typedef struct car_t {

   char

   wheel_t

} car_t;

Git keeps prompting me for a password

I agree with "codehugger" and using the instruction of "orkoden" it worked for me - on NetBeans 7.3 - when you right-click on the file and select context menu - push - a 'push to remote' window opened - there are two options here:

  1. origin:https://github.com/myaccount/myproject.git/

  2. https://github.com/myaccount/myproject.git/

As you can see, the difference is the origin parameter in the URL - you do not want to choose this option (1) you want to check option (2), and that works just fine for me.

Angular 2 Scroll to top on Route Change

If you have server side rendering, you should be careful not to run the code using windows on the server, where that variable doesn't exist. It would result in code breaking.

export class AppComponent implements OnInit {
  routerSubscription: Subscription;

  constructor(private router: Router,
              @Inject(PLATFORM_ID) private platformId: any) {}

  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
      this.routerSubscription = this.router.events
        .filter(event => event instanceof NavigationEnd)
        .subscribe(event => {
          window.scrollTo(0, 0);
        });
    }
  }

  ngOnDestroy() {
    this.routerSubscription.unsubscribe();
  }
}

isPlatformBrowser is a function used to check if the current platform where the app is rendered is a browser or not. We give it the injected platformId.

It it also possible to check for existence of variable windows, to be safe, like this:

if (typeof window != 'undefined')

Difficulty with ng-model, ng-repeat, and inputs

You get into a difficult situation when it is necessary to understand how scopes, ngRepeat and ngModel with NgModelController work. Also try to use 1.0.3 version. Your example will work a little differently.

You can simply use solution provided by jm-

But if you want to deal with the situation more deeply, you have to understand:

  • how AngularJS works;
  • scopes have a hierarchical structure;
  • ngRepeat creates new scope for every element;
  • ngRepeat build cache of items with additional information (hashKey); on each watch call for every new item (that is not in the cache) ngRepeat constructs new scope, DOM element, etc. More detailed description.
  • from 1.0.3 ngModelController rerenders inputs with actual model values.

How your example "Binding to each element directly" works for AngularJS 1.0.3:

  • you enter letter 'f' into input;
  • ngModelController changes model for item scope (names array is not changed) => name == 'Samf', names == ['Sam', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat replaces model value from item scope ('Samf') by value from unchanged names array ('Sam');
  • ngModelController rerenders input with actual model value ('Sam').

How your example "Indexing into the array" works:

  • you enter letter 'f' into input;
  • ngModelController changes item in names array => `names == ['Samf', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat can't find 'Samf' in cache;
  • ngRepeat creates new scope, adds new div element with new input (that is why the input field loses focus - old div with old input is replaced by new div with new input);
  • new values for new DOM elements are rendered.

Also, you can try to use AngularJS Batarang and see how changes $id of the scope of div with input in which you enter.

Remove a folder from git tracking

I came across this question while Googling for "git remove folder from tracking". The OP's question lead me to the answer. I am summarizing it here for future generations.

Question

How do I remove a folder from my git repository without deleting it from my local machine (i.e., development environment)?

Answer

Step 1. Add the folder path to your repo's root .gitignore file.

path_to_your_folder/

Step 2. Remove the folder from your local git tracking, but keep it on your disk.

git rm -r --cached path_to_your_folder/

Step 3. Push your changes to your git repo.

The folder will be considered "deleted" from Git's point of view (i.e. they are in past history, but not in the latest commit, and people pulling from this repo will get the files removed from their trees), but stay on your working directory because you've used --cached.

The value violated the integrity constraints for the column

Teradata table or view stores NULL as "?" and SQL considers it as a character or string. This is the main reason for the error "The value violated the integrity constraints for the column." when data is ported from Teradata source to SQL destination. Solution 1: Allow the destination table to hold NULL Solution 2: Convert the '?' character to be stored as some value in the destination table.

Run CSS3 animation only once (at page loading)

So i just found a solution for that: In the hover animation do this:

animation: hover 1s infinite alternate ease-in-out,splash 1;

Why doesn't importing java.util.* include Arrays and Lists?

Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.

Update


It gives that warning because your the line should actually be

List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();

You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

After adding dependencies open "Gradle" ('View'->Tool Windows->Gradle) tab and hit "refresh"

example of adding (compile 'io.reactivex:rxjava:1.1.0'):

hit refresh

If Idea still can not resolve dependency, hence it is possibly the dependency is not in mavenCentral() repository and you need add repository where this dependency located into repositories{}

Inserting line breaks into PDF

Another solutions (works with TCPDF)

Use HEREDOC for a long string. Put HERDOC for a CONST for example (define different languages)

$_prepare_const_EN = <<<EOT
this is a long string
and new line as well ...
EOT;

$define('STR_EN', $_prepare_const_EN);

$pdf->InsertText(STR_EN);

works for me wery well....

CSS: background image on background color

And if you want Generate a Black Shadow in the background, you can use the following:

background:linear-gradient( rgba(0, 0, 0, 0.5) 100%, rgba(0, 0, 0, 0.5)100%),url("logo/header-background.png");

Safe navigation operator (?.) or (!.) and null property paths

Update:

Planned in the scope of 3.7 release
https://github.com/microsoft/TypeScript/issues/33352


You can try to write a custom function like that.

The main advantage of the approach is a type-checking and partial intellisense.

export function nullSafe<T, 
    K0 extends keyof T, 
    K1 extends keyof T[K0],
    K2 extends keyof T[K0][K1],
    K3 extends keyof T[K0][K1][K2],
    K4 extends keyof T[K0][K1][K2][K3],
    K5 extends keyof T[K0][K1][K2][K3][K4]>
    (obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
    let result: any = obj;

    const keysCount = arguments.length - 1;
    for (var i = 1; i <= keysCount; i++) {
        if (result === null || result === undefined) return result;
        result = result[arguments[i]];
    }

    return result;
}

And usage (supports up to 5 parameters and can be extended):

nullSafe(a, 'b', 'c');

Example on playground.

How do I search for an object by its ObjectId in the mongo console?

To use Objectid method you don't need to import it. It is already on the mongodb object.

_x000D_
_x000D_
var ObjectId = new db.ObjectId('58c85d1b7932a14c7a0a320d');_x000D_
db.yourCollection.findOne({ _id: ObjectId }, function (err, info) {_x000D_
   console.log(info)_x000D_
});_x000D_
               
_x000D_
_x000D_
_x000D_

Declare a dictionary inside a static class

The correct syntax ( as tested in VS 2008 SP1), is this:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic;
     static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

Cannot get to $rootScope

I've found the following "pattern" to be very useful:

MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
function MainCtrl (scope, rootscope, location, thesocket, ...) {

where, MainCtrl is a controller. I am uncomfortable relying on the parameter names of the Controller function doing a one-for-one mimic of the instances for fear that I might change names and muck things up. I much prefer explicitly using $inject for this purpose.

How can I use numpy.correlate to do autocorrelation?

An alternative to numpy.correlate is available in statsmodels.tsa.stattools.acf(). This yields a continuously decreasing autocorrelation function like the one described by OP. Implementing it is fairly simple:

from statsmodels.tsa import stattools
# x = 1-D array
# Yield normalized autocorrelation function of number lags
autocorr = stattools.acf( x )

# Get autocorrelation coefficient at lag = 1
autocorr_coeff = autocorr[1]

The default behavior is to stop at 40 nlags, but this can be adjusted with the nlag= option for your specific application. There is a citation at the bottom of the page for the statistics behind the function.

ORA-12154 could not resolve the connect identifier specified

Use this link.on Microsoft Support

I gave permission to IUSR_MachineName user on oracle home folder and I was able to resolve the problem

How to integrate sourcetree for gitlab

I ended up using GitKraken . I've installed, auth and connected to my repo in 30 seconds.

Get div to take up 100% body height, minus fixed-height header and footer

This question has been pretty well answered, but I'm taking the liberty of adding a javascript solution. Just give the element that you want to 'expand' the id footerspacerdiv, and this javascript snippet will expand that div until the page takes up the full height of the browser window.

It works based on the observation that, when a page is less than the full height of the browser window, document.body.scrollHeight is equal to document.body.clientHeight. The while loop increases the height of footerspacerdiv until document.body.scrollHeight is greater than document.body.clientHeight. At this point, footerspacerdiv will actually be 1 pixel too tall, and the browser will show a vertical scroll bar. So, the last line of the script reduces the height of footerspacerdiv by one pixel to make the page height exactly the height of the browser window.

By placing footerspacerdiv just above the 'footer' of the page, this script can be used to 'push the footer down' to the bottom of the page, so that on short pages, the footer is flush with the bottom of the browser window.

<script>    
//expand footerspacer div so that footer goes to bottom of page on short pages        
  var objSpacerDiv=document.getElementById('footerspacer');          
  var bresize=0;   

  while(document.body.scrollHeight<=document.body.clientHeight) {
    objSpacerDiv.style.height=(objSpacerDiv.clientHeight+1)+"px";
    bresize=1;
  }             
  if(bresize) { objSpacerDiv.style.height=(objSpacerDiv.clientHeight-1)+"px"; }               
 </script>

DateTimePicker: pick both date and time

I'm afraid the DateTimePicker control doesn't have the ability to do those things. It's a pretty basic (and frustrating!) control. Your best option may be to find a third-party control that does what you want.

For the option of typing the date and time manually, you could build a custom component with a TextBox/DateTimePicker combination to accomplish this, and it might work reasonably well, if third-party controls are not an option.

Angular directives - when and how to use compile, controller, pre-link and post-link

What else happens between these function calls?

The various directive functions are executed from within two other angular functions called $compile (where the directive's compile is executed) and an internal function called nodeLinkFn (where the directive's controller, preLink and postLink are executed). Various things happen within the angular function before and after the directive functions are called. Perhaps most notably is the child recursion. The following simplified illustration shows key steps within the compile and link phases:

An illustration showing Angular compile and link phases

To demonstrate the these steps, let's use the following HTML markup:

<div ng-repeat="i in [0,1,2]">
    <my-element>
        <div>Inner content</div>
    </my-element>
</div>

With the following directive:

myApp.directive( 'myElement', function() {
    return {
        restrict:   'EA',
        transclude: true,
        template:   '<div>{{label}}<div ng-transclude></div></div>'
    }
});

Compile

The compile API looks like so:

compile: function compile( tElement, tAttributes ) { ... }

Often the parameters are prefixed with t to signify the elements and attributes provided are those of the source template, rather than that of the instance.

Prior to the call to compile transcluded content (if any) is removed, and the template is applied to the markup. Thus, the element provided to the compile function will look like so:

<my-element>
    <div>
        "{{label}}"
        <div ng-transclude></div>
    </div>
</my-element>

Notice that the transcluded content is not re-inserted at this point.

Following the call to the directive's .compile, Angular will traverse all child elements, including those that may have just been introduced by the directive (the template elements, for instance).

Instance creation

In our case, three instances of the source template above will be created (by ng-repeat). Thus, the following sequence will execute three times, once per instance.

Controller

The controller API involves:

controller: function( $scope, $element, $attrs, $transclude ) { ... }

Entering the link phase, the link function returned via $compile is now provided with a scope.

First, the link function create a child scope (scope: true) or an isolated scope (scope: {...}) if requested.

The controller is then executed, provided with the scope of the instance element.

Pre-link

The pre-link API looks like so:

function preLink( scope, element, attributes, controller ) { ... }

Virtually nothing happens between the call to the directive's .controller and the .preLink function. Angular still provide recommendation as to how each should be used.

Following the .preLink call, the link function will traverse each child element - calling the correct link function and attaching to it the current scope (which serves as the parent scope for child elements).

Post-link

The post-link API is similar to that of the pre-link function:

function postLink( scope, element, attributes, controller ) { ... }

Perhaps worth noticing that once a directive's .postLink function is called, the link process of all its children elements has completed, including all the children's .postLink functions.

This means that by the time .postLink is called, the children are 'live' are ready. This includes:

  • data binding
  • transclusion applied
  • scope attached

The template at this stage will thus look like so:

<my-element>
    <div class="ng-binding">
        "{{label}}"
        <div ng-transclude>                
            <div class="ng-scope">Inner content</div>
        </div>
    </div>
</my-element>

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

If you're using gcc and want to disable the warning for selected code, you can use the #pragma compiler directive:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
( your problematic library includes )
#pragma GCC diagnostic pop

For code you control, you may also use __attribute__((unused)) to instruct the compiler that specific variables are not used.

Close Form Button Event

private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        MessageBox.Show("The application has been closed successfully.", "Application Closed!", MessageBoxButtons.OK);
        System.Windows.Forms.Application.Exit();
    }
    else
    {
        this.Activate();
    }  
}

Hashing a string with Sha256

In the PHP version you can send 'true' in the last parameter, but the default is 'false'. The following algorithm is equivalent to the default PHP's hash function when passing 'sha256' as the first parameter:

public static string GetSha256FromString(string strData)
    {
        var message = Encoding.ASCII.GetBytes(strData);
        SHA256Managed hashString = new SHA256Managed();
        string hex = "";

        var hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }

MySQL root password change

stop all wamp services , exit from wamp.

open notepad then type> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');

then save it to c: drive with any name .. like this "c:/example.txt"

now goto your "wamp" falder wamp > bin > mysql > mysql(your version) > bin in my case path is "C:\wamp\bin\mysql\mysql5.6.17\bin"

now copy your path then run cmd with (ctrl + r) then type "cmd" (enter)

type cd then right click on cmd and paste path (enter) now type (mysqld --init-file=C:\example.txt) without braces then (enter)

then restart PC or open taskmgr and kill mysqld.exe

start wamp and your password will be removed...

How to fix the session_register() deprecated issue?

before PHP 5.3

session_register("name");

since PHP 5.3

$_SESSION['name'] = $name;

String is immutable. What exactly is the meaning?

immutable means you can't not change the value of the same referance.every time you required to create new referance means new memory location. ex:

String str="abc";
str="bcd";

here, in the above code ,in the memory there are 2 blocks for storing the value.the first for value "abc" and second for "bcd".the second value is not replace to first value.

this is call the immutable.

Objective-C and Swift URL encoding

NSString *str = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                             NULL,
                             (CFStringRef)yourString, 
                             NULL, 
                             CFSTR("/:"), 
                             kCFStringEncodingUTF8);

You will need to release or autorelease str yourself.

std::enable_if to conditionally compile a member function

From this post:

Default template arguments are not part of the signature of a template

But one can do something like this:

#include <iostream>

struct Foo {
    template < class T,
               class std::enable_if < !std::is_integral<T>::value, int >::type = 0 >
    void f(const T& value)
    {
        std::cout << "Not int" << std::endl;
    }

    template<class T,
             class std::enable_if<std::is_integral<T>::value, int>::type = 0>
    void f(const T& value)
    {
        std::cout << "Int" << std::endl;
    }
};

int main()
{
    Foo foo;
    foo.f(1);
    foo.f(1.1);

    // Output:
    // Int
    // Not int
}

Can't load IA 32-bit .dll on a AMD 64-bit platform

Had same issue in win64bit and JVM 64bit

Was solved by uploading dll to system32

How to do "If Clicked Else .."

This is all you need: http://api.jquery.com/click/

Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.

pandas GroupBy columns with NaN (missing) values

Ancient topic, if someone still stumbles over this--another workaround is to convert via .astype(str) to string before grouping. That will conserve the NaN's.

df = pd.DataFrame({'a': ['1', '2', '3'], 'b': ['4', np.NaN, '6']})
df['b'] = df['b'].astype(str)
df.groupby(['b']).sum()
    a
b   
4   1
6   3
nan 2

What is the purpose of XSD files?

You mention C# in your question so it may help to think of as XSD as serving a similar role to a C# interface.

It defines what the XML should 'look like' in a similar way that an interface defines what a class should implement.

error: package javax.servlet does not exist

I needed to import javaee-api as well.

  <dependency>
     <groupId>javax</groupId>
     <artifactId>javaee-api</artifactId>
     <version>7.0</version>
  </dependency>

Unless I got following error:

package javax.servlet.http does not exist
javax.servlet.annotation does not exist
javax.servlet.http does not exist
...

Keyboard shortcuts with jQuery

Since this question was originally asked, John Resig (the primary author of jQuery) has forked and improved the js-hotkeys project. His version is available at:

http://github.com/jeresig/jquery.hotkeys

Getting GET "?" variable in laravel

I haven't tested on other Laravel versions but on 5.3-5.8 you reference the query parameter as if it were a member of the Request class.

1. Url

http://example.com/path?page=2

2. In a route callback or controller action using magic method Request::__get()

Route::get('/path', function(Request $request){
 dd($request->page);
}); 

//or in your controller
public function foo(Request $request){
 dd($request->page);
}

//NOTE: If you are wondering where the request instance is coming from, Laravel automatically injects the request instance from the IOC container
//output
"2"

3. Default values

We can also pass in a default value which is returned if a parameter doesn't exist. It's much cleaner than a ternary expression that you'd normally use with the request globals

   //wrong way to do it in Laravel
   $page = isset($_POST['page']) ? $_POST['page'] : 1; 

   //do this instead
   $request->get('page', 1);

   //returns page 1 if there is no page
   //NOTE: This behaves like $_REQUEST array. It looks in both the
   //request body and the query string
   $request->input('page', 1);

4. Using request function

$page = request('page', 1);
//returns page 1 if there is no page parameter in the query  string
//it is the equivalent of
$page = 1; 
if(!empty($_GET['page'])
   $page = $_GET['page'];

The default parameter is optional therefore one can omit it

5. Using Request::query()

While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string

//this is the equivalent of retrieving the parameter
//from the $_GET global array
$page = $request->query('page');

//with a default
$page = $request->query('page', 1);

6. Using the Request facade

$page = Request::get('page');

//with a default value
$page = Request::get('page', 1);

You can read more in the official documentation https://laravel.com/docs/5.8/requests

can you add HTTPS functionality to a python flask web server?

If this webserver is only for testing and demoing purposes. You can use ngrok, a open source too that tunnels your http traffic.

Bascially ngrok creates a public URL (both http and https) and then tunnels the traffic to whatever port your Flask process is running on.

https://ngrok.com/product

It only takes a couple minutes to set up. You first have to download the software. Then run the command
./ngrok http [port number your python process is running on]

It will then open up a window in terminal giving you both an http and https url to access your web app.

How does Google reCAPTCHA v2 work behind the scenes?

Please remember that Google also use reCaptcha together with

Canvas fingerprinting 

to uniquely recognize User/Browsers without cookies!

Inserting values to SQLite table in Android

Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html

An array of List in c#

List<int>[]  a = new List<int>[100];

You still would have to allocate each individual list in the array before you can use it though:

for (int i = 0; i < a.Length; i++)
    a[i] = new List<int>();

Does Python have an argc argument?

In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.

Hadoop cluster setup - java.net.ConnectException: Connection refused

I resolved the same issue by adding this property to hdfs-site.xml

<property>
  <name>fs.default.name</name>
  <value>hdfs://localhost:9000</value>
  </property>

add scroll bar to table body

you can wrap the content of the <tbody> in a scrollable <div> :

html

....
<tbody>
  <tr>
    <td colspan="2">
      <div class="scrollit">
        <table>
          <tr>
            <td>January</td>
            <td>$100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>$80</td>
          </tr>
          <tr>
            <td>January</td>
            <td>$100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>$80</td>
          </tr>
          ...

css

.scrollit {
    overflow:scroll;
    height:100px;
}

see my jsfiddle, forked from yours: http://jsfiddle.net/VTNax/2/

Get selected value from combo box in C# WPF

I use this code, and it works for me:

DataRowView typeItem = (DataRowView)myComboBox.SelectedItem; 
string value = typeItem.Row[0].ToString();

how to set radio button checked in edit mode in MVC razor view

Add checked to both of your radio button. And then show/hide your desired one on document ready.

<div class="form-group">
    <div class="mt-radio-inline" style="padding-left:15px;">
        <label class="mt-radio mt-radio-outline">
            Full Edition
            <input type="radio" value="@((int)SelectEditionTypeEnum.FullEdition)" asp-for="SelectEditionType" checked>
            <span></span>
        </label>
        <label class="mt-radio mt-radio-outline">
            Select Modules
            <input type="radio" value="@((int)SelectEditionTypeEnum.CustomEdition)" asp-for="SelectEditionType" checked>
            <span></span>
        </label>
    </div>
</div>