Programs & Examples On #Intermediate code

Animation fade in and out

You can do this also in kotlin like this:

    contentView.apply {
        // Set the content view to 0% opacity but visible, so that it is visible
        // (but fully transparent) during the animation.
        alpha = 0f
        visibility = View.VISIBLE

        // Animate the content view to 100% opacity, and clear any animation
        // listener set on the view.
        animate()
                .alpha(1f)
                .setDuration(resources.getInteger(android.R.integer.config_mediumAnimTime).toLong())
                .setListener(null)
    }

read more about this in android docs

Typescript: difference between String and string

For quick readers:

Don’t ever use the types Number, String, Boolean, Symbol, or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.

source: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html

IllegalMonitorStateException on wait() call

I know this thread is almost 2 years old but still need to close this since I also came to this Q/A session with same issue...

Please read this definition of illegalMonitorException again and again...

IllegalMonitorException is thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

This line again and again says, IllegalMonitorException comes when one of the 2 situation occurs....

1> wait on an object's monitor without owning the specified monitor.

2> notify other threads waiting on an object's monitor without owning the specified monitor.

Some might have got their answers... who all doesn't, then please check 2 statements....

synchronized (object)

object.wait()

If both object are same... then no illegalMonitorException can come.

Now again read the IllegalMonitorException definition and you wont forget it again...

Parsing domain from a URL

You can pass PHP_URL_HOST into parse_url function as second parameter

$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$host = parse_url($url, PHP_URL_HOST);
print $host; // prints 'google.com'

AttributeError: 'dict' object has no attribute 'predictors'

The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

Android API 21 Toolbar Padding

Here is what I did and it works perfectly on every version of Android.

toolbar.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/primary_color"
    app:theme="@style/ThemeOverlay.AppCompat"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="16dp" <!-- Add margin -->
        android:layout_marginStart="16dp"
        android:gravity="left|center"
        android:text="Toolbar Title" <!-- Your title text -->
        android:textColor="@color/white" <!-- Matches default title styles -->
        android:textSize="20sp"
        android:fontFamily="sans-serif-medium"/>

</android.support.v7.widget.Toolbar>

MyActivity.java (To hide default toolbar title)

getSupportActionBar().setDisplayShowTitleEnabled(false); // Hide default toolbar title

Result with Keylines Shown

enter image description here

passing JSON data to a Spring MVC controller

You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.

In the Controller, you can use the javax.json to convert and manipulate this.

Download and add the .jar to the project libs and import the JsonObject.

To create an json object, you can use

JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();

To read it from String, you can use

JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();

Image overlay on responsive sized images bootstrap

If i understand your question you want to have the overlay just over the image and not cover everything?

I'd set the parent DIV (i renamed in content in the jsfiddle) position to relative, as the overlay should be positioned relative to this div not the window.

.content
{
  position: relative;
}

I did some pocking around and updated your fiddle to just have the overlay sized to the img which (I think) is what you want, let me know anyway :) http://jsfiddle.net/b9Vyw/

Bogus foreign key constraint fail

Cannot delete or update a parent row: a foreign key constraint fails (table1.user_role, CONSTRAINT FK143BF46A8dsfsfds@#5A6BD60 FOREIGN KEY (user_id) REFERENCES user (id))

What i did in two simple steps . first i delete the child row in child table like

mysql> delete from table2 where role_id = 2 && user_id =20;

Query OK, 1 row affected (0.10 sec)

and second step as deleting the parent

delete from table1 where id = 20;

Query OK, 1 row affected (0.12 sec)

By this i solve the Problem which means Delete Child then Delete parent

i Hope You got it. :)

How to change default text color using custom theme?

    <style name="Mytext" parent="@android:style/TextAppearance.Medium"> 
    <item name="android:textSize">20sp</item> 
    <item name="android:textColor">@color/white</item> 
    <item name="android:textStyle">bold</item>
    <item name="android:typeface">sans</item>
</style>

try this one ...

Function Pointers in Java

This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

HTML/JavaScript: Simple form validation on submit

You need to return the validating function. Something like:

onsubmit="return validateForm();"

Then the validating function should return false on errors. If everything is OK return true. Remember that the server has to validate as well.

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Why can't I use Docker CMD multiple times to run multiple services?

Even though CMD is written down in the Dockerfile, it really is runtime information. Just like EXPOSE, but contrary to e.g. RUN and ADD. By this, I mean that you can override it later, in an extending Dockerfile, or simple in your run command, which is what you are experiencing. At all times, there can be only one CMD.

If you want to run multiple services, I indeed would use supervisor. You can make a supervisor configuration file for each service, ADD these in a directory, and run the supervisor with supervisord -c /etc/supervisor to point to a supervisor configuration file which loads all your services and looks like

[supervisord]
nodaemon=true

[include]
files = /etc/supervisor/conf.d/*.conf

If you would like more details, I wrote a blog on this subject here: http://blog.trifork.com/2014/03/11/using-supervisor-with-docker-to-manage-processes-supporting-image-inheritance/

Date Format in Swift

Swift 3 with a Date extension

extension Date {
    func string(with format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}

Then you can use it like so:

let date = Date()
date.string(with: "MMM dd, yyyy")

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[] in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer (expecting Serializable, and using ObjectOutputStream). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.

I guess you can copy the entire package and make use of it.

Updating Anaconda fails: Environment Not Writable Error

I had installed anaconda via the system installer on OS X in the past, which created a ~/.conda/environments.txt owned by root. Conda could not modify this file, hence the error.

To fix this issue, I changed the ownership of that directory and file to my username:

sudo chown -R $USER ~/.conda

Set maxlength in Html Textarea

$(function(){  
  $("#id").keypress(function() {  
    var maxlen = 100;
    if ($(this).val().length > maxlen) {  
      return false;
    }  
  })
});  

How to do HTTP authentication in android?

I've not met that particular package before, but it says it's for client-side HTTP authentication, which I've been able to do on Android using the java.net APIs, like so:

Authenticator.setDefault(new Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("myuser","mypass".toCharArray());
    }});
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setUseCaches(false);
c.connect();

Obviously your getPasswordAuthentication() should probably do something more intelligent than returning a constant.

If you're trying to make a request with a body (e.g. POST) with authentication, beware of Android issue 4326. I've linked a suggested fix to the platform there, but there's a simple workaround if you only want Basic auth: don't bother with Authenticator, and instead do this:

c.setRequestProperty("Authorization", "basic " +
        Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));

Vim: How to insert in visual block mode?

if you want to add new text before or after the selected colum:

  • press ctrl+v
  • select columns
  • press shift+i
  • write your text
  • press esc
  • press "jj"

Correct path for img on React.js

If you used create-react-app to create your project then your public folder is accessible. So you need to add your image folder inside the public folder.

public/images/

<img src="/images/logo.png" />

Cannot read property 'map' of undefined

The error "Cannot read property 'map' of undefined" will be encountered if there is an error in the "this.props.data" or there is no props.data array.

Better put condition to check the the array like

if(this.props.data){
this.props.data.map(........)
.....
}

jQuery or JavaScript auto click

$(document).ready(function(){
   $('.lbOn').click();
});

Suppose this would work too.

Excel 2013 VBA Clear All Filters macro

Try something like this:

Sub ClearDataFilters()
'Clears filters on the activesheet. Will not clear filters if the sheet is protected.
On Error GoTo Protection
If ActiveWorkbook.ActiveSheet.FilterMode Or _
   ActiveWorkbook.ActiveSheet.AutoFilterMode Then _
   ActiveWorkbook.ActiveSheet.ShowAllData

Exit Sub
Protection:
If Err.Number = 1004 And Err.Description = _ 
    "ShowAllData method of Worksheet class failed" Then
    MsgBox "Unable to Clear Filters. This could be due to protection on the sheet.", _
    vbInformation
End If

End Sub

.FilterMode returns true if the worksheet is in filter mode. (See this for more information.)
See this for more information on .AutoFilter.
And finally, this will provide more information about the .ShowAllData method.

Adding new line of data to TextBox

If you use WinForms:

Use the AppendText(myTxt) method on the TextBox instead (.net 3.5+):

    private void button1_Click(object sender, EventArgs e)
    {
        string sent = chatBox.Text;

        displayBox.AppendText(sent);
        displayBox.AppendText(Environment.NewLine);

    }

Text in itself has typically a low memory footprint (you can say a lot within f.ex. 10kb which is "nothing"). The TextBox does not render all text that is in the buffer, only the visible part so you don't need to worry too much about lag. The slower operations are inserting text. Appending text is relatively fast.

If you need a more complex handling of the content you can use StringBuilder combined with the textbox. This will give you a very efficient way of handling text.

CSS hover vs. JavaScript mouseover

One additional benefit to doing it in javascript is you can add / remove the hover effect at different points in time - e.g. hover over table rows changes color, click disables the hover effect and starts edit in place mode.

How can I check if a key exists in a dictionary?

if key in array:
  # do something

Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.

Best method for reading newline delimited files and discarding the newlines?

I use this

def cleaned( aFile ):
    for line in aFile:
        yield line.strip()

Then I can do things like this.

lines = list( cleaned( open("file","r") ) )

Or, I can extend cleaned with extra functions to, for example, drop blank lines or skip comment lines or whatever.

Javamail Could not convert socket to TLS GMail

After a full day of search, I disabled Avast for 10 minutes and Windows Firewall (important) and everything started working!

This was my error:

Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  

Here is how to fix the issue in Avast 19.8.2393 by adding an exclusion to SMTP port 587 (or whichever port your application uses):

  1. Open Avast

  2. Click on 'Settings'

  3. Click on 'Troubleshooting' and then 'Open old settings'

enter image description here

  1. Click again on 'Troubleshooting', scroll down to 'Redirect settings' and delete the port that your app uses.

enter image description here

In my case, I just removed 587 from SMTP ports.

Now I am able to use Avast and also have my Windows Firewall switched on (no need to add additional exclusion for the Firewall).

Here are my application.properties e-mail properties:

###### I am using a Google App Password which I generated in my Gmail Security settings ######
spring.mail.host = smtp.gmail.com
spring.mail.port = 587
spring.mail.protocol = smtp
spring.mail.username = gmail account
spring.mail.password = password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

How to display hexadecimal numbers in C?

You can use the following snippet code:

#include<stdio.h>
int main(int argc, char *argv[]){
    unsigned int i;
    printf("decimal  hexadecimal\n");
    for (i = 0; i <= 256; i+=16)
        printf("%04d     0x%04X\n", i, i);
    return 0;
}

It prints both decimal and hexadecimal numbers in 4 places with zero padding.

Select all from table with Laravel and Eloquent

using DB facade you can perform SQL queries

 public function index()
{
    return DB::table('table_name')->get();
}

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

How to use Redirect in the new react-router-dom of Reactjs

You have to use setState to set a property that will render the <Redirect> inside your render() method.

E.g.

class MyComponent extends React.Component {
  state = {
    redirect: false
  }

  handleSubmit () {
    axios.post(/**/)
      .then(() => this.setState({ redirect: true }));
  }

  render () {
    const { redirect } = this.state;

     if (redirect) {
       return <Redirect to='/somewhere'/>;
     }

     return <RenderYourForm/>;
}

You can also see an example in the official documentation: https://reacttraining.com/react-router/web/example/auth-workflow


That said, I would suggest you to put the API call inside a service or something. Then you could just use the history object to route programatically. This is how the integration with redux works.

But I guess you have your reasons to do it this way.

Dump a mysql database to a plaintext (CSV) backup from the command line

Check out mk-parallel-dump which is part of the ever-useful maatkit suite of tools. This can dump comma-separated files with the --csv option.

This can do your whole db without specifying individual tables, and you can specify groups of tables in a backupset table.

Note that it also dumps table definitions, views and triggers into separate files. In addition providing a complete backup in a more universally accessible form, it also immediately restorable with mk-parallel-restore

How do I change a tab background color when using TabLayout?

You can change the background color of the tab by this attribute

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
style="@style/CategoryTab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
'android:background="@color/primary_color"/>'

I'm getting Key error in python

Let us make it simple if you're using Python 3

mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
    print('c key is present')

If you need else condition

mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
    print('key present')
else:
    print('key not found')

For the dynamic key value, you can also handle through try-exception block

mydict = {'a':'apple','b':'boy','c':'cat'}
try:
    print(mydict['c'])
except KeyError:
    print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}

Why does 'git commit' not save my changes?

I had an issue where I was doing commit --amend even after issuing a git add . and it still wasn't working. Turns out I made some .vimrc customizations and my editor wasn't working correctly. Fixing these errors so that vim returns the correct code resolved the issue.

How to get number of rows using SqlDataReader in C#

I also face a situation when I needed to return a top result but also wanted to get the total rows that where matching the query. i finaly get to this solution:

   public string Format(SelectQuery selectQuery)
    {
      string result;

      if (string.IsNullOrWhiteSpace(selectQuery.WherePart))
      {
        result = string.Format(
@"
declare @maxResult  int;
set @maxResult = {0};

WITH Total AS
(
SELECT count(*) as [Count] FROM {2}
)
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart);
      }
      else
      {
        result = string.Format(
@"
declare @maxResult  int;
set @maxResult = {0};

WITH Total AS
(
SELECT count(*) as [Count] FROM {2} WHERE {3}
)
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2} WHERE {3}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart, selectQuery.WherePart);
      }

      if (!string.IsNullOrWhiteSpace(selectQuery.OrderPart))
        result = string.Format("{0} ORDER BY {1}", result, selectQuery.OrderPart);

      return result;
    }

How to use router.navigateByUrl and router.navigate in Angular

In addition to the provided answer, there are more details to navigate. From the function's comments:

/**
 * Navigate based on the provided array of commands and a starting point.
 * If no starting route is provided, the navigation is absolute.
 *
 * Returns a promise that:
 * - resolves to 'true' when navigation succeeds,
 * - resolves to 'false' when navigation fails,
 * - is rejected when an error happens.
 *
 * ### Usage
 *
 * ```
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
 *
 * // Navigate without updating the URL
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
 * ```
 *
 * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
 * URL.
 */

The Router Guide has more details on programmatic navigation.

jQuery when element becomes visible

Tried this on firefox, works http://jsfiddle.net/Tm26Q/1/

$(function(){
 /** Just to mimic a blinking box on the page**/
  setInterval(function(){$("div#box").hide();},2001);
  setInterval(function(){$("div#box").show();},1000);
 /**/
});

$("div#box").on("DOMAttrModified",
function(){if($(this).is(":visible"))console.log("visible");});

UPDATE

Currently the Mutation Events (like DOMAttrModified used in the solution) are replaced by MutationObserver, You can use that to detect DOM node changes like in the above case.

How to enable loglevel debug on Apache2 server

Do note that on newer Apache versions the RewriteLog and RewriteLogLevel have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):

AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`

Instead, you're now supposed to use the general LogLevel directive, with a level of trace1 up to trace8. 'debug' didn't display any rewrite messages in the log for me.

Example: LogLevel warn rewrite:trace3

For the official documentation, see here.

Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOs) applications?

Ruby, Python, Lua, Scheme, Lisp, Smalltalk, C#, Haskell, ActionScript, JavaScript, Objective-C, C++, C. That's just the ones that pop into my head right now. I'm sure there's hundreds if not thousands of others. (E.g. there's no reason why you couldn't use any .NET language with MonoTouch, i.e. VB.NET, F#, Nemerle, Boo, Cobra, ...)

Also are there plans in the future to expand the amount of programming languages that iOs will support?

Sure. Pretty much every programming language community on this planet is currently working on getting their language to run on iOS.

Also, a lot of people are working on programming languages specifically designed for touch devices such as iPod touch, iPhone and iPad, e.g. Phil Mercurio's Thyrd language.

Getting the IP address of the current machine using Java

This is a working example of the ACCEPTED answer above! This NetIdentity class will store both the internal host ip, as well as the local loopback. If you're on a DNS based server, as mentioned above, you may need to add some more checks, or possible go the Configuration File Route.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Class that allows a device to identify itself on the INTRANET.
 * 
 * @author Decoded4620 2016
 */
public class NetIdentity {

    private String loopbackHost = "";
    private String host = "";

    private String loopbackIp = "";
    private String ip = "";
    public NetIdentity(){

        try{
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

            while(interfaces.hasMoreElements()){
                NetworkInterface i = interfaces.nextElement();
                if(i != null){
                    Enumeration<InetAddress> addresses = i.getInetAddresses();
                    System.out.println(i.getDisplayName());
                    while(addresses.hasMoreElements()){
                        InetAddress address = addresses.nextElement();
                        String hostAddr = address.getHostAddress();

                        // local loopback
                        if(hostAddr.indexOf("127.") == 0 ){
                            this.loopbackIp = address.getHostAddress();
                            this.loopbackHost = address.getHostName();
                        }

                        // internal ip addresses (behind this router)
                        if( hostAddr.indexOf("192.168") == 0 || 
                                hostAddr.indexOf("10.") == 0 || 
                                hostAddr.indexOf("172.16") == 0 ){
                            this.host = address.getHostName();
                            this.ip = address.getHostAddress();
                        }


                        System.out.println("\t\t-" + address.getHostName() + ":" + address.getHostAddress() + " - "+ address.getAddress());
                    }
                }
            }
        }
        catch(SocketException e){

        }
        try{
            InetAddress loopbackIpAddress = InetAddress.getLocalHost();
            this.loopbackIp = loopbackIpAddress.getHostName();
            System.out.println("LOCALHOST: " + loopbackIp);
        }
        catch(UnknownHostException e){
            System.err.println("ERR: " + e.toString());
        }
    }

    public String getLoopbackHost(){
        return loopbackHost;
    }

    public String getHost(){
        return host;
    }
    public String getIp(){
        return ip;
    }
    public String getLoopbackIp(){
        return loopbackIp;
    }
}

When I run this code I actually get a print out like this:

    Software Loopback Interface 1
        -127.0.0.1:127.0.0.1 - [B@19e1023e
        -0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
        -VIKING.yourisp.com:192.168.1.142 - [B@64b8f8f4
        -fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
Intel Edison USB RNDIS Device
Driver for user-mode network applications
Cisco Systems VPN Adapter for 64-bit Windows
VirtualBox Host-Only Ethernet Adapter
        -VIKING:192.168.56.1 - [B@3cd1f1c8
        -VIKING:fe80:0:0:0:d599:3cf0:5462:cb7%eth4 - [B@3a4afd8d
LogMeIn Hamachi Virtual Ethernet Adapter
        -VIKING:25.113.118.39 - [B@1996cd68
        -VIKING:2620:9b:0:0:0:0:1971:7627 - [B@3339ad8e
        -VIKING:fe80:0:0:0:51bf:994d:4656:8486%eth5 - [B@555590
Bluetooth Device (Personal Area Network)
        -fe80:0:0:0:4c56:8009:2bca:e16b%eth6:fe80:0:0:0:4c56:8009:2bca:e16b%eth6 - [B@3c679bde
Bluetooth Device (RFCOMM Protocol TDI)
Intel(R) Ethernet Connection (2) I218-V
        -fe80:0:0:0:4093:d169:536c:7c7c%eth7:fe80:0:0:0:4093:d169:536c:7c7c%eth7 - [B@16b4a017
Microsoft Wi-Fi Direct Virtual Adapter
        -fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1:fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1 - [B@8807e25
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0000
VirtualBox Host-Only Ethernet Adapter-WFP Native MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0001
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0002
VirtualBox Host-Only Ethernet Adapter-VirtualBox NDIS Light-Weight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0003
VirtualBox Host-Only Ethernet Adapter-QoS Packet Scheduler-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0004
VirtualBox Host-Only Ethernet Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0000
Intel(R) Ethernet Connection (2) I218-V-WFP Native MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0001
Intel(R) Ethernet Connection (2) I218-V-Shrew Soft Lightweight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0002
Intel(R) Ethernet Connection (2) I218-V-VirtualBox NDIS Light-Weight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0003
Intel(R) Ethernet Connection (2) I218-V-QoS Packet Scheduler-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0004
Intel(R) Ethernet Connection (2) I218-V-WFP 802.3 MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-WFP Native MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-Virtual WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-Native WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Broadcom 802.11ac Network Adapter-Shrew Soft Lightweight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Broadcom 802.11ac Network Adapter-VirtualBox NDIS Light-Weight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-QoS Packet Scheduler-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0006
Broadcom 802.11ac Network Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0007
Microsoft Wi-Fi Direct Virtual Adapter-WFP Native MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-Native WiFi Filter Driver-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0002
Microsoft Wi-Fi Direct Virtual Adapter-Shrew Soft Lightweight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Microsoft Wi-Fi Direct Virtual Adapter-VirtualBox NDIS Light-Weight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0006

For my use I'm setting up a Upnp Server, it helped to understand the 'pattern' that i was looking for. Some of the objects returned are Ethernet Adapters, Network Adapters, Virtual Network Adapters, Drivers, and VPN Client Adapters. Not everything has an Address either. So you'll want to skip out on interface objects that don't.

You can also add this to the loop for the current NetworkInterface i

while(interfaces.hasMoreElements()){
    Enumeration<InetAddress> addresses = i.getInetAddresses();
    System.out.println(i.getDisplayName());
    System.out.println("\t- name:" + i.getName());
    System.out.println("\t- idx:" + i.getIndex());
    System.out.println("\t- max trans unit (MTU):" + i.getMTU());
    System.out.println("\t- is loopback:" + i.isLoopback());
    System.out.println("\t- is PPP:" + i.isPointToPoint());
    System.out.println("\t- isUp:" + i.isUp());
    System.out.println("\t- isVirtual:" + i.isVirtual());
    System.out.println("\t- supportsMulticast:" + i.supportsMulticast());
}

And You'll see information in your output much like this:

Software Loopback Interface 1
    - name:lo
    - idx:1
    - max trans unit (MTU):-1
    - is loopback:true
    - is PPP:false
    - isUp:true
    - isVirtual:false
    - supportsMulticast:true
        -ADRESS: [127.0.0.1(VIKING-192.168.56.1)]127.0.0.1:127.0.0.1 - [B@19e1023e
        -ADRESS: [0:0:0:0:0:0:0:1(VIKING-192.168.56.1)]0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
    - name:wlan0
    - idx:2
    - max trans unit (MTU):1500
    - is loopback:false
    - is PPP:false
    - isUp:true
    - isVirtual:false
    - supportsMulticast:true
        -ADRESS: [VIKING.monkeybrains.net(VIKING-192.168.56.1)]VIKING.monkeybrains.net:192.168.1.142 - [B@64b8f8f4
        -ADRESS: [fe80:0:0:0:81fa:31d:21c9:85cd%wlan0(VIKING-192.168.56.1)]fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
    - name:eth0
    - idx:3
    - max trans unit (MTU):-1
    - is loopback:false
    - is PPP:false
    - isUp:false
    - isVirtual:false
    - supportsMulticast:true

find files by extension, *.html under a folder in nodejs

Old post but ES6 now handles this out of the box with the includes method.

let files = ['file.json', 'other.js'];

let jsonFiles = files.filter(file => file.includes('.json'));

console.log("Files: ", jsonFiles) ==> //file.json

How can I check if a string contains a character in C#?

You can use the IndexOf method, which has a suitable overload for string comparison types:

if (def.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0) ...

Also, you would not need the == true, since an if statement only expects an expression that evaluates to a bool.

How to call VS Code Editor from terminal / command line

This works for Windows:

CMD> start vscode://file/o:/git/libzmq/builds/msvc/vs2017/libzmq.sln

But if the filepath has spaces, normally one would add double quotes around it, like this:

CMD> start "vscode://file/o:/git/lib zmq/builds/msvc/vs2017/libzmq.sln"

But this messes up with start, which can take a double-quoted title, so it will create a window with this name as the title and not open the project.

CMD> start "title" "vscode://file/o:/git/lib zmq/builds/msvc/vs2017/libzmq.sln"

Why does Java have transient fields?

Because not all variables are of a serializable nature

CSV parsing in Java - working example..?

i had to use a csv parser about 5 years ago. seems there are at least two csv standards: http://en.wikipedia.org/wiki/Comma-separated_values and what microsoft does in excel.

i found this libaray which eats both: http://ostermiller.org/utils/CSV.html, but afaik, it has no way of inferring what data type the columns were.

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

You could add the following VBA code to your sheet:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") > 0.5 Then
        MsgBox "Discount too high"
    End If
End Sub

Every time a cell is changed on the sheet, it will check the value of cell A1.

Notes:

  • if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
  • the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.

Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):

  • Pros: his method will work if A1's value is linked to cells located in other sheets.
  • Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.

Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

To extend one of the answers, also subarrays of multidimensional arrays are passed by value unless passed explicitely by reference.

<?php
$foo = array( array(1,2,3), 22, 33);

function hello($fooarg) {
  $fooarg[0][0] = 99;
}

function world(&$fooarg) {
  $fooarg[0][0] = 66;
}

hello($foo);
var_dump($foo); // (original array not modified) array passed-by-value

world($foo);
var_dump($foo); // (original array modified) array passed-by-reference

The result is:

array(3) {
  [0]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  [1]=>
  int(22)
  [2]=>
  int(33)
}
array(3) {
  [0]=>
  array(3) {
    [0]=>
    int(66)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  [1]=>
  int(22)
  [2]=>
  int(33)
}

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

How to calculate the SVG Path for an arc (of a circle)

ReactJS component based on the selected answer:

import React from 'react';

const polarToCartesian = (centerX, centerY, radius, angleInDegrees) => {
    const angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;

    return {
        x: centerX + (radius * Math.cos(angleInRadians)),
        y: centerY + (radius * Math.sin(angleInRadians))
    };
};

const describeSlice = (x, y, radius, startAngle, endAngle) => {

    const start = polarToCartesian(x, y, radius, endAngle);
    const end = polarToCartesian(x, y, radius, startAngle);

    const largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

    const d = [
        "M", 0, 0, start.x, start.y,
        "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
    ].join(" ");

    return d;
};

const path = (degrees = 90, radius = 10) => {
    return describeSlice(0, 0, radius, 0, degrees) + 'Z';
};

export const Arc = (props) => <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300">
    <g transform="translate(150,150)" stroke="#000" strokeWidth="2">
        <path d={path(props.degrees, props.radius)} fill="#333"/>
    </g>

</svg>;

export default Arc;

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

Implement toString() on the class.

I recommend the Apache Commons ToStringBuilder to make this easier. With it, you just have to write this sort of method:

public String toString() {
     return new ToStringBuilder(this).
       append("name", name).
       append("age", age).
       toString(); 
}

In order to get this sort of output:

Person@7f54[name=Stephen,age=29]

There is also a reflective implementation.

What does the [Flags] Enum Attribute mean in C#?

In extension to the accepted answer, in C#7 the enum flags can be written using binary literals:

[Flags]
public enum MyColors
{
    None   = 0b0000,
    Yellow = 0b0001,
    Green  = 0b0010,
    Red    = 0b0100,
    Blue   = 0b1000
}

I think this representation makes it clear how the flags work under the covers.

Is there a way to get version from package.json in nodejs code?

I made a useful code to get the parent module's package.json

function loadParentPackageJson() {
    if (!module.parent || !module.parent.filename) return null
    let dir = path.dirname(module.parent.filename)
    let maxDepth = 5
    let packageJson = null
    while (maxDepth > 0) {
        const packageJsonPath = `${dir}/package.json`
        const exists = existsSync(packageJsonPath)
        if (exists) {
            packageJson = require(packageJsonPath)
            break
        }
        dir = path.resolve(dir, '../')
        maxDepth--
    }
    return packageJson
}

Concatenate text files with Windows command line, dropping leading lines

You can also simply try this

type file2.txt >> file1.txt

It will append the content of file2.txt at the end of file1.txt

If you need original file1.txt, take a backup beforehand. Or you can do this

type file1.txt > out.txt
type file2.txt >> out.txt

If you want to have a line break at the end of the first file, you can try the following command before appending.

type file1.txt > out.txt
printf "\n" >> out.txt
type file2.txt >> out.txt

How to add chmod permissions to file in Git?

According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index sub-command.

To set the flag, use following command:

git update-index --chmod=+x path/to/file

To remove it, use:

git update-index --chmod=-x path/to/file

Under the hood

While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:

  • 100644 for regular files
  • 100755 for executable ones

You can visualize it using ls-file subcommand, with --stage option:

$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0       .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0       my_executable_script.sh

By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode option to false:

git config core.fileMode false

Troubleshooting

If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:

git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file

Bonus

Starting with Git 2.9, you can stage a file AND set the flag in one command:

git add --chmod=+x path/to/file

Git Bash: Could not open a connection to your authentication agent

I checked all the solutions on this post and the post that @kenorb referenced above, and I did not find any solution that worked for me.

I am using Git 1.9.5 Preview on Windows 7 with the following configuration: - Run Git from the Windows Command Prompt - Checkout Windows-style, commit Unix-style line endings

I used the 'Git Bash' console for everything... And all was well until I tried to install the SSH keys. GitHub's documentation says to do the following (don't run these commands until you finish reading the post):

Ensure ssh-agent is enabled:

If you are using Git Bash, turn on ssh-agent:
# start the ssh-agent in the background
ssh-agent -s
# Agent pid 59566
If you are using another terminal prompt, such as msysgit, turn on ssh-agent:
# start the ssh-agent in the background
eval $(ssh-agent -s)
# Agent pid 59566

Now of course I missed the fact that you were supposed to do one or the other. So, I ran these commands multiple times because the later ssh-add command was failing, so I returned to this step, and continued to retry over and over.

This results in 1 Windows 'ssh-agent' process being created every single time you run these commands (notice the new PID every time you enter those commands?)

So, Ctrl+Alt+Del and hit End Process to stop each 'ssh-agent.exe' process.

Now that all the messed up stuff from the failed attempts is cleaned up, I will tell you how to get it working...

In 'Git Bash':

Start the 'ssh-agent.exe' process

eval $(ssh-agent -s)

And install the SSH keys

ssh-add "C:\Users\MyName\.ssh\id_rsa"

* Adjust the path above with your username, and make sure that the location of the* /.ssh directory is in the correct place. I think you choose this location during the Git installation? Maybe not...

The part I was doing wrong before I figured this out was I was not using quotes around the 'ssh-add' location. The above is how it needs to be entered on Windows.

How to set image in imageview in android?

        ImageView iv= (ImageView)findViewById(R.id.img_selected_image);
        public static int getDrawable(Context context, String name)//method to get id
        {
         Assert.assertNotNull(context);
         Assert.assertNotNull(name);
        return context.getResources().getIdentifier(name,    //return id
            "your drawable", context.getPackageName());
        }
        image.setImageResource(int Id);//set id using this method

How do I get this javascript to run every second?

window.setTimeout(func,1000);

This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.

Reference

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

For me none of the solutions here solved it. Frustrated, I restarted my Macbook's iTerm terminal, and voila! My github authorization started working again.

Weird, but maybe iTerm has its own way of handling SSH authorizations or that my terminal session wasn't authorized somehow.

How to check if a Constraint exists in Sql server?

INFORMATION_SCHEMA is your friend. It has all kinds of views that show all kinds of schema information. Check your system views. You will find you have three views dealing with constraints, one being CHECK_CONSTRAINTS.

How to render an array of objects in React?

You can do it in two ways:

First:

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);

    return (
      <div>
      {listItems }
      </div>
    );
  }

Second: Directly write the map function in the return

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    return (
      <div>
      {data.map(function(d, idx){
         return (<li key={idx}>{d.name}</li>)
       })}
      </div>
    );
  }

How can I return the current action in an ASP.NET MVC view?

I vote for this 2:

string currentActionName = ViewContext.RouteData.GetRequiredString("action");

and

string currentViewName = ((WebFormView)ViewContext.View).ViewPath;

You can retrive both physical name of current view and action that triggered it. It can be usefull in partial *.acmx pages to determine host container.

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

A table name as a variable

You can't use a table name for a variable. You'd have to do this instead:

DECLARE @sqlCommand varchar(1000)
SET @sqlCommand = 'SELECT * from yourtable'
EXEC (@sqlCommand)

How to Export-CSV of Active Directory Objects?

For posterity....I figured out how to get what I needed. Here it is in case it might be useful to somebody else.

$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
    $grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
    $arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
    $aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
    $alist += $aline
}
$alist | Out-File D:\Temp\ADUsers.csv

How to position a div in the middle of the screen when the page is bigger than the screen

Short answer, Just add position:fixed and that will solve your problem

Android webview launches browser when calling loadurl

Simply Answer you can use like this

public class MainActivity extends AppCompatActivity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         WebView webView = new WebView(this);
         setContentView(webView);
         webView.setWebViewClient(new WebViewClient());
         webView.loadUrl("http://www.google.com");
   }
}

How to import JSON File into a TypeScript file?

Angular 10

You should now edit the tsconfig.app.json (notice the "app" in the name) file instead.

There you'll find the compilerOptions, and you simply add resolveJsonModule: true.

So, for example, the file in a brand new project should look like this:

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],
    "resolveJsonModule": true
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

How to mount the android img file under linux?

I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img files all the time.

Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount

"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...

So, how to get the file from the inside of userdata.img?" To load .img files you have to select loop and load the .img Select loop

Next you select mount Select mount

Furius ISO mount handles all the other options loading the .img file to your /home/dir.

Android Dialog: Removing title bar

use,

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); //before     
dialog.setContentView(R.layout.logindialog);

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

For mac :

I have added below two commands its working fine!

-vm
/usr/bin
/usr/libexec/java_home --verbose

Example

What does "request for member '*******' in something not a structure or union" mean?

can also appear if:

struct foo {   int x, int y, int z }foo; 

foo.x=12

instead of

struct foo {   int x; int y; int z; }foo; 

foo.x=12

How to see docker image contents

You can just run an interactive shell container using that image and explore whatever content that image has.

For instance:

docker run -it image_name sh

Or following for images with an entrypoint

docker run -it --entrypoint sh image_name

Or, if you want to see how the image was build, meaning the steps in its Dockerfile, you can:

docker image history --no-trunc image_name > image_history

The steps will be logged into the image_history file.

Changing fonts in ggplot2

A simple answer if you don't want to install anything new

To change all the fonts in your plot plot + theme(text=element_text(family="mono")) Where mono is your chosen font.

List of default font options:

  • mono
  • sans
  • serif
  • Courier
  • Helvetica
  • Times
  • AvantGarde
  • Bookman
  • Helvetica-Narrow
  • NewCenturySchoolbook
  • Palatino
  • URWGothic
  • URWBookman
  • NimbusMon
  • URWHelvetica
  • NimbusSan
  • NimbusSanCond
  • CenturySch
  • URWPalladio
  • URWTimes
  • NimbusRom

R doesn't have great font coverage and, as Mike Wise points out, R uses different names for common fonts.

This page goes through the default fonts in detail.

Go / golang time.Now().UnixNano() convert to milliseconds?

I think it's better to round the time to milliseconds before the division.

func makeTimestamp() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

Here is an example program:

package main

import (
        "fmt"
        "time"
)

func main() {
        fmt.Println(unixMilli(time.Unix(0, 123400000)))
        fmt.Println(unixMilli(time.Unix(0, 123500000)))
        m := makeTimestampMilli()
        fmt.Println(m)
        fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}

func unixMilli(t time.Time) int64 {
        return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func makeTimestampMilli() int64 {
        return unixMilli(time.Now())
}

The above program printed the result below on my machine:

123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST

Web Service vs WCF Service

Basic and primary difference is, ASP.NET web service is designed to exchange SOAP messages over HTTP only while WCF Service can exchange message using any format (SOAP is default) over any transport protocol i.e. HTTP, TCP, MSMQ or NamedPipes etc.

Pagination response payload from a RESTful API

generally, I make by simple way, whatever, I create a restAPI endpoint for example "localhost/api/method/:lastIdObtained/:countDateToReturn" with theses parameters, you can do it a simple request. in the service, eg. .net

jsonData function(lastIdObtained,countDatetoReturn){
'... write your code as you wish..'
and into select query make a filter
select top countDatetoreturn tt.id,tt.desc
 from tbANyThing tt
where id > lastIdObtained
order by id
}

In Ionic, when I scroll from bottom to top, I pass the zero value, when I get the answer, I set the value of the last id obtained, and when I slide from top to bottom, I pass the last registration id I got

What does value & 0xff do in Java?

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.

Constants in Kotlin -- what's a recommended way to create them?

You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants.kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file. The constants known at compile time must be marked with const.

So, in this case, it should be:

const val MY_CONST = "something"

and then you can import the constant using:

import package_name.MY_CONST

You can refer to this link

.includes() not working in Internet Explorer

Or just put this in a Javascript file and have a good day :)

String.prototype.includes = function (str) {
  var returnValue = false;

  if (this.indexOf(str) !== -1) {
    returnValue = true;
  }

  return returnValue;
}

Javascript getElementById based on a partial string

Given that what you want is to determine the full id of the element based upon just the prefix, you're going to have to do a search of the entire DOM (or at least, a search of an entire subtree if you know of some element that is always guaranteed to contain your target element). You can do this with something like:

function findChildWithIdLike(node, prefix) {
    if (node && node.id && node.id.indexOf(prefix) == 0) {
        //match found
        return node;
    }

    //no match, check child nodes
    for (var index = 0; index < node.childNodes.length; index++) {
        var child = node.childNodes[index];
        var childResult = findChildWithIdLike(child, prefix);
        if (childResult) {
            return childResult;
        }
    }
};

Here is an example: http://jsfiddle.net/xwqKh/

Be aware that dynamic element ids like the ones you are working with are typically used to guarantee uniqueness of element ids on a single page. Meaning that it is likely that there are multiple elements that share the same prefix. Probably you want to find them all.

If you want to find all of the elements that have a given prefix, instead of just the first one, you can use something like what is demonstrated here: http://jsfiddle.net/xwqKh/1/

How to create a HashMap with two keys (Key-Pair, Value)?

Two possibilities. Either use a combined key:

class MyKey {
    int firstIndex;
    int secondIndex;
    // important: override hashCode() and equals()
}

Or a Map of Map:

Map<Integer, Map<Integer, Integer>> myMap;

How to use if statements in underscore.js templates?

You can try _.isUndefined

<% if (!_.isUndefined(date)) { %><span class="date"><%= date %></span><% } %>

R: Print list to a text file

depending on your tastes, an alternative to nico's answer:

d<-lapply(mylist, write, file=" ... ", append=T);

I'm getting favicon.ico error

I copied the favicon.ico to assets folder its worked for me .

PHP: Split string

explode does the job:

$parts = explode('.', $string);

You can also directly fetch parts of the result into variables:

list($part1, $part2) = explode('.', $string);

Cannot create PoolableConnectionFactory

This specific issue may arise in localhost also. We cannot rule out this is because network issue or internet connectivity issue. This issue will come even though all the database connection properties are correct.

I have faced the same issue when i have used host name. Instead use ip address. It will get resolved.

PHP sessions default timeout

Yes, that's usually happens after 1440s (24 minutes)

How to drop a list of rows from Pandas dataframe?

In a comment to @theodros-zelleke's answer, @j-jones asked about what to do if the index is not unique. I had to deal with such a situation. What I did was to rename the duplicates in the index before I called drop(), a la:

dropped_indexes = <determine-indexes-to-drop>
df.index = rename_duplicates(df.index)
df.drop(df.index[dropped_indexes], inplace=True)

where rename_duplicates() is a function I defined that went through the elements of index and renamed the duplicates. I used the same renaming pattern as pd.read_csv() uses on columns, i.e., "%s.%d" % (name, count), where name is the name of the row and count is how many times it has occurred previously.

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

Code golf for @liammclennan's answer.

_x000D_
_x000D_
var Animal = function (args) {_x000D_
  return {_x000D_
    name: args.name,_x000D_
_x000D_
    getName: function () {_x000D_
      return this.name; // member access_x000D_
    },_x000D_
_x000D_
    callGetName: function () {_x000D_
      return this.getName(); // method call_x000D_
    }_x000D_
  };_x000D_
};_x000D_
_x000D_
var cat = Animal({ name: 'tiger' });_x000D_
console.log(cat.callGetName());
_x000D_
_x000D_
_x000D_

Insert into a MySQL table or update if exists

Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):

INSERT  live-db.table1
SELECT  *
FROM    test-db.table1 t
ON DUPLICATE KEY UPDATE
        ColToUpdate1 = t.ColToUpdate1,
        ColToUpdate2 = t.ColToUpdate2,
        ...

As mentioned elsewhere, only the columns you want to update need to be included after ON DUPLICATE KEY UPDATE.

No need to list the columns in the INSERT or SELECT, though I agree it's probably better practice.

Is there a method that tells my program to quit?

In Python 3 there is an exit() function:

elif choice == "q":
    exit()

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

It sounds like you've got it the wrong way round. If your existing data is in MM/DD/YYYY format, then you want:

select to_date(date_column,'MM/DD/YYYY') from table;

to convert the existing data to DATE values. (I do wonder why they're not stored as dates, to be honest...)

If you want to perform the conversion in one step, you might want:

select to_char(to_date(date_column,'MM/DD/YYYY'), 'YYYY-MM-DD') from table;

In other words, for each row, parse it in MM/DD/YYYY format, then reformat it to YYYY-MM-DD format.

(I'd still suggest trying to keep data in its "natural" type though, rather than storing it as text in the first place.)

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

The fact that the same number of rows is returned is an after fact, the query optimizer cannot know in advance that every row in Accepts has a matching row in Marker, can it?

If you join two tables A and B, say A has 1 million rows and B has 1 row. If you say A LEFT INNER JOIN B it means only rows that match both A and B can result, so the query plan is free to scan B first, then use an index to do a range scan in A, and perhaps return 10 rows. But if you say A LEFT OUTER JOIN B then at least all rows in A have to be returned, so the plan must scan everything in A no matter what it finds in B. By using an OUTER join you are eliminating one possible optimization.

If you do know that every row in Accepts will have a match in Marker, then why not declare a foreign key to enforce this? The optimizer will see the constraint, and if is trusted, will take it into account in the plan.

Call angularjs function using jquery/javascript

You can use following:

angular.element(domElement).scope() to get the current scope for the element

angular.element(domElement).injector() to get the current app injector

angular.element(domElement).controller() to get a hold of the ng-controller instance.

Hope that might help

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

How do you implement a class in C?

Also see this answer and this one

It is possible. It always seems like a good idea at the time but afterwards it becomes a maintenance nightmare. Your code become littered with pieces of code tying everything together. A new programmer will have lots of problems reading and understanding the code if you use function pointers since it will not be obvious what functions is called.

Data hiding with get/set functions is easy to implement in C but stop there. I have seen multiple attempts at this in the embedded environment and in the end it is always a maintenance problem.

Since you all ready have maintenance issues I would steer clear.

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

Replacing &nbsp; from javascript dom text node

I think when you define a function with "var foo = function() {...};", the function is only defined after that line. In other words, try this:

var replaceHtmlEntites = (function() {
  var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
  var translate = {
    "nbsp": " ",
    "amp" : "&",
    "quot": "\"",
    "lt"  : "<",
    "gt"  : ">"
  };
  return function(s) {
    return ( s.replace(translate_re, function(match, entity) {
      return translate[entity];
    }) );
  }
})();

var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
cleanText = replaceHtmlEntities(text);

Edit: Also, only use "var" the first time you declare a variable (you're using it twice on the cleanText variable).

Edit 2: The problem is the spelling of the function name. You have "var replaceHtmlEntites =". It should be "var replaceHtmlEntities ="

Excel: Searching for multiple terms in a cell

This will do it for you:

=IF(OR(ISNUMBER(SEARCH("Gingrich",C3)),ISNUMBER(SEARCH("Obama",C3))),"1","")

Given this function in the column to the right of the names (which are in column C), the result is:

Romney  
Gingrich    1
Obama       1

This could be due to the service endpoint binding not using the HTTP protocol

If you have a database(working in visual studio), make sure there are no foreign keys in the tables, I had foreign keys and it gave me this error and when I removed them it ran smoothly

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.

Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.

How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.

How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.

Load and execution sequence of a web page?

AFAIK, the browser (at least Firefox) requests every resource as soon as it parses it. If it encounters an img tag it will request that image as soon as the img tag has been parsed. And that can be even before it has received the totality of the HTML document... that is it could still be downloading the HTML document when that happens.

For Firefox, there are browser queues that apply, depending on how they are set in about:config. For example it will not attempt to download more then 8 files at once from the same server... the additional requests will be queued. I think there are per-domain limits, per proxy limits, and other stuff, which are documented on the Mozilla website and can be set in about:config. I read somewhere that IE has no such limits.

The jQuery ready event is fired as soon as the main HTML document has been downloaded and it's DOM parsed. Then the load event is fired once all linked resources (CSS, images, etc.) have been downloaded and parsed as well. It is made clear in the jQuery documentation.

If you want to control the order in which all that is loaded, I believe the most reliable way to do it is through JavaScript.

cannot make a static reference to the non-static field

you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below. sb = starting balance and eB = ending balance.

Account account = new Account(1122, 20000, 4.5);

    double sB = Account.withdraw(account.getBalance(), 2500);
    double eB = Account.deposit(sB, 3000);
    System.out.println("Balance is " + eB);
    System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
    account.setDateCreated(new Date());
    System.out.println("The account was created " + account.getDateCreated());

How to detect query which holds the lock in Postgres?

From this excellent article on query locks in Postgres, one can get blocked query and blocker query and their information from the following query.

CREATE VIEW lock_monitor AS(
SELECT
  COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
  now() - blockeda.query_start AS waiting_duration, blockeda.pid AS blocked_pid,
  blockeda.query as blocked_query, blockedl.mode as blocked_mode,
  blockinga.pid AS blocking_pid, blockinga.query as blocking_query,
  blockingl.mode as blocking_mode
FROM pg_catalog.pg_locks blockedl
JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
JOIN pg_catalog.pg_locks blockingl ON(
  ( (blockingl.transactionid=blockedl.transactionid) OR
  (blockingl.relation=blockedl.relation AND blockingl.locktype=blockedl.locktype)
  ) AND blockedl.pid != blockingl.pid)
JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid
  AND blockinga.datid = blockeda.datid
WHERE NOT blockedl.granted
AND blockinga.datname = current_database()
);

SELECT * from lock_monitor;

As the query is long but useful, the article author has created a view for it to simplify it's usage.

pycharm running way slow

I thought I had a speed issue with PyCharm but in the end it turned out that the output console in PyCharm does not necessarily emulate the output of state-of-the-art terminal applications.

Here's my solution: Click on drop down (arrow) symbol of your configuration -> click edit configuration -> click emulate terminal in output console -> click ok -> Run the configuration.

How to deploy a war file in Tomcat 7

I followed the instruction in the following link, it works for me. http://www.coderanch.com/t/487178/Tomcat/war-file-show-load

  1. Stop Tomcat

  2. Delete all the logs in tomcat/logs and all files in tomcat/conf/Catalina/localhost

  3. Remove the war file and the directory it created (if it did) from tomact/webapps

  4. Start Tomcat

  5. While watching the logs, copy the war file to the webapps directory again

After this, keep an eye on the catalina.xxxx-xx-xx.log to find out the issue.

Swift presentViewController

Solved the black screen by adding a navigation controller and setting the second view controller as rootVC.

let vc = ViewController()       
var navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil

Delete all nodes and relationships in neo4j 1.8

Neo4j cannot delete nodes that have a relation. You have to delete the relations before you can delete the nodes.

But, it is simple way to delete "ALL" nodes and "ALL" relationships with a simple chyper. This is the code:

MATCH (n) DETACH DELETE n

--> DETACH DELETE will remove all of the nodes and relations by Match

Formatting ISODate from Mongodb

you can use mongo query like this yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

enter image description here

How can I define colors as variables in CSS?

I'm not clear on why you can't use PHP. You could then simply add and use variables as you wish, save the file as a PHP file and link to that .php file as the style sheet instead of the .css file.

It doesn't have to be PHP, but you get what I mean.

When we want programming stuff, why not use a programming language until CSS (maybe) supports things like variables?

Also, check out Nicole Sullivan's Object-oriented CSS.

How to solve error message: "Failed to map the path '/'."

I had the same issue (MVC 4) under IIS 7. It turned out that the App Pool identity didn't have the correct authorization to the site's path.

How to fit a smooth curve to my data in R?

Maybe smooth.spline is an option, You can set a smoothing parameter (typically between 0 and 1) here

smoothingSpline = smooth.spline(x, y, spar=0.35)
plot(x,y)
lines(smoothingSpline)

you can also use predict on smooth.spline objects. The function comes with base R, see ?smooth.spline for details.

What is 'Context' on Android?

Context means component (or application) in various time-period. If I do eat so much food between 1 to 2 pm then my context of that time is used to access all methods (or resources) that I use during that time. Content is a component (application) for a particular time. The Context of components of the application keeps changing based on the underlying lifecycle of the components or application. For instance, inside the onCreate() of an Activity,

getBaseContext() -- gives the context of the Activity that is set (created) by the constructor of activity. getApplicationContext() -- gives the Context setup (created) during the creation of application.

Note: <application> holds all Android Components.

<application>
    <activity> .. </activity> 

    <service>  .. </service>

    <receiver> .. </receiver>

    <provider> .. </provider>
</application> 

It means, when you call getApplicationContext() from inside whatever component, you are calling the common context of the whole application.

Context keeps being modified by the system based on the lifecycle of components.

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)

explanation:

par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

WAMP Server doesn't load localhost

Solution(s) for this, found in the official wampserver.com forums:

SOLUTION #1:

This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )

To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80". Note thatPID on the right side. This is the process id of the software which currently usesport 80. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).

SOLUTION #2:

left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80" to 8080. Restart. Done !

SOLUTION #3:

Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here

By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.

IMPORTANT: you have to use localhost or 127.0.0.1 now with port 8080, this means 127.0.0.1:8080 or localhost:8080.

How can you debug a CORS request with cURL?

The bash script "corstest" below works for me. It is based on Jun's comment above.

usage

corstest [-v] url

examples

./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *

the positive result is displayed in green

./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS

the negative result is displayed in red and blue

the -v option will show the full curl headers

corstest

#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'  
red='\033[0;31m'  
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# show the usage
#
usage() {
  echo "usage: [-v] $0 url"
  echo "  -v |--verbose: show curl result" 
  exit 1 
}

if [ $# -lt 1 ]
then
  usage
fi

# commandline option
while [  "$1" != ""  ]
do
  url=$1
  shift

  # optionally show usage
  case $url in      
    -v|--verbose)
       verbose=true;
       ;;          
  esac
done  


if [ "$verbose" = "true" ]
then
  curl -s -X GET $url -H 'Cache-Control: no-cache' --head 
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)


if [ $? -eq 0 ]
then
  color_msg $green "$url $origin"
else
  color_msg $red "$url does not support CORS"
  color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Java Multithreading concept and join() method

See the concept is very simple.

1) All threads are started in the constructor and thus are in ready to run state. Main is already the running thread.

2) Now you called the t1.join(). Here what happens is that the main thread gets knotted behind the t1 thread. So you can imagine a longer thread with main attached to the lower end of t1.

3) Now there are three threads which could run: t2, t3 and combined thread(t1 + main).

4)Now since till t1 is finished main can't run. so the execution of the other two join statements has been stopped.

5) So the scheduler now decides which of the above mentioned(in point 3) threads run which explains the output.

How to view file diff in git before commit

To check for local differences:

git diff myfile.txt

or you can use a diff tool (in case you'd like to revert some changes):

git difftool myfile.txt

To use git difftool more efficiently, install and use your favourite GUI tool such as Meld, DiffMerge or OpenDiff.

Note: You can also use . (instead of filename) to see current dir changes.

In order to check changes per each line, use: git blame which will display which line was commited in which commit.


To view the actual file before the commit (where master is your branch), run:

git show master:path/my_file

Change mysql user password using command line

As of MySQL 5.7.6, use ALTER USER

Example:

ALTER USER 'username' IDENTIFIED BY 'password';

Because:

  • SET PASSWORD ... = PASSWORD('auth_string') syntax is deprecated as of MySQL 5.7.6 and will be removed in a future MySQL release.

  • SET PASSWORD ... = 'auth_string' syntax is not deprecated, but ALTER USER is now the preferred statement for assigning passwords.

How to display gpg key details without importing it?

To get the key IDs (8 bytes, 16 hex digits), this is the command which worked for me in GPG 1.4.16, 2.1.18 and 2.2.19:

gpg --list-packets <key.asc | awk '$1=="keyid:"{print$2}'

To get some more information (in addition to the key ID):

gpg --list-packets <key.asc

To get even more information:

gpg --list-packets -vvv --debug 0x2 <key.asc

The command

gpg --dry-run --import <key.asc

also works in all 3 versions, but in GPG 1.4.16 it prints only a short (4 bytes, 8 hex digits) key ID, so it's less secure to identify keys.

Some commands in other answers (e.g. gpg --show-keys, gpg --with-fingerprint, gpg --import --import-options show-only) don't work in some of the 3 GPG versions above, thus they are not portable when targeting multiple versions of GPG.

In Typescript, How to check if a string is Numeric

For full numbers (non-floats) in Angular you can use:

if (Number.isInteger(yourVariable)) { ... }

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

For an IIS MVC 5 / Angular CLI ( Yes, I am well aware your problem is with Angular JS ) project with API I did the following:

web.config under <system.webServer> node

    <staticContent>
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
    </staticContent>
    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, atv2" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
      </customHeaders>
    </httpProtocol>

global.asax.cs

protected void Application_BeginRequest() {
  if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) && Request.HttpMethod == "OPTIONS") {
    Response.Flush();
    Response.End();
  }
}

That should fix your issues for both MVC and WebAPI without having to do all the other run around. I then created an HttpInterceptor in the Angular CLI project that automatically added in the the relevant header information. Hope this helps someone out in a similar situation.

TSQL DATETIME ISO 8601

You technically have two options when speaking of ISO dates.

In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd or y-m-d. Which are both valid ISO formats.

Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.

Because of this, your safest bet is to persist/filter based on the always netural ymd format.

The code:

select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)

Add ArrayList to another ArrayList in java

Very first will declare outer Arraylist which will contain another inner Arraylist inside it

ArrayList> CompletesystemStatusArrayList; ArrayList systemStatusArrayList

CompletesystemStatusArrayList=new ArrayList

systemStatusArrayList=new ArrayList();

    systemStatusArrayList.add("1");
    systemStatusArrayList.add("2");
    systemStatusArrayList.add("3");
    systemStatusArrayList.add("4");
    systemStatusArrayList.add("5");
    systemStatusArrayList.add("6");
    systemStatusArrayList.add("7");
    systemStatusArrayList.add("8");

    CompletesystemStatusArrayList.add(systemStatusArrayList);

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

Output an Image in PHP

You can use header to send the right Content-type :

header('Content-Type: ' . $type);

And readfile to output the content of the image :

readfile($file);


And maybe (probably not necessary, but, just in case) you'll have to send the Content-Length header too :

header('Content-Length: ' . filesize($file));


Note : make sure you don't output anything else than your image data (no white space, for instance), or it will no longer be a valid image.

Getting last day of the month in a given string date

Java 8 and above.

By using convertedDate.getMonth().length(convertedDate.isLeapYear()) where convertedDate is an instance of LocalDate.

String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
                                convertedDate.getMonth().length(convertedDate.isLeapYear()));

Java 7 and below.

By using getActualMaximum method of java.util.Calendar:

String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));

JavaScript CSS how to add and remove multiple CSS classes to an element

This works:

myElement.className = 'foo bar baz';

How do we change the URL of a working GitLab install?

You did everything correctly!

You might also change the email configuration, depending on if the email server is also the same server. The email configuration is in gitlab.yml for the mails sent by GitLab and also the admin-email.

How to add new line into txt file

No new line:

File.AppendAllText("file.txt", DateTime.Now.ToString());

and then to get a new line after OK:

File.AppendAllText("file.txt", string.Format("{0}{1}", "OK", Environment.NewLine));

How do you debug PHP scripts?

Nusphere is also a good debugger for php nusphere

How do I run a command on an already existing Docker container?

I had to use bash -c to run my command: docker exec -it CONTAINER_ID bash -c "mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql mysql"

Passing environment-dependent variables in webpack

Just another answer that is similar to @zer0chain's answer. However, with one distinction.

Setting webpack -p is sufficient.

It is the same as:

--define process.env.NODE_ENV="production"

And this is the same as

// webpack.config.js
const webpack = require('webpack');

module.exports = {
  //...

  plugins:[
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    })
  ]
};

So you may only need something like this in package.json Node file:

{
  "name": "projectname",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "debug": "webpack -d",
    "production": "webpack -p"
  },
  "author": "prosti",
  "license": "ISC",
  "dependencies": {    
    "webpack": "^2.2.1",
    ...
  }
}

Just a few tips from the DefinePlugin:

The DefinePlugin allows you to create global constants which can be configured at compile time. This can be useful for allowing different behavior between development builds and release builds. For example, you might use a global constant to determine whether logging takes place; perhaps you perform logging in your development build but not in the release build. That's the sort of scenario the DefinePlugin facilitates.


That this is so you can check if you type webpack --help

Config options:
  --config  Path to the config file
                         [string] [default: webpack.config.js or webpackfile.js]
  --env     Enviroment passed to the config, when it is a function

Basic options:
  --context    The root directory for resolving entry point and stats
                                       [string] [default: The current directory]
  --entry      The entry point                                          [string]
  --watch, -w  Watch the filesystem for changes                        [boolean]
  --debug      Switch loaders to debug mode                            [boolean]
  --devtool    Enable devtool for better debugging experience (Example:
               --devtool eval-cheap-module-source-map)                  [string]
  -d           shortcut for --debug --devtool eval-cheap-module-source-map
               --output-pathinfo                                       [boolean]
  -p           shortcut for --optimize-minimize --define
               process.env.NODE_ENV="production" 

                      [boolean]
  --progress   Print compilation progress in percentage                [boolean]

Java - checking if parseInt throws exception

It would be something like this.

String text = textArea.getText();
Scanner reader = new Scanner(text).useDelimiter("\n");
while(reader.hasNext())
    String line = reader.next();

    try{
        Integer.parseInt(line);
        //it worked
    }
    catch(NumberFormatException e){
       //it failed
    }
}

How to use mongoimport to import csv

All these answers above are great. And the way to go on a full featured application.

But if you want to prototype fast, want flexibility as the collection still changes as well as to minimize your early code base, there is a much simpler way that is not much discussed.

You can basically forego mongoimport by now. I could have saved 3 hours if it was mentioned here on this question. So let me share for others:

Mongodb has a GUI called Mongo Compass has both csv and json import features out of the box in a matter of clicks. It is an official part of the Mongo ecosytem. At the time of writing it is free and it works very well for my use case. https://www.mongodb.com/products/compass

  1. You simply get MongoDB compass running on your machine by following the simple installation. A couple of fields for DB connection and authentication directly in the GUI.
  2. Import the csv/json file. It took less than a second on a 30KB file to be parsed before user (me) validates.
  3. Validate the "type" of each property. Great feature, I could directly mention the property types such as booleans, integers, etc. In my experience, they seem all default to string. You can update before importing. Dates were more finicky and needed special attention on the coding side.
  4. One click further the csv is a collection in your mongo db local or on the cloud. Voila!

Remove an array element and shift the remaining ones

You can use memmove(), but you have to keep track of the array size yourself:

size_t array_size = 5;
int array[5] = {1, 2, 3, 4, 5};

// delete element at index 2
memmove(array + 2, array + 3, (array_size - 2 - 1) * sizeof(int));
array_size--;

In C++, though, it would be better to use a std::vector:

std::vector<int> array;
// initialize array...

// delete element at index 2
array.erase(array.begin() + 2);

Bulk insert with SQLAlchemy ORM

As far as I know, there is no way to get the ORM to issue bulk inserts. I believe the underlying reason is that SQLAlchemy needs to keep track of each object's identity (i.e., new primary keys), and bulk inserts interfere with that. For example, assuming your foo table contains an id column and is mapped to a Foo class:

x = Foo(bar=1)
print x.id
# None
session.add(x)
session.flush()
# BEGIN
# INSERT INTO foo (bar) VALUES(1)
# COMMIT
print x.id
# 1

Since SQLAlchemy picked up the value for x.id without issuing another query, we can infer that it got the value directly from the INSERT statement. If you don't need subsequent access to the created objects via the same instances, you can skip the ORM layer for your insert:

Foo.__table__.insert().execute([{'bar': 1}, {'bar': 2}, {'bar': 3}])
# INSERT INTO foo (bar) VALUES ((1,), (2,), (3,))

SQLAlchemy can't match these new rows with any existing objects, so you'll have to query them anew for any subsequent operations.

As far as stale data is concerned, it's helpful to remember that the session has no built-in way to know when the database is changed outside of the session. In order to access externally modified data through existing instances, the instances must be marked as expired. This happens by default on session.commit(), but can be done manually by calling session.expire_all() or session.expire(instance). An example (SQL omitted):

x = Foo(bar=1)
session.add(x)
session.commit()
print x.bar
# 1
foo.update().execute(bar=42)
print x.bar
# 1
session.expire(x)
print x.bar
# 42

session.commit() expires x, so the first print statement implicitly opens a new transaction and re-queries x's attributes. If you comment out the first print statement, you'll notice that the second one now picks up the correct value, because the new query isn't emitted until after the update.

This makes sense from the point of view of transactional isolation - you should only pick up external modifications between transactions. If this is causing you trouble, I'd suggest clarifying or re-thinking your application's transaction boundaries instead of immediately reaching for session.expire_all().

Detect the Enter key in a text input field

It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.

        <script type="text/javascript"> 
        function stopRKey(evt) { 
          var evt = (evt) ? evt : ((event) ? event : null); 
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
          if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
        } 

        document.onkeypress = stopRKey; 

        </script>

Why would you use String.Equals over ==?

I've just been banging my head against a wall trying to solve a bug because I read this page and concluded there was no meaningful difference when in practice there is so I'll post this link here in case anyone else finds they get different results out of == and equals.

Object == equality fails, but .Equals succeeds. Does this make sense?

string a = "x";
string b = new String(new []{'x'});

Console.WriteLine("x == x " + (a == b));//True
Console.WriteLine("object x == x " + ((object)a == (object)b));//False
Console.WriteLine("x equals x " + (a.Equals(b)));//True
Console.WriteLine("object x equals x " + (((object)a).Equals((object)b)));//True

Better way to Format Currency Input editText?

I built on Guilhermes answer, but I preserve the position of the cursor and also treat the periods differently - this way if a user is typing after the period, it does not affect the numbers before the period I find that this gives a very smooth input.

    [yourtextfield].addTextChangedListener(new TextWatcher()
    {
        NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
        private String current = "";

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            if(!s.toString().equals(current))
            {
                   [yourtextfield].removeTextChangedListener(this);

                   int selection = [yourtextfield].getSelectionStart();


                   // We strip off the currency symbol
                   String replaceable = String.format("[%s,\\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
                   String cleanString = s.toString().replaceAll(replaceable, "");

                   double price;

                   // Parse the string                     
                   try
                   {
                       price = Double.parseDouble(cleanString);
                   }
                   catch(java.lang.NumberFormatException e)
                   {
                       price = 0;
                   }

                   // If we don't see a decimal, then the user must have deleted it.
                   // In that case, the number must be divided by 100, otherwise 1
                   int shrink = 1;
                   if(!(s.toString().contains(".")))
                   {
                       shrink = 100;
                   }

                   // Reformat the number
                   String formated = currencyFormat.format((price / shrink));

                   current = formated;
                   [yourtextfield].setText(formated);
                   [yourtextfield].setSelection(Math.min(selection, [yourtextfield].getText().length()));

                   [yourtextfield].addTextChangedListener(this);
                }
        }


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

        }


        @Override
        public void afterTextChanged(Editable s)
        {
        }
    });

Strip HTML from Text JavaScript

I would like to share an edited version of the Shog9's approved answer.


As Mike Samuel pointed with a comment, that function can execute inline javascript codes.
But Shog9 is right when saying "let the browser do it for you..."

so.. here my edited version, using DOMParser:

function strip(html){
   let doc = new DOMParser().parseFromString(html, 'text/html');
   return doc.body.textContent || "";
}

here the code to test the inline javascript:

strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")

Also, it does not request resources on parse (like images)

strip("Just text <img src='https://assets.rbl.ms/4155638/980x.jpg'>")

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

You should use html():

SEE DEMO

$(document).ready(function(){
    $("#date").html('<span>'+$("#date").text().substring(0, 2) + '</span><br />'+$("#date").text().substring(3));     
});

Modify tick label text

you can do:

for k in ax.get_xmajorticklabels():
    if some-condition:
        k.set_color(any_colour_you_like)

draw()

Adding 30 minutes to time formatted as H:i in PHP

What you need is a datetime which is 30 minutes later than your given datetime, and a datetime which is 30 minutes before a given datetime. In other words, you need a future datetime and a past datetime. Hence, classes that achieve that are called Future and Past. What data do they need to calculate what you need? Apparently, they must have a datetime relative to which to count those 30 minutes, and an interval itself -- 30 minutes in your case. Thus, the desired datetime looks like the following:

use Meringue\ISO8601DateTime\FromCustomFormat as DateTimeCreatedFromCustomFormat;

(new Future(
    new DateTimeCreatedFromCustomFormat('H:i', '10:00'),
    new NMinutes(30)
))
    ->value();

If you want to format it somehow, you can do:

use Meringue\ISO8601DateTime\FromCustomFormat as DateTimeCreatedFromCustomFormat;

(new ISO8601Formatted(
    new Future(
        new DateTimeCreatedFromCustomFormat('H:i', '10:00'),
        new NMinutes(30)
    ),
    'H:i'
))
    ->value();

It's more verbose, but I guess it's way less cryptic than built-in php functions.

If you liked this approach, you can learn some more about the meringue library used in this example, and the overall approach.

mySQL :: insert into table, data from another table?

This query is for add data from one table to another table using foreign key

let qry = "INSERT INTO `tb_customer_master` (`My_Referral_Code`, `City_Id`, `Cust_Name`, `Reg_Date_Time`, `Mobile_Number`, `Email_Id`, `Gender`, `Cust_Age`, `Profile_Image`, `Token`, `App_Type`, `Refer_By_Referral_Code`, `Status`) values ('" + randomstring.generate(7) + "', '" + req.body.City_Id + "', '" + req.body.Cust_Name + "', '" + req.body.Reg_Date_Time + "','" + req.body.Mobile_Number + "','" + req.body.Email_Id + "','" + req.body.Gender + "','" + req.body.Cust_Age + "','" + req.body.Profile_Image + "','" + req.body.Token + "','" + req.body.App_Type + "','" + req.body.Refer_By_Referral_Code + "','" + req.body.Status + "')";
                        connection.query(qry, (err, rows) => {
                            if (err) { res.send(err) } else {
                                let insert = "INSERT INTO `tb_customer_and_transaction_master` (`Cust_Id`)values ('" + rows.insertId + "')";
                                connection.query(insert, (err) => {
                                    if (err) {
                                        res.json(err)
                                    } else {
                                        res.json("Customer added")
                                    }
                                })
                            }
    
    
                        })
                    }
                }
    
            }
        })
    })

How to fix "Referenced assembly does not have a strong name" error?

Situation: You had project A,B,C,D in solution X,Y

Project A, B, C in X Project A, C, D in Y

I need use project C in project A, but later i dont use. In bin Debug project A had C.dll.

If I compile solution X, all good ( in this solution i delete reference A -> C. ), but in solution Y I get this problem.

Solution is delete C.dll in project A bin Debug

Close iOS Keyboard by touching anywhere using Swift

Swift 3

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

How can I send the "&" (ampersand) character via AJAX?

You might want to use encodeURIComponent().

encodeURIComponent("&quot;Busola&quot;"); // => %26quot%3BBusola%26quot%3B

Unable to load DLL 'SQLite.Interop.dll'

Expanding on Kugel’s answer which worked for me (VS2015 Enterprise) leveraging SQLite from a dll the Nuget package can be removed from the main project after building and testing:

1.Install Nuget package to main project.

Install-Package System.Data.SQLite

2.Build Application and test that your Sqlite connection is working:

select * from sqlite_master

3.Uninstall Nuget package from the main build.

UnInstall-Package System.Data.SQLite

4.Manually remove the dll references for SQLite and EntityFramework:

System.Data.SQLite
System.Data.SQLite.EF6
System.Data.SQLite.Linq
  1. Remove Xml references from the main project's “packages.config” xml file.

This worked for me and keeps my project clean.

Changing Locale within the app itself

After a good night of sleep, I found the answer on the Web (a simple Google search on the following line "getBaseContext().getResources().updateConfiguration(mConfig, getBaseContext().getResources().getDisplayMetrics());"), here it is :

link text => this link also shows screenshots of what is happening !

Density was the issue here, I needed to have this in the AndroidManifest.xml

<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true"
/>

The most important is the android:anyDensity =" true ".

Don't forget to add the following in the AndroidManifest.xml for every activity (for Android 4.1 and below):

android:configChanges="locale"

This version is needed when you build for Android 4.2 (API level 17) explanation here:

android:configChanges="locale|layoutDirection"

How do I query using fields inside the new PostgreSQL JSON datatype?

Postgres 9.2

I quote Andrew Dunstan on the pgsql-hackers list:

At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.

Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.

Postgres 9.3

Offers an arsenal of new functions and operators to add "json-processing".

The answer to the original question in Postgres 9.3:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ]'
  ) AS elem
WHERE elem->>'name' = 'Toby';

Advanced example:

For bigger tables you may want to add an expression index to increase performance:

Postgres 9.4

Adds jsonb (b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb also supports GIN, btree and hash indexes, GIN being the most potent of these.

The manual goes as far as suggesting:

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

Bold emphasis mine.

Performance benefits from general improvements to GIN indexes.

Postgres 9.5

Complete jsonb functions and operators. Add more functions to manipulate jsonb in place and for display.

Powershell v3 Invoke-WebRequest HTTPS error

Lee's answer is great, but I also had issues with which protocols the web server supported.
After also adding the following lines, I could get the https request through. As pointed out in this answer https://stackoverflow.com/a/36266735

$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols

My full solution with Lee's code.

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}
"@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

How to drop all user tables?

The simplest way is to drop the user that owns the objects with the cascade command.

DROP USER username CASCADE

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. you are selecting

t1.ID, t2.ReceivedDate from Table t1

union

t2.ID from Table t2

which is incorrect.

so you have to write

t1.ID, t1.ReceivedDate from Table t1 union t2.ID, t2.ReceivedDate from Table t1

you can use sub query here

 SELECT tbl1.ID, tbl1.ReceivedDate FROM
      (select top 2 t1.ID, t1.ReceivedDate
      from tbl1 t1
      where t1.ItemType = 'TYPE_1'
      order by ReceivedDate desc
      ) tbl1 
 union
    SELECT tbl2.ID, tbl2.ReceivedDate FROM
     (select top 2 t2.ID, t2.ReceivedDate
      from tbl2 t2
      where t2.ItemType = 'TYPE_2'
      order by t2.ReceivedDate desc
     ) tbl2 

so it will return only distinct values by default from both table.

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Quick answer: the FROM address must exactly match the account you are sending from, or you will get a error 5.7.1 Client does not have permissions to send as this sender.

My guess is that prevents email spoofing with your Office 365 account, otherwise you might be able to send as [email protected].

Another thing to try is in the authentication, fill in the third field with the domain, like

Dim smtpAuth = New System.Net.NetworkCredential(
    "TheDude", "hunter2password", "MicrosoftOffice365Domain.com")

If that doesn't work, double check that you can log into the account at: https://portal.microsoftonline.com

Yet another thing to note is your Antivirus solution may be blocking programmatic access to ports 25 and 587 as a anti-spamming solution. Norton and McAfee may silently block access to these ports. Only enabling Mail and Socket debugging will allow you to notice it (see below).

One last thing to note, the Send method is Asynchronous. If you call

Dispose
immediately after you call send, your are more than likely closing your connection before the mail is sent. Have your smtpClient instance listen for the OnSendCompleted event, and call dispose from there. You must use SendAsync method instead, the Send method does not raise this event.


Detailed Answer: With Visual Studio (VB.NET or C# doesn't matter), I made a simple form with a button that created the Mail Message, similar to that above. Then I added this to the application.exe.config (in the bin/debug directory of my project). This enables the Output tab to have detailed debug info.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.Net">
                <listeners>
                    <add name="System.Net" />
                </listeners>
            </source>
            <source name="System.Net.Sockets">
                <listeners>
                    <add name="System.Net" />
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="System.Net" value="Verbose" />
            <add name="System.Net.Sockets" value="Verbose" />
        </switches>
        <sharedListeners>
            <add name="System.Net"
              type="System.Diagnostics.TextWriterTraceListener"
              initializeData="System.Net.log"
            />
        </sharedListeners>
        <trace autoflush="true" />
    </system.diagnostics>
</configuration>

How to reset db in Django? I get a command 'reset' not found error

reset has been replaced by flush with Django 1.5, see:

python manage.py help flush

jQuery: read text file from file system

A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:

html:

<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
  <script type="text/javascript">
    function loadData() {
      // getData() will return the string of data...
      document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
    }
  </script>
</head>

<body onload='loadData()'>
  <h1>check out the data!</h1>
  <div id='data'></div>
</body>

</html>

script.js:

// function wrapper, just return the string of data (csv etc)
function getData () {
    return 'look at this line of data\n\
oh, look at this line'
}

See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\').

Generate random numbers using C++11 random library

Stephan T. Lavavej (stl) from Microsoft did a talk at Going Native about how to use the new C++11 random functions and why not to use rand(). In it, he included a slide that basically solves your question. I've copied the code from that slide below.

You can see his full talk here: http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

#include <random>
#include <iostream>

int main() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(1.0, 10.0);

    for (int i=0; i<16; ++i)
        std::cout << dist(mt) << "\n";
}

We use random_device once to seed the random number generator named mt. random_device() is slower than mt19937, but it does not need to be seeded because it requests random data from your operating system (which will source from various locations, like RdRand for example).


Looking at this question / answer, it appears that uniform_real_distribution returns a number in the range [a, b), where you want [a, b]. To do that, our uniform_real_distibution should actually look like:

std::uniform_real_distribution<double> dist(1, std::nextafter(10, DBL_MAX));

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

How do I get a button to open another activity?

Button T=(Button)findViewById(R.id.button_timer);
T.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent i=new Intent(getApplicationContext(),YOURACTIVITY.class);
        startActivity(i);
    }
});

SharePoint 2013 get current user using JavaScript

you can use below function if you know the id of the user:

function getUser(id){
var returnValue;
jQuery.ajax({
 url: "http://YourSite/_api/Web/GetUserById(" + id + ")",
 type: "GET",
 headers: { "Accept": "application/json;odata=verbose" },
 success: function(data) {
       var dataResults = data.d;
       alert(dataResults.Title);
  }
});
}

or you can try

var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser";

Defining arrays in Google Scripts

Try this

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  //var values = rows.getValues();

  var Names = sheet.getRange("A2:A7");
  var Name = [
    Names.getCell(1, 1).getValue(),
    Names.getCell(2, 1).getValue(),
    .....
    Names.getCell(5, 1).getValue()]

You can define arrays simply as follows, instead of allocating and then assigning.

var arr = [1,2,3,5]

Your initial error was because of the following line, and ones like it

var Name[0] = Name_cell.getValue(); 

Since Name is already defined and you are assigning the values to its elements, you should skip the var, so just

Name[0] = Name_cell.getValue();

Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.

Reading a JSP variable from JavaScript

   <% String s="Hi"; %>
   var v ="<%=s%>"; 

How to output only captured groups with sed?

you can use grep

grep -Eow "[0-9]+" file

What is the syntax of the enhanced for loop in Java?

Enhanced for loop:

for (String element : array) {

    // rest of code handling current element
}

Traditional for loop equivalent:

for (int i=0; i < array.length; i++) {
    String element = array[i]; 

    // rest of code handling current element
}

Take a look at these forums: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html

AttributeError: 'str' object has no attribute 'append'

myList[1] is an element of myList and it's type is string.

myList[1] is str, you can not append to it. myList is a list, you should have been appending to it.

>>> myList = [1, 'from form', [1,2]]
>>> myList[1]
'from form'
>>> myList[2]
[1, 2]
>>> myList[2].append('t')
>>> myList
[1, 'from form', [1, 2, 't']]
>>> myList[1].append('t')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
>>> 

How do you decompile a swf file

erlswf is an opensource project written in erlang for decompiling .swf files.

Here's the site: https://github.com/bef/erlswf

SHA-1 fingerprint of keystore certificate

First there is same .jar file that in fb-sdk android-support-v4.jar.
Then generate SHA1 key using:

PackageInfo info;
try {

    info = getPackageManager().getPackageInfo(
        "com.example.worldmission", PackageManager.GET_SIGNATURES);

    for (Signature signature : info.signatures) {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        String something = new String(Base64.encode(md.digest(), 0));
        Log.e("Hash key", something);
        System.out.println("Hash key" + something);
    }

} catch (NameNotFoundException e1) {
    Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
    Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
    Log.e("exception", e.toString());
}

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

Using Bootstrap Tooltip with AngularJS

The best solution I've been able to come up with is to include an "onmouseenter" attribute on your element like this:

<button type="button" class="btn btn-default" 
    data-placement="left"
    title="Tooltip on left"
    onmouseenter="$(this).tooltip('show')">
</button>

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

Function not defined javascript

There are a couple of things to check:

  • In FireBug, see if there are any loading errors that would indicate that your script is badly formatted and the functions do not get registered.
  • You can also try typing "proceedToSecond" into the FireBug console to see if the function gets defined
  • One thing you may try is removing the space around the @type attribute to the script tag: it should be <script type="text/javascript"> instead of <script type = "text/javascript">

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

Error happens in your function declarations,look the following sentence!You need a semicolon!


AST_NODE* Statement(AST_NODE* node)

How to set the locale inside a Debian/Ubuntu Docker container?

@Mixel's answer worked great for the Ubuntu-based docker image we have.

However, we also have a centos-based docker image for testing recipes via chef (using the kitchen-docker driver). One of the packages we pre-install was failing to install due to no locale being set. In order to get a locale installed, I had to run the following:

localedef -c -f UTF-8 -i en_US en_US.UTF-8
export LC_ALL=en_US.UTF-8

I got this information from this answer on ServerFault.

After running the above commands as part of the docker provisioning the package installed without any errors. From .kitchen.yml:

platforms:
  - name: centos7
    driver_config:
      image: #(private image)
      platform: centos
      provision_command:
      - localedef -c -f UTF-8 -i en_US en_US.UTF-8
      - export LC_ALL=en_US.UTF-8

What is referencedColumnName used for in JPA?

"referencedColumnName" property is the name of the column in the table that you are making reference with the column you are anotating. Or in a short manner: it's the column referenced in the destination table. Imagine something like this: cars and persons. One person can have many cars but one car belongs only to one person (sorry, I don't like anyone else driving my car).

Table Person
name char(64) primary key
age int

Table Car
car_registration char(32) primary key
car_brand (char 64)
car_model (char64)
owner_name char(64) foreign key references Person(name)

When you implement classes you will have something like

class Person{
   ...
}

class Car{
    ...
    @ManyToOne
    @JoinColumn([column]name="owner_name", referencedColumnName="name")
    private Person owner;
}

EDIT: as @searchengine27 has commented, columnName does not exist as a field in persistence section of Java7 docs. I can't remember where I took this property from, but I remember using it, that's why I'm leaving it in my example.

How to add a scrollbar to an HTML5 table?

You can use a division class with the overflow attribute using the value scroll. Or you can enclose the table inside an iframe. The iframe works well with old and new IE browsers, but it may not work with other browsers and probably not with the latest IE.

 #myid { overflow-x: scroll; overflow-y: hide; width:200px; /* Or whatever the amount of pixels */ }
.myid { overflow-x: scroll; overflow-y: hide; width:200px; /* Or whatever the amount of pixels */ }

<div class="myid">
     <div class="row">Content1</div>
     <div class="row2">Content2</div>
</div>

<table id="myid"><tr><td>Content</td></tr></table>

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

Error occurred during initialization of VM Could not reserve enough space for 1572864KB object heap.

To solve This Error You Have To Change Only Heap Size Which Is Define In Gradle.Properties file. You Have To Change The HeapSize To 1024m And Rebuild the Project, If The Error Is Not Solved Then You Have To Close The Project And Rebuild It.

For Video Tutorial See Below Link SOLVED : Unable To Start The Daemon Process In Android Studio

How can I delete all cookies with JavaScript?

On the face of it, it looks okay - if you call eraseCookie() on each cookie that is read from document.cookie, then all of your cookies will be gone.

Try this:

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
  eraseCookie(cookies[i].split("=")[0]);

All of this with the following caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.

Get table column names in MySQL?

I made a PDO function which returns all the column names in an simple array.

public function getColumnNames($table){
    $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
    try {
        $core = Core::getInstance();
        $stmt = $core->dbh->prepare($sql);
        $stmt->bindValue(':table', $table, PDO::PARAM_STR);
        $stmt->execute();
        $output = array();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $output[] = $row['COLUMN_NAME'];                
        }
        return $output; 
    }

    catch(PDOException $pe) {
        trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
    }
}

The output will be an array:

Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )

Sorry for the necro but I like my function ;)

P.S. I have not included the class Core but you can use your own class.. D.S.

CSS:Defining Styles for input elements inside a div

CSS 3

divContainer input[type="text"] {
    width:150px;
}

CSS2 add a class "text" to the text inputs then in your css

.divContainer.text{
    width:150px;
}

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

How do I upgrade to Python 3.6 with conda?

Anaconda has not updated python internally to 3.6.

a) Method 1

  1. If you wanted to update you will type conda update python
  2. To update anaconda type conda update anaconda
  3. If you want to upgrade between major python version like 3.5 to 3.6, you'll have to do

    conda install python=$pythonversion$
    

b) Method 2 - Create a new environment (Better Method)

conda create --name py36 python=3.6

c) To get the absolute latest python(3.6.5 at time of writing)

conda create --name py365 python=3.6.5 --channel conda-forge

You can see all this from here

Also, refer to this for force upgrading

EDIT: Anaconda now has a Python 3.6 version here

How to access Spring MVC model object in javascript file?

   @RequestMapping("/op")
   public ModelAndView method(Map<String, Object> model) {
       model.put("att", "helloooo");
       return new ModelAndView("dom/op");
   }

In your .js

<script>
    var valVar = [[${att}]];
</script>

Loading an image to a <img> from <input file>

As iEamin said in his answer, HTML 5 does now support this. The link he gave, http://www.html5rocks.com/en/tutorials/file/dndfiles/ , is excellent. Here is a minimal sample based on the samples at that site, but see that site for more thorough examples.

Add an onchange event listener to your HTML:

<input type="file" onchange="onFileSelected(event)">

Make an image tag with an id (I'm specifying height=200 to make sure the image isn't too huge onscreen):

<img id="myimage" height="200">

Here is the JavaScript of the onchange event listener. It takes the File object that was passed as event.target.files[0], constructs a FileReader to read its contents, and sets up a new event listener to assign the resulting data: URL to the img tag:

function onFileSelected(event) {
  var selectedFile = event.target.files[0];
  var reader = new FileReader();

  var imgtag = document.getElementById("myimage");
  imgtag.title = selectedFile.name;

  reader.onload = function(event) {
    imgtag.src = event.target.result;
  };

  reader.readAsDataURL(selectedFile);
}

What should every programmer know about security?

Rule #1 of security for programmers: Don't roll your own

Unless you are yourself a security expert and/or cryptographer, always use a well-designed, well-tested, and mature security platform, framework, or library to do the work for you. These things have spent years being thought out, patched, updated, and examined by experts and hackers alike. You want to gain those advantages, not dismiss them by trying to reinvent the wheel.

Now, that's not to say you don't need to learn anything about security. You certainly need to know enough to understand what you're doing and make sure you're using the tools correctly. However, if you ever find yourself about to start writing your own cryptography algorithm, authentication system, input sanitizer, etc, stop, take a step back, and remember rule #1.

Htaccess: add/remove trailing slash from URL

This is what I've used for my latest app.

# redirect the main page to landing
##RedirectMatch 302 ^/$ /landing

# remove php ext from url
# https://stackoverflow.com/questions/4026021/remove-php-extension-with-htaccess
RewriteEngine on 

# File exists but has a trailing slash
# https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)/+$ /$1 [R=302,L,QSA]

# ok. It will still find the file but relative assets won't load
# e.g. page: /landing/  -> assets/js/main.js/main
# that's we have the rules above.
RewriteCond %{REQUEST_FILENAME} !\.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^/?(.*?)/?$ $1.php

Microsoft.Office.Core Reference Missing

If you are not able to find PIA for Office 2013 then follow these steps:

  1. Click on Solution Explorer in Visual Studio
  2. Right click on your project name (not solution name)
  3. Select 'Manage Nuget packages'
  4. Click on Browse and search for PIA 2013, choose the shown PIA and click on Install.....

And you are done.

CMake link to external library

arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:

You could add an "imported" library target, instead of a link-directory. Something like:

# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )

And then link as if this library was built by your project:

TARGET_LINK_LIBRARIES(GLBall mylib)

Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.

I do not know if this will solve your problem with "updated versions of libs".

How to add to the end of lines containing a pattern with sed or awk?

Solution with awk:

awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file

Simply: if the row starts with all print the row plus "anotherthing", else print just the row.

A failure occurred while executing com.android.build.gradle.internal.tasks

Try this, in Android Studio

File > Invalidate Caches/Restart... 

WCF service startup error "This collection already contains an address with scheme http"

Summary,

Code solution: Here

Configuration solutions: Here

With the help of Mike Chaliy, I found some solutions on how to do this through code. Because this issue is going to affect pretty much all projects we deploy to a live environment I held out for a purely configuration solution. I eventually found one which details how to do it in .net 3.0 and .net 3.5.

Taken from the site, below is an example of how to alter your applications web config:

<system.serviceModel>
    <serviceHostingEnvironment>
        <baseAddressPrefixFilters>
            <add prefix="net.tcp://payroll.myorg.com:8000"/>
            <add prefix="http://shipping.myorg.com:9000"/>
        </baseAddressPrefixFilters>
    </serviceHostingEnvironment>
</system.serviceModel>

In the above example, net.tcp://payroll.myorg.com:8000 and http://shipping.myorg.com:9000 are the only base addresses, for their respective schemes, which will be allowed to be passed through. The baseAddressPrefixFilter does not support any wildcards .

The baseAddresses supplied by IIS may have addresses bound to other schemes not present in baseAddressPrefixFilter list. These addresses will not be filtered out.

Dns solution (untested): I think that if you created a new dns entry specific to your web application, added a new web site, and gave it a single host header matching the dns entry, you would mitigate this issue altogether, and would not have to write custom code or add prefixes to your web.config file.