Programs & Examples On #Enhanced rich text

Disable time in bootstrap date time picker

This shows only date:

$('#myDateTimePicker').datetimepicker({
        format: 'dd.mm.yyyy',
        minView: 2,
        maxView: 4,
        autoclose: true
      });

More on the subject here

How to pass Multiple Parameters from ajax call to MVC Controller

You're making an HTTP POST, but trying to pass parameters with the GET query string syntax. In a POST, the data are passed as named parameters and do not use the param=value&foo=bar syntax. Using jQuery's ajax method lets you create a javascript object with the named parameters, like so:

$.ajax({
  url: '/Home/SaveChart',
  type: 'POST',
  async: false,
  dataType: 'text',
  processData: false,    
  data: { 
      input: JSON.stringify(IVRInstant.data), 
      name: $("#wrkname").val()
  },
  success: function (data) { }
});

What's the simplest way of detecting keyboard input in a script from the terminal?

This needs run as root: (Warning, this is a system-wide keylogger)

#!/usr/bin/python3

import signal
import keyboard
import time
import os


if not os.geteuid() == 0:
  print("This script needs to be run as root.")
  exit()

def exitNice(signum, frame):
  global running 
  running = False

def keyEvent(e):
  global running
  if e.event_type == "up":
    print("Key up: " + str(e.name))
  if e.event_type == "down":
    print("Key down: " + str(e.name))
  if e.name == "q":
    exitNice("", "")
    print("Quitting")

running = True
signal.signal(signal.SIGINT, exitNice)
keyboard.hook(keyEvent)

print("Press 'q' to quit")
fps = 1/24
while running:
  time.sleep(fps)

Spring Boot: Cannot access REST Controller on localhost (404)

I had this issue and what you need to do is fix your packages. If you downloaded this project from http://start.spring.io/ then you have your main class in some package. For example if the package for the main class is: "com.example" then and your controller must be in package: "com.example.controller". Hope this helps.

What is __stdcall?

I agree that all the answers so far are correct, but here is the reason. Microsoft's C and C++ compilers provide various calling conventions for (intended) speed of function calls within an application's C and C++ functions. In each case, the caller and callee must agree on which calling convention to use. Now, Windows itself provides functions (APIs), and those have already been compiled, so when you call them you must conform to them. Any calls to Windows APIs, and callbacks from Windows APIs, must use the __stdcall convention.

Fatal error: Cannot use object of type stdClass as array in

CodeIgniter returns result rows as objects, not arrays. From the user guide:

result()


This function returns the query result as an array of objects, or an empty array on failure.

You'll have to access the fields using the following notation:

foreach ($getvidids->result() as $row) {
    $vidid = $row->videoid;
}

Launching Spring application Address already in use

Using IntelliJ, I got this error when I tried to run a Spring app while there was one app already running. I had to stop the first one. After that, running the second app didn't return any errors.

How to write JUnit test with Spring Autowire?

A JUnit4 test with Autowired and bean mocking (Mockito):

// JUnit starts spring context
@RunWith(SpringRunner.class)
// spring load context configuration from AppConfig class
@ContextConfiguration(classes = AppConfig.class)
// overriding some properties with test values if you need
@TestPropertySource(properties = {
        "spring.someConfigValue=your-test-value",
})
public class PersonServiceTest {

    @MockBean
    private PersonRepository repository;

    @Autowired
    private PersonService personService; // uses PersonRepository    

    @Test
    public void testSomething() {
        // using Mockito
        when(repository.findByName(any())).thenReturn(Collection.emptyList());
        Person person = new Person();
        person.setName(null);

        // when
        boolean found = personService.checkSomething(person);

        // then
        assertTrue(found, "Something is wrong");
    }
}

C# Dictionary get item by index

Your key is a string and your value is an int. Your code won't work because it cannot look up the random int you pass. Also, please provide full code

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

Given a column of numbers:

lst = []
cols = ['A']
for a in range(100, 105):
    lst.append([a])
df = pd.DataFrame(lst, columns=cols, index=range(5))
df

    A
0   100
1   101
2   102
3   103
4   104

You can reference the previous row with shift:

df['Change'] = df.A - df.A.shift(1)
df

    A   Change
0   100 NaN
1   101 1.0
2   102 1.0
3   103 1.0
4   104 1.0

Reading a JSP variable from JavaScript

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

Reactive forms - disabled attribute

in Angular-9 if you want to disable/enable on button click here is a simple solution if you are using reactive forms.

define a function in component.ts file

//enable example you can use the same approach for disable with .disable()

toggleEnable() {
  this.yourFormName.controls.formFieldName.enable();
  console.log("Clicked")
} 

Call it from your component.html

e.g

<button type="button" data-toggle="form-control" class="bg-primary text-white btn- 
                reset" style="width:100%"(click)="toggleEnable()">

What does 'var that = this;' mean in JavaScript?

This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another this automatically gets set to the global scope. This can be confusing because you expect this to have the same value as in the outer function.

var car = {};
car.starter = {};

car.start = function(){
    var that = this;

    // you can access car.starter inside this method with 'this'
    this.starter.active = false;

    var activateStarter = function(){
        // 'this' now points to the global scope
        // 'this.starter' is undefined, so we use 'that' instead.
        that.starter.active = true;

        // you could also use car.starter, but using 'that' gives
        // us more consistency and flexibility
    };

    activateStarter();

};

This is specifically a problem when you create a function as a method of an object (like car.start in the example) then create a function inside that method (like activateStarter). In the top level method this points to the object it is a method of (in this case, car) but in the inner function this now points to the global scope. This is a pain.

Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name that is used. It's an easily recognizable convention for overcoming a shortcoming in the language.

Like El Ronnoco hints at Douglas Crockford thinks this is a good idea.

How to download Google Play Services in an Android emulator?

I came across another solution to use the Google play services on an emulator. The guys at http://www.genymotion.com/ provide very fast emulators on which you can install Google play services. They just need you to sign up to begin downloading and you need Virtual box installed. At the moment they cater for Android 16 and 17 but more are on the way.

Try-catch block in Jenkins pipeline script

This answer worked for me:

pipeline {
  agent any
  stages {
    stage("Run unit tests"){
      steps {
        script {
          try {
            sh  '''
              # Run unit tests without capturing stdout or logs, generates cobetura reports
              cd ./python
              nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
              cd ..
              '''
          } finally {
            junit 'nosetests.xml'
          }
        }
      }
    }
    stage ('Speak') {
      steps{
        echo "Hello, CONDITIONAL"
      }
    }
  }
}

Is it correct to use alt tag for an anchor link?

For anchors, you should use title instead. alt is not valid atribute of a. See http://w3schools.com/tags/tag_a.asp

How to rollback just one step using rake db:migrate

Roll back the most recent migration:

rake db:rollback

Roll back the n most recent migrations:

rake db:rollback STEP=n

You can find full instructions on the use of Rails migration tasks for rake on the Rails Guide for running migrations.


Here's some more:

  • rake db:migrate - Run all migrations that haven't been run already
  • rake db:migrate VERSION=20080906120000 - Run all necessary migrations (up or down) to get to the given version
  • rake db:migrate RAILS_ENV=test - Run migrations in the given environment
  • rake db:migrate:redo - Roll back one migration and run it again
  • rake db:migrate:redo STEP=n - Roll back the last n migrations and run them again
  • rake db:migrate:up VERSION=20080906120000 - Run the up method for the given migration
  • rake db:migrate:down VERSION=20080906120000 - Run the down method for the given migration

And to answer your question about where you get a migration's version number from:

The version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run

$ rake db:migrate VERSION=20080906120000

(From Running Migrations in the Rails Guides)

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

     <asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
                                                                    FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
                                                                    <ItemTemplate>
                                                                        <asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
                                                                            Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
                                                                    </ItemTemplate>
                                                                    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
                                                                    <ItemStyle HorizontalAlign="Center" Width="50px" />
                                                                    <FooterTemplate>
                                                                        <asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
                                                                    </FooterTemplate>
                                                                </asp:TemplateField>


 private void TotalExEmpOFMonth()
    {
        Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
        /*Sum of the  Total Amount Of month*/
        foreach (GridViewRow gvr in GrdPFRecord.Rows)
        {
            TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
            lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
            lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));



        }
    }

Re-sign IPA (iPhone)

None of these resigning approaches were working for me, so I had to work out something else.

In my case, I had an IPA with an expired certificate. I could have rebuilt the app, but because we wanted to ensure we were distributing exactly the same version (just with a new certificate), we did not want to rebuild it.

Instead of the ways of resigning mentioned in the other answers, I turned to Xcode’s method of creating an IPA, which starts with an .xcarchive from a build.

  1. I duplicated an existing .xcarchive and started replacing the contents. (I ignored the .dSYM file.)

  2. I extracted the old app from the old IPA file (via unzipping; the app is the only thing in the Payload folder)

  3. I moved this app into the new .xcarchive, under Products/Applications replacing the app that was there.

  4. I edited Info.plist, editing

    • ApplicationProperties/ApplicationPath
    • ApplicationProperties/CFBundleIdentifier
    • ApplicationProperties/CFBundleShortVersionString
    • ApplicationProperties/CFBundleVersion
    • Name
  5. I moved the .xcarchive into Xcode’s archive folder, usually /Users/xxxx/Library/Developer/Xcode/Archives.

  6. In Xcode, I opened the Organiser window, picked this new archive and did a regular (in this case Enterprise) export.

The result was a good IPA that works.

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to read xls with explicit implementation poi classes for xlsx.

G:\Selenium Jar Files\TestData\Data.xls

Either use HSSFWorkbook and HSSFSheet classes or make your implementation more generic by using shared interfaces, like;

Change:

XSSFWorkbook workbook = new XSSFWorkbook(file);

To:

 org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);

And Change:

XSSFSheet sheet = workbook.getSheetAt(0);

To:

org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

jQuery check if <input> exists and has a value

You can create your own custom selector :hasValue and then use that to find, filter, or test any other jQuery elements.

jQuery.expr[':'].hasValue = function(el,index,match) {
  return el.value != "";
};

Then you can find elements like this:

var data = $("form input:hasValue").serialize();

Or test the current element with .is()

var elHasValue = $("#name").is(":hasValue");

_x000D_
_x000D_
jQuery.expr[':'].hasValue = function(el) {_x000D_
  return el.value != "";_x000D_
};_x000D_
_x000D_
_x000D_
var data = $("form input:hasValue").serialize();_x000D_
console.log(data)_x000D_
_x000D_
_x000D_
var elHasValue = $("[name='LastName']").is(":hasValue");_x000D_
console.log(elHasValue)
_x000D_
label { display: block; margin-top:10px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
  <label>_x000D_
    First Name:_x000D_
    <input type="text" name="FirstName" value="Frida" />_x000D_
  </label>_x000D_
_x000D_
  <label>_x000D_
    Last Name:_x000D_
    <input type="text" name="LastName" />_x000D_
  </label>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Further Reading:

Listing available com ports with Python

Probably late, but might help someone in need.

import serial.tools.list_ports


class COMPorts:

    def __init__(self, data: list):
        self.data = data

    @classmethod
    def get_com_ports(cls):
        data = []
        ports = list(serial.tools.list_ports.comports())

        for port_ in ports:
            obj = Object(data=dict({"device": port_.device, "description": port_.description.split("(")[0].strip()}))
            data.append(obj)

        return cls(data=data)

    @staticmethod
    def get_description_by_device(device: str):
        for port_ in COMPorts.get_com_ports().data:
            if port_.device == device:
                return port_.description

    @staticmethod
    def get_device_by_description(description: str):
        for port_ in COMPorts.get_com_ports().data:
            if port_.description == description:
                return port_.device


class Object:
    def __init__(self, data: dict):
        self.data = data
        self.device = data.get("device")
        self.description = data.get("description")


if __name__ == "__main__":
    for port in COMPorts.get_com_ports().data:
        print(port.device)
        print(port.description)

    print(COMPorts.get_device_by_description(description="Arduino Leonardo"))
    print(COMPorts.get_description_by_device(device="COM3"))

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

In Windows 10 SQL Server 19 the solution is known.

Copy the following files:

  • libssl-1_1-x64.dll
  • libcrypto-1_1-x64.dll

from the folder

C:\Program Files\Microsoft SQL Server\MSSSQL15.MSSQLSERVER\PYTHON_SERVICES\Library\bin

to the folder

C:\Program Files\Microsoft SQL Server\MSSSQL15.MSSQLSERVER\PYTHON_SERVICES\DLLs

Then open a new DOS command shell prompt.

From https://docs.microsoft.com/en-us/sql/machine-learning/troubleshooting/known-issues-for-sql-server-machine-learning-services?view=sql-server-ver15#7-unable-to-install-python-packages-using-pip-after-installing-sql-server-2019-on-windows

Linking dll in Visual Studio

You don't add or link directly against a DLL, you link against the LIB produced by the DLL.

A LIB provides symbols and other necessary data to either include a library in your code (static linking) or refer to the DLL (dynamic linking).

To link against a LIB, you need to add it to the project Properties -> Linker -> Input -> Additional Dependencies list. All LIB files here will be used in linking. You can also use a pragma like so:

#pragma comment(lib, "dll.lib")

With static linking, the code is included in your executable and there are no runtime dependencies. Dynamic linking requires a DLL with matching name and symbols be available within the search path (which is not just the path or system directory).

Scale image to fit a bounding box

This helped me:

.img-class {
  width: <img width>;
  height: <img height>;
  content: url('/path/to/img.png');
}

Then on the element (you can use javascript or media queries to add responsiveness):

<div class='img-class' style='transform: scale(X);'></div>

Hope this helps!

adb doesn't show nexus 5 device

Try executing :

sudo ./adb kill-server

sudo ./adb start-server

sudo ./adb devices

Best practice for storing and protecting private API keys in applications

The only true way to keep these private is to keep them on your server, and have the app send whatever it is to the server, and the server interacts with Dropbox. That way you NEVER distribute your private key in any format.

Find Oracle JDBC driver in Maven repository

Please try below:

<dependency>
    <groupId>com.oracle.ojdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>19.3.0.0</version>
</dependency>

Creating a PHP header/footer

Just create the header.php file, and where you want to use it do:

<?php
include('header.php');
?>

Same with the footer. You don't need php tags in these files if you just have html.

See more about include here:

http://php.net/manual/en/function.include.php

Error: stray '\240' in program

SOLUTION: DELETE THAT LINE OF CODE [*IF YOU COPIED IT FROM ANOTHER SOURCE DOCUMENT] AND TYPE IT YOURSELF.

Error: stray '\240' in program is simply a character encoding error message.

From my experience, it is just a matter of character encoding. For example, if you copy a piece of code from a web page or you first write it in a text editor before copying and pasting in an IDE, it can come with the character encoding of the source document or editor.

Python handling socket.error: [Errno 104] Connection reset by peer

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)

So you can't do anything about it, it is the issue of the server.

But you could use try .. except block to handle that exception:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        raise # Not error we are looking for
    pass # Handle error here.

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Using regular expression in css?

An ID is meant to identify the element uniquely. Any styles applied to it should also be unique to that element. If you have styles you want to apply to many elements, you should add a class to them all, rather than relying on ID selectors...

<div id="sections">
   <div id="s1" class="sec">...</div>
   <div id="s2" class="sec">...</div>
   ...
</div>

and

.sec {
    ...
}

Or in your specific case you could select all divisions inside your parent container, if nothing else is inside it, like so:

#sections > div {
    ...
}

switch() statement usage

In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:

http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/

Personally, when I have 3 or more cases, I usually just go with case/switch.

How do files get into the External Dependencies in Visual Studio C++?

To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified  all '.lib' files & there names for current project.

So, Developer has to specify external dependencies for Project as below..

1. Select Project in Solution explorer.

2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".

3.  Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".

enter image description here enter image description here

CSS Circular Cropping of Rectangle Image

The approach is wrong, you need to apply the border-radius to the container div instead of the actual image.

This would work:

_x000D_
_x000D_
.image-cropper {
  width: 100px;
  height: 100px;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
}

img {
  display: inline;
  margin: 0 auto;
  height: 100%;
  width: auto;
}
_x000D_
<div class="image-cropper">
  <img src="https://via.placeholder.com/150" class="rounded" />
</div>
_x000D_
_x000D_
_x000D_

How can I convert tabs to spaces in every file of a directory?

Try the command line tool expand.

expand -i -t 4 input | sponge output

where

  • -i is used to expand only leading tabs on each line;
  • -t 4 means that each tab will be converted to 4 whitespace chars (8 by default).
  • sponge is from the moreutils package, and avoids clearing the input file.

Finally, you can use gexpand on OSX, after installing coreutils with Homebrew (brew install coreutils).

How do I make case-insensitive queries on Mongodb?

You can use Case Insensitive Indexes:

The following example creates a collection with no default collation, then adds an index on the name field with a case insensitive collation. International Components for Unicode

/*
* strength: CollationStrength.Secondary
* Secondary level of comparison. Collation performs comparisons up to secondary * differences, such as diacritics. That is, collation performs comparisons of 
* base characters (primary differences) and diacritics (secondary differences). * Differences between base characters takes precedence over secondary 
* differences.
*/
db.users.createIndex( { name: 1 }, collation: { locale: 'tr', strength: 2 } } )

To use the index, queries must specify the same collation.

db.users.insert( [ { name: "Oguz" },
                            { name: "oguz" },
                            { name: "OGUZ" } ] )

// does not use index, finds one result
db.users.find( { name: "oguz" } )

// uses the index, finds three results
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 2 } )

// does not use the index, finds three results (different strength)
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 1 } )

or you can create a collection with default collation:

db.createCollection("users", { collation: { locale: 'tr', strength: 2 } } )
db.users.createIndex( { name : 1 } ) // inherits the default collation

JavaScript: Alert.Show(message) From ASP.NET Code-behind

if you are using ScriptManager on the page then you can also try using this:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Your Message');", true);

Why can't decimal numbers be represented exactly in binary?

The root (mathematical) reason is that when you are dealing with integers, they are countably infinite.

Which means, even though there are an infinite amount of them, we could "count out" all of the items in the sequence, without skipping any. That means if we want to get the item in the 610000000000000th position in the list, we can figure it out via a formula.

However, real numbers are uncountably infinite. You can't say "give me the real number at position 610000000000000" and get back an answer. The reason is because, even between 0 and 1, there are an infinite number of values, when you are considering floating-point values. The same holds true for any two floating point numbers.

More info:

http://en.wikipedia.org/wiki/Countable_set

http://en.wikipedia.org/wiki/Uncountable_set

Update: My apologies, I appear to have misinterpreted the question. My response is about why we cannot represent every real value, I hadn't realized that floating point was automatically classified as rational.

Difference between web server, web container and application server

A Web application runs within a Web container of a Web server. The Web container provides the runtime environment through components that provide naming context and life cycle management. Some Web servers may also provide additional services such as security and concurrency control. A Web server may work with an EJB server to provide some of those services. A Web server, however, does not need to be located on the same machine as an EJB server.

Web applications are composed of web components and other data such as HTML pages. Web components can be servlets, JSP pages created with the JavaServer Pages™ technology, web filters, and web event listeners. These components typically execute in a web server and may respond to HTTP requests from web clients. Servlets, JSP pages, and filters may be used to generate HTML pages that are an application’s user interface. They may also be used to generate XML or other format data that is consumed by other application components.

Source: http://www.service-architecture.com/articles/application-servers/j2ee_web_server_or_container.html

List of <p:ajax> events

As the list of possible events is not tied to p:ajax itself but to the component it is used with, you'll have to ask the component for which ajax events it supports.

There are multiple ways to determine the ajax events for a given component:

1) Ask the component in xhtml:

You can output the list directly in xhtml by binding that component to a request scoped variable and printing the eventNames property:

<p:autoComplete binding="#{ac}"></p:autoComplete>
<h:outputText value="#{ac.eventNames}" />

This outputs

[blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup,
 mousedown, mousemove, mouseout, mouseover, mouseup, select, itemSelect,
 itemUnselect, query, moreText, clear]

2) Ask the component in java code:

Figure out the component implementation class and invoke its' implementation of javax.faces.component.UIComponentBase.getEventNames() method:

import javax.faces.component.UIComponentBase;

public class SomeTest {

    public static void main(String[] args) {
        dumpEvents(new org.primefaces.component.inputtext.InputText());
        dumpEvents(new org.primefaces.component.autocomplete.AutoComplete());
        dumpEvents(new org.primefaces.component.datatable.DataTable());
    }

    private static void dumpEvents(UIComponentBase comp) {
        System.out.println(
                comp + ":\n\tdefaultEvent: " + comp.getDefaultEventName() + ";\n\tEvents: " + comp.getEventNames());
    }

}

This outputs:

org.primefaces.component.inputtext.InputText@239963d8:
    defaultEvent: valueChange;
    Events: [blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup, select]
org.primefaces.component.autocomplete.AutoComplete@72d818d1:
    defaultEvent: valueChange;
    Events: [blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup, select, itemSelect, itemUnselect, query, moreText, clear]
org.primefaces.component.datatable.DataTable@614ddd49:
    defaultEvent: null;
    Events: [rowUnselect, colReorder, tap, rowEditInit, toggleSelect, cellEditInit, sort, rowToggle, cellEdit, rowSelectRadio, filter, cellEditCancel, rowSelect, contextMenu, taphold, rowReorder, colResize, rowUnselectCheckbox, rowDblselect, rowEdit, page, rowEditCancel, virtualScroll, rowSelectCheckbox]

3) 'rtfm' ;-)

Best option is to look into the documentation of the particular component in use as hopefully provided by the component developers, not limited to PrimeFaces btw. (p:ajax can be attached to any component providing ajax behaviors).

The advantage over previous suggestions is that the documentation not only provides the event names, but also enhanced description of the event potentially enriched with an event type class that can be caught by a listener.

For example the org.primefaces.event.SelectEvent in case of

<p:ajax event="itemSelect" listener="#{anyBean.onItemSelect}"/>

and listener method signature public void onItemSelect(SelectEvent) provides additional event contextual data.

Where there is no explicit list of ajax events on a compoment in the PrimeFaces documentation, the list of on* javascript callbacks can be used as events by removing the 'on' and using the remainder as an event name. The other answers in this question provides help on these plain dom events too.

How to declare and use 1D and 2D byte arrays in Verilog?

Verilog thinks in bits, so reg [7:0] a[0:3] will give you a 4x8 bit array (=4x1 byte array). You get the first byte out of this with a[0]. The third bit of the 2nd byte is a[1][2].

For a 2D array of bytes, first check your simulator/compiler. Older versions (pre '01, I believe) won't support this. Then reg [7:0] a [0:3] [0:3] will give you a 2D array of bytes. A single bit can be accessed with a[2][0][7] for example.

reg [7:0] a [0:3];
reg [7:0] b [0:3] [0:3];

reg [7:0] c;
reg d;

initial begin

   for (int i=0; i<=3; i++) begin
      a[i] = i[7:0];
   end

   c = a[0];
   d = a[1][2]; 


   // using 2D
   for (int i=0; i<=3; i++)
      for (int j=0; j<=3; j++)
          b[i][j] = i*j;  // watch this if you're building hardware

end

How do I install PIL/Pillow for Python 3.6?

You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:

pip install some-package.whl

If you have problem to install the wheel read this answer

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

The other answers in my case did not work. I had to restart windows before I could debug the application again.

Expand and collapse with angular js

You can solve this fully in the html:

<div>
  <input ng-model=collapse type=checkbox>Title
  <div ng-show=collapse>
     Only shown when checkbox is clicked
  </div>
</div>

This also works well with ng-repeat since it will create a local scope for each member.

<table>
  <tbody ng-repeat='m in members'>
    <tr>
       <td><input type=checkbox ng-model=collapse></td>
       <td>{{m.title}}</td>
    </tr>
    <tr ng-show=collapse>
      <td> </td>
      <td>{{ m.content }}</td>
    </tr>
  </tbody>
</table>

Be aware that even though a repeat has its own scope, initially it will inherit the value from collapse from super scopes. This allows you to set the initial value in one place but it can be surprising.

You can of course restyle the checkbox. See http://jsfiddle.net/azD5m/5/

Updated fiddle: http://jsfiddle.net/azD5m/374/ Original fiddle used closing </input> tags to add the HTML text label instead of using <label> tags.

What is the purpose of willSet and didSet in Swift?

NOTE

willSet and didSet observers are not called when a property is set in an initializer before delegation takes place

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

Here is a very good solution -> http://css-tricks.com/replace-the-image-in-an-img-with-css/

Pro(s) and Con(s):
(+) works with vector image that have relative width/height (a thing that RobAu's answer does not handle)
(+) is cross browser (works also for IE8+)
(+) it only uses CSS. So no need to modify the img src (or if you do not have access/do not want to change the already existing img src attribute).
(-) sorry, it does use the background css attribute :)

outline on only one border

You can use box-shadow to create an outline on one side. Like outline, box-shadow does not change the size of the box model.

This puts a line on top:

box-shadow: 0 -1px 0 #000;

I made a jsFiddle where you can check it out in action.


INSET

For an inset border, use the inset keyword. This puts an inset line on top:

box-shadow: 0 1px 0 #000 inset;

Multiple lines can be added using comma-separated statements. This puts an inset line on the top and the left:

box-shadow: 0 1px 0 #000 inset,
            1px 0 0 #000 inset;

For more details on how box-shadow works, check out the MDN page.

Picasso v/s Imageloader v/s Fresco vs Glide

These answers are totally my opinion

Answers

  1. Picasso is an easy to use image loader, same goes for Imageloader. Fresco uses a different approach to image loading, i haven't used it yet but it looks too me more like a solution for getting image from network and caching them then showing the images. then the other way around like Picasso/Imageloader/Glide which to me are more Showing image on screen that also does getting images from network and caching them.

  2. Glide tries to be somewhat interchangeable with Picasso.I think when they were created Picasso's mind set was follow HTTP spec's and let the server decide the caching policies and cache full sized and resize on demand. Glide is the same with following the HTTP spec but tries to have a smaller memory footprint by making some different assumptions like cache the resized images instead of the fullsized images, and show images with RGB_565 instead of RGB_8888. Both libraries offer full customization of the default settings.

  3. As to which library is the best to use is really hard to say. Picasso, Glide and Imageloader are well respected and well tested libraries which all are easy to use with the default settings. Both Picasso and Glide require only 1 line of code to load an image and have a placeholder and error image. Customizing the behaviour also doesn't require that much work. Same goes for Imageloader which is also an older library then Picasso and Glide, however I haven't used it so can't say much about performance/memory usage/customizations but looking at the readme on github gives me the impression that it is also relatively easy to use and setup. So in choosing any of these 3 libraries you can't make the wrong decision, its more a matter of personal taste. For fresco my opinion is that its another facebook library so we have to see how that is going to work out for them, so far there track record isn't that good. Like the facebook SDK is still isn't officially released on mavenCentral I have not used to facebook sdk since sept 2014 and it seems they have put the first version online on mavenCentral in oct 2014. So it will take some time before we can get any good opinion about it.

  4. between the 3 big name libraries I think there are no significant differences. The only one that stand out is fresco but that is because it has a different approach and is new and not battle tested.

How to add a boolean datatype column to an existing table in sql?

The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApprovednot bool AdminApproved.

If you need to create a bool (defaulting to false):

    ALTER TABLE person
    ADD AdminApproved BIT
    DEFAULT 0 NOT NULL;

Highlight the difference between two strings in PHP

Here is a short function you can use to diff two arrays. It implements the LCS algorithm:

function computeDiff($from, $to)
{
    $diffValues = array();
    $diffMask = array();

    $dm = array();
    $n1 = count($from);
    $n2 = count($to);

    for ($j = -1; $j < $n2; $j++) $dm[-1][$j] = 0;
    for ($i = -1; $i < $n1; $i++) $dm[$i][-1] = 0;
    for ($i = 0; $i < $n1; $i++)
    {
        for ($j = 0; $j < $n2; $j++)
        {
            if ($from[$i] == $to[$j])
            {
                $ad = $dm[$i - 1][$j - 1];
                $dm[$i][$j] = $ad + 1;
            }
            else
            {
                $a1 = $dm[$i - 1][$j];
                $a2 = $dm[$i][$j - 1];
                $dm[$i][$j] = max($a1, $a2);
            }
        }
    }

    $i = $n1 - 1;
    $j = $n2 - 1;
    while (($i > -1) || ($j > -1))
    {
        if ($j > -1)
        {
            if ($dm[$i][$j - 1] == $dm[$i][$j])
            {
                $diffValues[] = $to[$j];
                $diffMask[] = 1;
                $j--;  
                continue;              
            }
        }
        if ($i > -1)
        {
            if ($dm[$i - 1][$j] == $dm[$i][$j])
            {
                $diffValues[] = $from[$i];
                $diffMask[] = -1;
                $i--;
                continue;              
            }
        }
        {
            $diffValues[] = $from[$i];
            $diffMask[] = 0;
            $i--;
            $j--;
        }
    }    

    $diffValues = array_reverse($diffValues);
    $diffMask = array_reverse($diffMask);

    return array('values' => $diffValues, 'mask' => $diffMask);
}

It generates two arrays:

  • values array: a list of elements as they appear in the diff.
  • mask array: contains numbers. 0: unchanged, -1: removed, 1: added.

If you populate an array with characters, it can be used to compute inline difference. Now just a single step to highlight the differences:

function diffline($line1, $line2)
{
    $diff = computeDiff(str_split($line1), str_split($line2));
    $diffval = $diff['values'];
    $diffmask = $diff['mask'];

    $n = count($diffval);
    $pmc = 0;
    $result = '';
    for ($i = 0; $i < $n; $i++)
    {
        $mc = $diffmask[$i];
        if ($mc != $pmc)
        {
            switch ($pmc)
            {
                case -1: $result .= '</del>'; break;
                case 1: $result .= '</ins>'; break;
            }
            switch ($mc)
            {
                case -1: $result .= '<del>'; break;
                case 1: $result .= '<ins>'; break;
            }
        }
        $result .= $diffval[$i];

        $pmc = $mc;
    }
    switch ($pmc)
    {
        case -1: $result .= '</del>'; break;
        case 1: $result .= '</ins>'; break;
    }

    return $result;
}

Eg.:

echo diffline('StackOverflow', 'ServerFault')

Will output:

S<del>tackO</del><ins>er</ins>ver<del>f</del><ins>Fau</ins>l<del>ow</del><ins>t</ins> 

StackOerverfFaulowt

Additional notes:

  • The diff matrix requires (m+1)*(n+1) elements. So you can run into out of memory errors if you try to diff long sequences. In this case diff larger chunks (eg. lines) first, then diff their contents in a second pass.
  • The algorithm can be improved if you trim the matching elements from the beginning and the end, then run the algorithm on the differing middle only. A latter (more bloated) version contains these modifications too.

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

Substitute a comma with a line break in a cell

For some reason, none of the above worked for me. This DID however:

  1. Selected the range of cells I needed to replace.
  2. Go to Home > Find & Select > Replace or Ctrl + H
  3. Find what: ,
  4. Replace with: CTRL + SHIFT + J
  5. Click Replace All

Somehow CTRL + SHIFT + J is registered as a linebreak.

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

This is what I do on debian - I suspect it should work on ubuntu (amend the version as required + adapt the folder where you want to copy the JDK files as you wish, I'm using /opt/jdk):

wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u71-b15/jdk-8u71-linux-x64.tar.gz
sudo mkdir /opt/jdk
sudo tar -zxf jdk-8u71-linux-x64.tar.gz -C /opt/jdk/
rm jdk-8u71-linux-x64.tar.gz

Then update-alternatives:

sudo update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_71/bin/java 1
sudo update-alternatives --install /usr/bin/javac javac /opt/jdk/jdk1.8.0_71/bin/javac 1

Select the number corresponding to the /opt/jdk/jdk1.8.0_71/bin/java when running the following commands:

sudo update-alternatives --config java
sudo update-alternatives --config javac

Finally, verify that the correct version is selected:

java -version
javac -version

How to get the Facebook user id using the access token

You can use below code on onSuccess(LoginResult loginResult)

loginResult.getAccessToken().getUserId();

Why does Git treat this text file as a binary file?

If you have not set the type of a file, Git tries to determine it automatically and a file with really long lines and maybe some wide characters (e.g. Unicode) is treated as binary. With the .gitattributes file you can define how Git interpretes the file. Setting the diff attribute manually lets Git interprete the file content as text and will do an usual diff.

Just add a .gitattributes to your repository root folder and set the diff attribute to the paths or files. Here's an example:

src/Acme/DemoBundle/Resources/public/js/i18n/* diff
doc/Help/NothingToSay.yml                      diff
*.css                                          diff

If you want to check if there are attributes set on a file, you can do that with the help of git check-attr

git check-attr --all -- src/my_file.txt

Another nice reference about Git attributes could be found here.

How can I specify the required Node.js version in package.json?

Just like said Ibam, engineStrict is now deprecated. But I've found this solution:

check-version.js:

import semver from 'semver';
import { engines } from './package';

const version = engines.node;
if (!semver.satisfies(process.version, version)) {
  console.log(`Required node version ${version} not satisfied with current version ${process.version}.`);
  process.exit(1);
}

package.json:

{
  "name": "my package",
  "engines": {
    "node": ">=50.9" // intentionally so big version number
  },
  "scripts": {
    "requirements-check": "babel-node check-version.js",
    "postinstall": "npm run requirements-check"
  }
}

Find out more here: https://medium.com/@adambisek/how-to-check-minimum-required-node-js-version-4a78a8855a0f#.3oslqmig4

.nvmrc

And one more thing. A dotfile '.nvmrc' can be used for requiring specific node version - https://github.com/creationix/nvm#nvmrc

But, it is only respected by npm scripts (and yarn scripts).

Getting "conflicting types for function" in C, why?

You are trying to call do_something before you declare it. You need to add a function prototype before your printf line:

char* do_something(char*, const char*);

Or you need to move the function definition above the printf line. You can't use a function before it is declared.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Recently I came across a node/agent which had one executor occupied for days by a build "X" of a pipeline job, although that jobs page claimed build "X" did not exist anymore (discarded after 10 subsequent builds (!), as configured in the pipeline job). Verified that on disk: build "X" was really gone.

The solution: it was the agent/node which wrongly reported that the occupied executor was busy running build "X". Interrupting that executor's thread has immediately released it.

def executor = Jenkins.instance.getNode('NODENAME').computer.executors.find {
    it.isBusy() && it.name.contains('JOBNAME')
}

println executor?.name
if (executor?.isBusy()) executor.interrupt()

Other answers considered:

  • The answer from @cheffe: did not work (see next point, and update below).
  • The answers with Thread.getAllStackTraces(): no matching thread.
  • The answer from @levente-holló and all answers with getBuildByNumber(): did not apply as the build wasn't really there anymore!
  • The answer from @austinfromboston: that came close to my needs, but it would also have nuked any other builds running at the moment.

Update:
I experienced again a similar situation, where a Executor was occupied for days by a (still existing) finished pipeline build. This code snippet was the only working solution.

Difference between string and char[] types in C++

Arkaitz is correct that string is a managed type. What this means for you is that you never have to worry about how long the string is, nor do you have to worry about freeing or reallocating the memory of the string.

On the other hand, the char[] notation in the case above has restricted the character buffer to exactly 256 characters. If you tried to write more than 256 characters into that buffer, at best you will overwrite other memory that your program "owns". At worst, you will try to overwrite memory that you do not own, and your OS will kill your program on the spot.

Bottom line? Strings are a lot more programmer friendly, char[]s are a lot more efficient for the computer.

AngularJS access scope from outside js function

we can call it after loaded

http://jsfiddle.net/gentletech/s3qtv/3/

<div id="wrap" ng-controller="Ctrl">
    {{message}}<br>
    {{info}}
    </div>
    <a  onClick="hi()">click me </a>

    function Ctrl($scope) {
        $scope.message = "hi robi";
        $scope.updateMessage = function(_s){
            $scope.message = _s;    
        };
    }

function hi(){
    var scope = angular.element(document.getElementById("wrap")).scope();
        scope.$apply(function() {
        scope.info = "nami";
        scope.updateMessage("i am new fans like nami");
    });
}

Removing special characters VBA Excel

Here is how removed special characters.

I simply applied regex

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

Use JSTL forEach loop's varStatus as an ID

you'd use any of these:

JSTL c:forEach varStatus properties

Property Getter Description

  • current getCurrent() The item (from the collection) for the current round of iteration.

  • index getIndex() The zero-based index for the current round of iteration.

  • count getCount() The one-based count for the current round of iteration

  • first isFirst() Flag indicating whether the current round is the first pass through the iteration
  • last isLast() Flag indicating whether the current round is the last pass through the iteration

  • begin getBegin() The value of the begin attribute

  • end getEnd() The value of the end attribute

  • step getStep() The value of the step attribute

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

Getting the location from an IP address

Ipdata.co is a fast, highly available IP Geolocation API with reliable performance.

It's extremely scalable with 10 endpoints around the world each able to handle >10,000 requests per second!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

In php

php > $ip = '8.8.8.8';
php > $details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}?api-key=test"));
php > echo $details->region;
California
php > echo $details->city;
Mountain View
php > echo $details->country_name;
United States
php > echo $details->latitude;
37.751

Here's a client-side example showing how you'd get the country, region and city;

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
 $("#response").html(JSON.stringify(response, null, 4));_x000D_
  $("#country").html('Country: ' + response.country_name);_x000D_
  $("#region").html('Region ' + response.region);_x000D_
  $("#city").html('City' + response.city);  _x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="country"></div>_x000D_
<div id="region"></div>_x000D_
<div id="city"></div>_x000D_
<pre id="response"></pre>
_x000D_
_x000D_
_x000D_

Disclaimer;

I built the service.

For examples in multiple languages see the Docs

Also see this detailed analysis of the best IP Geolocation APIs.

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

If above all options are not working and you have used nuget packages like Microsoft.Net.Compilers and CodeDom and still not working then there is issue with your project file open project file. Project file is using one of the compiler option which not support your selected language. Open project file with notepad++ and remove the following line.

Orignal Project File

<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="..\packages\Microsoft.Net.Compilers.Toolset.3.7.0\build\Microsoft.Net.Compilers.Toolset.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.Toolset.3.7.0\build\Microsoft.Net.Compilers.Toolset.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.3.7.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.3.7.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')" />
  <!--Don't delete below one-->
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />

Remove The following lines

  <Import Project="..\packages\Microsoft.Net.Compilers.Toolset.3.7.0\build\Microsoft.Net.Compilers.Toolset.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.Toolset.3.7.0\build\Microsoft.Net.Compilers.Toolset.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.3.7.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.3.7.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')" />

How to remove provisioning profiles from Xcode

. Simple Steps:

1:Click finder

2:Right click on Finder
3:click on goto folder

4: Paste in Search : ~/Library/MobileDevice/Provisioning Profiles

5:Click on Go

6:List of the Profiles .you can delete any one

Thanks

You'll want to restart XCode to refresh the list.

How to install bcmath module?

Try yum install php-bcmath. If you still can't find anything, try yum search bcmath to find the package name

How to search by key=>value in a multidimensional array in PHP

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

Rails: Can't verify CSRF token authenticity when making a POST request

If you want to exclude the sample controller's sample action

class TestController < ApplicationController
  protect_from_forgery :except => [:sample]

  def sample
     render json: @hogehoge
  end
end

You can to process requests from outside without any problems.

What's the difference between Sender, From and Return-Path?

The official RFC which defines this specification could be found here:

http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)

2.1.2. Header Field: From

Description:  
    Mailbox of message author  
[...]  
Related information:
    Specifies the author(s) of the message; that is, the mailbox(es)
    of the person(s) or system(s) responsible for the writing of the
    message. Defined as standard by RFC 822.

2.1.3. Header Field: Sender

Description:  
    Mailbox of message sender  
[...]  
Related information:
    Specifies the mailbox of the agent responsible for the actual
    transmission of the message.  Defined as standard by RFC 822.

2.1.22. Header Field: Return-Path

Description:
    Message return path
[...]  
Related information:
    Return path for message response diagnostics. See also RFC 2821
    [17]. Defined as standard by RFC 822.

SELECT DISTINCT on one column

try this:

SELECT 
    t.*
    FROM TestData t
        INNER JOIN (SELECT
                        MIN(ID) as MinID
                        FROM TestData
                        WHERE SKU LIKE 'FOO-%'
                   ) dt ON t.ID=dt.MinID

EDIT
once the OP corrected his samle output (previously had only ONE result row, now has all shown), this is the correct query:

declare @TestData table (ID int, sku char(6), product varchar(15))
insert into @TestData values (1 ,  'FOO-23'      ,'Orange')
insert into @TestData values (2 ,  'BAR-23'      ,'Orange')
insert into @TestData values (3 ,  'FOO-24'      ,'Apple')
insert into @TestData values (4 ,  'FOO-25'      ,'Orange')

--basically the same as @Aaron Alton's answer:
SELECT
    dt.ID, dt.SKU, dt.Product
    FROM (SELECT
              ID, SKU, Product, ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowID
              FROM @TestData
              WHERE  SKU LIKE 'FOO-%'
         ) AS dt
    WHERE dt.RowID=1
    ORDER BY dt.ID

Calling one Activity from another in Android

check the following code to call one activity from another.

Intent intent = new Intent(CurrentActivity.this, OtherActivity.class);
CurrentActivity.this.startActivity(intent);

I need to learn Web Services in Java. What are the different types in it?

The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.

The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.

The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()

SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.

The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html

psql: FATAL: Peer authentication failed for user "dev"

This works for me when I run into it:

sudo -u username psql

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

Getting "project" nuget configuration is invalid error

Simply restarting Visual Studio worked for me.

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

Well try ini_set('memory_limit', '256M');

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

Conversion of System.Array to List

There is also a constructor overload for List that will work... But I guess this would required a strong typed array.

//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);

... for Array class

var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
    intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);

possibly undefined macro: AC_MSG_ERROR

I have experienced this same problem under CentOS 7

In may case, the problem went off after installation of libcurl-devel (libcurl was already installed on this machine)

How to initialise memory with new operator in C++?

std::fill is one way. Takes two iterators and a value to fill the region with. That, or the for loop, would (I suppose) be the more C++ way.

For setting an array of primitive integer types to 0 specifically, memset is fine, though it may raise eyebrows. Consider also calloc, though it's a bit inconvenient to use from C++ because of the cast.

For my part, I pretty much always use a loop.

(I don't like to second-guess people's intentions, but it is true that std::vector is, all things being equal, preferable to using new[].)

Get type of a generic parameter in Java with reflection

Nope, that is not possible. Due to downwards compatibility issues, Java's generics are based on type erasure, i.a. at runtime, all you have is a non-generic List object. There is some information about type parameters at runtime, but it resides in class definitions (i.e. you can ask "what generic type does this field's definition use?"), not in object instances.

Detecting when user scrolls to bottom of div with jQuery

Here's another version.

The key code is function scroller() which takes input as the height of the div containing the scrolling section, using overflow:scroll. It approximates 5px from the top or 10px from the bottom as at the top or bottom. Otherwise it's too sensitive. It seems 10px is about the minimum. You'll see it adds 10 to the div height to get the bottom height. I assume 5px might work, I didn't test extensively. YMMV. scrollHeight returns the height of the inner scrolling area, not the displayed height of the div, which in this case is 400px.

<?php

$scrolling_area_height=400;
echo '
<script type="text/javascript">
          function scroller(ourheight) {
            var ourtop=document.getElementById(\'scrolling_area\').scrollTop;
            if (ourtop > (ourheight-\''.($scrolling_area_height+10).'\')) {
                alert(\'at the bottom; ourtop:\'+ourtop+\' ourheight:\'+ourheight);
            }
            if (ourtop <= (5)) {
                alert(\'Reached the top\');
            }
          }
</script>

<style type="text/css">
.scroller { 
            display:block;
            float:left;
            top:10px;
            left:10px;
            height:'.$scrolling_area_height.';
            border:1px solid red;
            width:200px;
            overflow:scroll; 
        }
</style>

$content="your content here";

<div id="scrolling_area" class="scroller">
onscroll="var ourheight=document.getElementById(\'scrolling_area\').scrollHeight;
        scroller(ourheight);"
        >'.$content.'
</div>';

?>

How to join (merge) data frames (inner, outer, left, right)

You can do joins as well using Hadley Wickham's awesome dplyr package.

library(dplyr)

#make sure that CustomerId cols are both type numeric
#they ARE not using the provided code in question and dplyr will complain
df1$CustomerId <- as.numeric(df1$CustomerId)
df2$CustomerId <- as.numeric(df2$CustomerId)

Mutating joins: add columns to df1 using matches in df2

#inner
inner_join(df1, df2)

#left outer
left_join(df1, df2)

#right outer
right_join(df1, df2)

#alternate right outer
left_join(df2, df1)

#full join
full_join(df1, df2)

Filtering joins: filter out rows in df1, don't modify columns

semi_join(df1, df2) #keep only observations in df1 that match in df2.
anti_join(df1, df2) #drops all observations in df1 that match in df2.

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

For me I did enter a invalid url like : orcl only instead of jdbc:oracle:thin:@//localhost:1521/orcl

How to select current date in Hive SQL

The functions current_date and current_timestamp are now available in Hive 1.2.0 and higher, which makes the code a lot cleaner.

vue.js 'document.getElementById' shorthand

Theres no shorthand way in vue 2.

Jeff's method seems already deprecated in vue 2.

Heres another way u can achieve your goal.

_x000D_
_x000D_
 var app = new Vue({_x000D_
    el:'#app',_x000D_
    methods: {    _x000D_
        showMyDiv() {_x000D_
           console.log(this.$refs.myDiv);_x000D_
        }_x000D_
    }_x000D_
    _x000D_
   });
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
   <div id="myDiv" ref="myDiv"></div>_x000D_
   <button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I return an empty IEnumerable?

As for me, most elegant way is yield break

Mysql Compare two datetime fields

Your query apparently returned all correct dates, even considering the time.

If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.

Make sure your mydate column is a datetime type.

Launch an app from within another (iPhone)

In Swift

Just in case someone was looking for a quick Swift copy and paste.

if let url = NSURL(string: "app://") where UIApplication.sharedApplication().canOpenURL(url) {
            UIApplication.sharedApplication().openURL(url)
} else if let itunesUrl = NSURL(string: "https://itunes.apple.com/itunes-link-to-app") where UIApplication.sharedApplication().canOpenURL(itunesUrl) {
            UIApplication.sharedApplication().openURL(itunesUrl)      
}

Where is my m2 folder on Mac OS X Mavericks

Go to finder:

Press on keyboard CMD+shift+G . it will show u a popup like this

Enter path ~/.m2

press enter.

WebDriver - wait for element using Java

This is how I do it in my code.

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

or

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

to be precise.

See also:

C read file line by line

In your readLine function, you return a pointer to the line array (Strictly speaking, a pointer to its first character, but the difference is irrelevant here). Since it's an automatic variable (i.e., it's “on the stack”), the memory is reclaimed when the function returns. You see gibberish because printf has put its own stuff on the stack.

You need to return a dynamically allocated buffer from the function. You already have one, it's lineBuffer; all you have to do is truncate it to the desired length.

    lineBuffer[count] = '\0';
    realloc(lineBuffer, count + 1);
    return lineBuffer;
}

ADDED (response to follow-up question in comment): readLine returns a pointer to the characters that make up the line. This pointer is what you need to work with the contents of the line. It's also what you must pass to free when you've finished using the memory taken by these characters. Here's how you might use the readLine function:

char *line = readLine(file);
printf("LOG: read a line: %s\n", line);
if (strchr(line, 'a')) { puts("The line contains an a"); }
/* etc. */
free(line);
/* After this point, the memory allocated for the line has been reclaimed.
   You can't use the value of `line` again (though you can assign a new value
   to the `line` variable if you want). */

Is it bad practice to use break to exit a loop in Java?

Good lord no. Sometimes there is a possibility that something can occur in the loop that satisfies the overall requirement, without satisfying the logical loop condition. In that case, break is used, to stop you cycling around a loop pointlessly.

Example

String item;

for(int x = 0; x < 10; x++)
{
    // Linear search.
    if(array[x].equals("Item I am looking for"))
    {
       //you've found the item. Let's stop.
       item = array[x];
       break; 
    }
}

What makes more sense in this example. Continue looping to 10 every time, even after you've found it, or loop until you find the item and stop? Or to put it into real world terms; when you find your keys, do you keep looking?

Edit in response to comment

Why not set x to 11 to break the loop? It's pointless. We've got break! Unless your code is making the assumption that x is definitely larger than 10 later on (and it probably shouldn't be) then you're fine just using break.

Edit for the sake of completeness

There are definitely other ways to simulate break. For example, adding extra logic to your termination condition in your loop. Saying that it is either loop pointlessly or use break isn't fair. As pointed out, a while loop can often achieve similar functionality. For example, following the above example..

while(x < 10 && item == null)
{
    if(array[x].equals("Item I am looking for"))
    {
        item = array[x];
    }

    x++;
}

Using break simply means you can achieve this functionality with a for loop. It also means you don't have to keep adding in conditions into your termination logic, whenever you want the loop to behave differently. For example.

for(int x = 0; x < 10; x++)
{
   if(array[x].equals("Something that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("Something else that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("This is what I want"))
   {
       item = array[x];
   }
}

Rather than a while loop with a termination condition that looks like this:

while(x < 10 && !array[x].equals("Something that will make me want to cancel") && 
                !array[x].equals("Something else that will make me want to cancel"))

Failure [INSTALL_FAILED_INVALID_APK]

If you have multiple modules project with multiple flavors and each flavor has a different applicationId then you have to make sure that all your modules are targeting the same build variant.
Active Build Variant from Android Studio

How to set Angular 4 background image?

I wanted a profile picture of size 96x96 with data from api. The following solution worked for me in project Angular 7.

.ts:

  @Input() profile;

.html:

 <span class="avatar" [ngStyle]="{'background-image': 'url('+ profile?.public_picture +')'}"></span>

.scss:

 .avatar {
      border-radius: 100%;
      background-size: cover;
      background-position: center center;
      background-repeat: no-repeat;
      width: 96px;
      height: 96px;
    }

Please note that if you write background instead of 'background-image' in [ngStyle], the styles you write (even in style of element) for other background properties like background-position/size, etc. won't work. Because you will already fix it's properties with background: 'url(+ property +) (no providers for size, position, etc. !)'. The [ngStyle] priority is higher than style of element. In background here, only url() property will work. Be sure to use 'background-image' instead of 'background'in case you want to write more properties to background image.

How to model type-safe enum types?

There are many ways of doing.

1) Use symbols. It won't give you any type safety, though, aside from not accepting non-symbols where a symbol is expected. I'm only mentioning it here for completeness. Here's an example of usage:

def update(what: Symbol, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case 'row => replaceRow(where, newValue)
    case 'col | 'column => replaceCol(where, newValue)
    case _ => throw new IllegalArgumentException
  }

// At REPL:   
scala> val a = unitMatrixInt(3)
a: teste7.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a('row, 1) = a.row(0)
res41: teste7.MatrixInt =
/ 1 0 0 \
| 1 0 0 |
\ 0 0 1 /

scala> a('column, 2) = a.row(0)
res42: teste7.MatrixInt =
/ 1 0 1 \
| 0 1 0 |
\ 0 0 0 /

2) Using class Enumeration:

object Dimension extends Enumeration {
  type Dimension = Value
  val Row, Column = Value
}

or, if you need to serialize or display it:

object Dimension extends Enumeration("Row", "Column") {
  type Dimension = Value
  val Row, Column = Value
}

This can be used like this:

def update(what: Dimension, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case Row => replaceRow(where, newValue)
    case Column => replaceCol(where, newValue)
  }

// At REPL:
scala> a(Row, 2) = a.row(1)
<console>:13: error: not found: value Row
       a(Row, 2) = a.row(1)
         ^

scala> a(Dimension.Row, 2) = a.row(1)
res1: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

scala> import Dimension._
import Dimension._

scala> a(Row, 2) = a.row(1)
res2: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

Unfortunately, it doesn't ensure that all matches are accounted for. If I forgot to put Row or Column in the match, the Scala compiler wouldn't have warned me. So it gives me some type safety, but not as much as can be gained.

3) Case objects:

sealed abstract class Dimension
case object Row extends Dimension
case object Column extends Dimension

Now, if I leave out a case on a match, the compiler will warn me:

MatrixInt.scala:70: warning: match is not exhaustive!
missing combination         Column

    what match {
    ^
one warning found

It's used pretty much the same way, and doesn't even need an import:

scala> val a = unitMatrixInt(3)
a: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a(Row,2) = a.row(0)
res15: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 1 0 0 /

You might wonder, then, why ever use an Enumeration instead of case objects. As a matter of fact, case objects do have advantages many times, such as here. The Enumeration class, though, has many Collection methods, such as elements (iterator on Scala 2.8), which returns an Iterator, map, flatMap, filter, etc.

This answer is essentially a selected parts from this article in my blog.

window.close and self.close do not close the window in Chrome

This might be old, but let's answer it.

I use top.close() to close a tab. window.close() or other open...close didn't work for me.

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

Set value for particular cell in pandas DataFrame with iloc

To modify the value in a cell at the intersection of row "r" (in column "A") and column "C"

  1. retrieve the index of the row "r" in column "A"

        i = df[ df['A']=='r' ].index.values[0]
    
  2. modify the value in the desired column "C"

        df.loc[i,"C"]="newValue"
    

Note: before, be sure to reset the index of rows ...to have a nice index list!

        df=df.reset_index(drop=True)

how to start stop tomcat server using CMD?

You can use the following command c:\path of you tomcat directory\bin>catalina run

Null check in an enhanced for loop

I have modified the above answer, so you don't need to cast from Object

public static <T> List<T> safeClient( List<T> other ) {
            return other == null ? Collections.EMPTY_LIST : other;
}

and then simply call the List by

for (MyOwnObject ownObject : safeClient(someList)) {
    // do whatever
}

Explaination: MyOwnObject: If List<Integer> then MyOwnObject will be Integer in this case.

End of File (EOF) in C

EOF is -1 because that's how it's defined. The name is provided by the standard library headers that you #include. They make it equal to -1 because it has to be something that can't be mistaken for an actual byte read by getchar(). getchar() reports the values of actual bytes using positive number (0 up to 255 inclusive), so -1 works fine for this.

The != operator means "not equal". 0 stands for false, and anything else stands for true. So what happens is, we call the getchar() function, and compare the result to -1 (EOF). If the result was not equal to EOF, then the result is true, because things that are not equal are not equal. If the result was equal to EOF, then the result is false, because things that are equal are not (not equal).

The call to getchar() returns EOF when you reach the "end of file". As far as C is concerned, the 'standard input' (the data you are giving to your program by typing in the command window) is just like a file. Of course, you can always type more, so you need an explicit way to say "I'm done". On Windows systems, this is control-Z. On Unix systems, this is control-D.

The example in the book is not "wrong". It depends on what you actually want to do. Reading until EOF means that you read everything, until the user says "I'm done", and then you can't read any more. Reading until '\n' means that you read a line of input. Reading until '\0' is a bad idea if you expect the user to type the input, because it is either hard or impossible to produce this byte with a keyboard at the command prompt :)

Get the year from specified date php

I would use this:

$parts = explode('-', '2068-06-15');
echo $parts[0];

It appears the date is coming from a source where it is always the same, much quicker this way using explode.

Using Django time/date widgets in custom form

My Django Setup : 1.11 Bootstrap: 3.3.7

Since none of the answers are completely clear, I am sharing my template code which presents no errors at all.

Top Half of template:

{% extends 'base.html' %}
{% load static %}
{% load i18n %}

{% block head %}
    <title>Add Interview</title>
{% endblock %}

{% block content %}

<script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<script type="text/javascript" src="{% static 'js/jquery.js' %}"></script>

Bottom Half:

<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.min.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/jquery.init.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/actions.min.js' %}"></script>
{% endblock %}

Omitting one Setter/Getter in Lombok

with lombak 1.8.12, this worked for me

@Getter(value = lombok.AccessLevel.NONE)
@Setter(value = lombok.AccessLevel.NONE)

private int password;

Equivalent to 'app.config' for a library (DLL)

I took a look at the AppDomain instead of the assembly. This has the benefit of working inside static methods of a library. Link seems to work great for getting the key value as suggested by the other answers here.

public class DLLConfig
{
    public static string GetSettingByKey(AppDomain currentDomain, string configName, string key)
    {
        string value = string.Empty;
        try
        {  
            string exeConfigPath = (currentDomain.RelativeSearchPath ?? currentDomain.BaseDirectory) + "\\" + configName;
            if (File.Exists(exeConfigPath))
            {
                using (Stream stream = File.OpenRead(exeConfigPath))
                {
                    XDocument xdoc = XDocument.Load(stream);
                    XElement element = xdoc.Element("configuration").Element("appSettings").Elements().First(a => a.Attribute("key").Value == key);
                    value = element.Attribute("value").Value;
                }
            }

        }
        catch (Exception ex)
        {
                
        }
        return value;
            
    }
}

Use it within your library class like so;

namespace ProjectName
{
     public class ClassName
     {
         public static string SomeStaticMethod()
         {
             string value = DLLConfig.GetSettingByKey(AppDomain.CurrentDomain,"ProjectName.dll.config", "keyname");
         }
     }
}

Xcode Simulator: how to remove older unneeded devices?

In addition to @childno.de answer, your Mac directory

/private/var/db/receipts/

may still contains obsolete iPhoneSimulatorSDK .bom and .plist files like this:

/private/var/db/receipts/com.apple.pkg.iPhoneSimulatorSDK8_4.bom /private/var/db/receipts/com.apple.pkg.iPhoneSimulatorSDK8_4.plist

These could make your Downloads tab of Xcode's preferences show a tick (v) for that obsolete simulator version.

To purge the unwanted simulators, you can do a search using this bash command from your Mac terminal:

sudo find / -name "*PhoneSimulator*"

Then go to corresponding directories to manually delete unwanted SimulatorSDKs

Getting a 'source: not found' error when using source in a bash script

If you're writing a bash script, call it by name:

#!/bin/bash

/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).

The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.

Searching a string in eclipse workspace

eclipse instasearch plugin is a very useful plugin for search needs inside eclipse. It is based on lucene. This is also available in eclipse marketplace.

It has extensive feature set.

  • Instantly shows search results
  • Shows a preview using relevant lines
  • Periodically updates the index
  • Matches partial words (e.g. case in CamelCase)
  • Opens and highlights matches in files
  • Searches JAR source attachments
  • Supports filtering by extension/project/working set

Android ImageButton with a selected state?

if (iv_new_pwd.isSelected()) {
                iv_new_pwd.setSelected(false);
                Log.d("mytag", "in case 1");
                edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT);
            } else {
                Log.d("mytag", "in case 1");
                iv_new_pwd.setSelected(true);
                edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }

Python sys.argv lists and indexes

In a nutshell, sys.argv is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0], and the second element (first argument, if there is one) is sys.argv[1], etc.

The test len(sys.argv) >= 2 simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.

Get age from Birthdate

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

function getAge(dateString) 
{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    {
        age--;
    }
    return age;
}

See Demo.

How to merge many PDF files into a single one?

First, get Pdftk:

sudo apt-get install pdftk

Now, as shown on example page, use

pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf

for merging pdf files into one.

JavaScript is in array

Assuming that you're only using the array for lookup, you can use a Set (introduced in ES6), which allows you to find an element in O(1), meaning that lookup is sublinear. With the traditional methods of .includes() and .indexOf(), you still may need to look at all 500 (ie: N) elements in your array if the item specified doesn't exist in the array (or is the last item). This can be inefficient, however, with the help of a Set, you don't need to look at all elements, and instead, instantly check if the element is within your set:

_x000D_
_x000D_
const blockedTile = new Set(["118", "67", "190", "43", "135", "520"]);

if(blockedTile.has("118")) {
  // 118 is in your Set
  console.log("Found 118");
}
_x000D_
_x000D_
_x000D_

If for some reason you need to convert your set back into an array, you can do so through the use of Array.from() or the spread syntax (...), however, this will iterate through the entire set's contents (which will be O(N)). Sets also don't keep duplicates, meaning that your array won't contain duplicate items.

how to console.log result of this ajax call?

You could try something like this (copied from the jQuery Ajax examples)

var request = $.ajax({
  url: "script.php",
  type: "POST",
  data: {id : menuId},
  dataType: "html"
});

request.done(function(msg) {
  console.log( msg );
});

request.fail(function(jqXHR, textStatus) {
  console.log( "Request failed: " + textStatus );
});

The problem with your original code is that the error argument you pass into your on function isn't actually coming from anywhere. JQuery on doesn't return a second argument, and even if it did, it would relate to the click event not the Ajax call.

How exactly do you configure httpOnlyCookies in ASP.NET?

If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:

<httpCookies httpOnlyCookies="true"/>

Make Font Awesome icons in a circle?

The below example didnt quite work for me,this is the version that i made work!

HTML:

<div class="social-links">
    <a href="#"><i class="fa fa-facebook fa-lg"></i></a>
    <a href="#"><i class="fa fa-twitter fa-lg"></i></a>
    <a href="#"><i class="fa fa-google-plus fa-lg"></i></a>
    <a href="#"><i class="fa fa-pinterest fa-lg"></i></a>
</div>

CSS:

.social-links {
    text-align:center;
}

.social-links a{
    display: inline-block;
    width:50px;
    height: 50px;
    border: 2px solid #909090;
    border-radius: 50px;
    margin-right: 15px;

}
.social-links a i{
    padding: 18px 11px;
    font-size: 20px;
    color: #909090;
}

How to call any method asynchronously in c#

Check out the MSDN article Asynchronous Programming with Async and Await if you can afford to play with new stuff. It was added to .NET 4.5.

Example code snippet from the link (which is itself from this MSDN sample code project):

// Three things to note in the signature: 
//  - The method has an async modifier.  
//  - The return type is Task or Task<T>. (See "Return Types" section.)
//    Here, it is Task<int> because the return statement returns an integer. 
//  - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync. 
    //  - AccessTheWebAsync can't continue until getStringTask is complete. 
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
    //  - Control resumes here when getStringTask is complete.  
    //  - The await operator then retrieves the string result from getStringTask. 
    string urlContents = await getStringTask;

    // The return statement specifies an integer result. 
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
    return urlContents.Length;
}

Quoting:

If AccessTheWebAsync doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.

string urlContents = await client.GetStringAsync();

More details are in the link.

Origin http://localhost is not allowed by Access-Control-Allow-Origin

This approach resolved my issue to allow multiple domain

app.use(function(req, res, next) {
      var allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
      var origin = req.headers.origin;
      if(allowedOrigins.indexOf(origin) > -1){
           res.setHeader('Access-Control-Allow-Origin', origin);
      }
      //res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.header('Access-Control-Allow-Credentials', true);
      return next();
    });

How do I properly compare strings in C?

You can't compare arrays directly like this

array1==array2

You should compare them char-by-char; for this you can use a function and return a boolean (True:1, False:0) value. Then you can use it in the test condition of the while loop.

Try this:

#include <stdio.h>
int checker(char input[],char check[]);
int main()
{
    char input[40];
    char check[40];
    int i=0;
    printf("Hello!\nPlease enter a word or character:\n");
    scanf("%s",input);
    printf("I will now repeat this until you type it back to me.\n");
    scanf("%s",check);

    while (!checker(input,check))
    {
        printf("%s\n", input);
        scanf("%s",check);
    }

    printf("Good bye!");

    return 0;
}

int checker(char input[],char check[])
{
    int i,result=1;
    for(i=0; input[i]!='\0' || check[i]!='\0'; i++) {
        if(input[i] != check[i]) {
            result=0;
            break;
        }
    }
    return result;
}

Switch role after connecting to database

If someone still needs it (like I do).

The specified role_name must be a role that the current session user is a member of. https://www.postgresql.org/docs/10/sql-set-role.html

We need to make the current session user a member of the role:

create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;

produces:

Role ROLE created.


Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"

Grant succeeded.


Role SET succeeded.

Where is nodejs log file?

forever might be of interest to you. It will run your .js-File 24/7 with logging options. Here are two snippets from the help text:

[Long Running Process] The forever process will continue to run outputting log messages to the console. ex. forever -o out.log -e err.log my-script.js

and

[Daemon] The forever process will run as a daemon which will make the target process start in the background. This is extremely useful for remote starting simple node.js scripts without using nohup. It is recommended to run start with -o -l, & -e. ex. forever start -l forever.log -o out.log -e err.log my-daemon.js forever stop my-daemon.js

CSS text-transform capitalize on all caps

If the data is coming from a database, as in my case, you can lower it before sending it to a select list/drop down list. Shame you can't do it in CSS.

JavaScript onclick redirect

There are several issues in your code :

  • You are handling the click event of a submit button, whose default behavior is to post a request to the server and reload the page. You have to inhibit this behavior by returning false from your handler:

    onclick="SubmitFrm(); return false;"
    
  • value cannot be called because it is a property, not a method:

    var Searchtxt = document.getElementById("txtSearch").value;
    
  • The search query you are sending in the query string has to be encoded:

    window.location = "http://www.mysite.com/search/?Query="
        + encodeURIComponent(Searchtxt);
    

How to open a WPF Popup when another control is clicked, using XAML markup only?

I had some issues with the MouseDown part of this, but here is some code that might get your started.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Control VerticalAlignment="Top">
            <Control.Template>
                <ControlTemplate>
                    <StackPanel>
                    <TextBox x:Name="MyText"></TextBox>
                    <Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
                        <Border Background="Red">
                            <TextBlock>Test Popup Content</TextBlock>
                        </Border>
                    </Popup>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Control.Template>
        </Control>
    </Grid>
</Window>

Using "If cell contains #N/A" as a formula condition.

"N/A" is not a string it is an error, try this:

=if(ISNA(A1),C1)

you have to place this fomula in cell B1 so it will get the value of your formula

Intersect Two Lists in C#

public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
    return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
                .Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}

The container 'Maven Dependencies' references non existing library - STS

I have solved it using "force update", pressing Alt+F5 as it is mentioned in the following link.

How to use a variable inside a regular expression?

You have to build the regex as a string:

TEXTO = sys.argv[1]
my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"

if re.search(my_regex, subject, re.IGNORECASE):
    etc.

Note the use of re.escape so that if your text has special characters, they won't be interpreted as such.

TypeScript: correct way to do string equality?

The === is not for checking string equalit , to do so you can use the Regxp functions for example

if (x.match(y) === null) {
// x and y are not equal 
}

there is also the test function

Error Code: 1406. Data too long for column - MySQL

Try to check the limits of your SQL database. Maybe you'r exceeding the field limit for this row.

Android get image from gallery into ImageView

Simple pass Intent first:

Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

And you will get picture path on your onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
    }

for full source code here

Command not found error in Bash variable assignment

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

E.g.

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

So remove spaces:

name="Stack Overflow" 

and it will work fine.

SQL: how to use UNION and order by a specific select?

@Adrian's answer is perfectly suitable, I just wanted to share another way of achieving the same result:

select nvl(a.id, b.id)
from a full outer join b on a.id = b.id
order by b.id;

How can I declare dynamic String array in Java

What your looking for is the DefaultListModel - Dynamic String List Variable.

Here is a whole class that uses the DefaultListModel as though it were the TStringList of Delphi. The difference is that you can add Strings to the list without limitation and you have the same ability at getting a single entry by specifying the entry int.

FileName: StringList.java

package YOUR_PACKAGE_GOES_HERE;

//This is the StringList Class by i2programmer
//You may delete these comments
//This code is offered freely at no requirements
//You may alter the code as you wish
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

public class StringList {

    public static String OutputAsString(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static Object OutputAsObject(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static int OutputAsInteger(DefaultListModel list, int entry) {
        return Integer.parseInt(list.getElementAt(entry).toString());
    }

    public static double OutputAsDouble(DefaultListModel list, int entry) {
        return Double.parseDouble(list.getElementAt(entry).toString());
    }

    public static byte OutputAsByte(DefaultListModel list, int entry) {
        return Byte.parseByte(list.getElementAt(entry).toString());
    }

    public static char OutputAsCharacter(DefaultListModel list, int entry) {
        return list.getElementAt(entry).toString().charAt(0);
    }

    public static String GetEntry(DefaultListModel list, int entry) {
        String result = "";
        result = list.getElementAt(entry).toString();
        return result;
    }

    public static void AddEntry(DefaultListModel list, String entry) {
        list.addElement(entry);
    }

    public static void RemoveEntry(DefaultListModel list, int entry) {
        list.removeElementAt(entry);
    }

    public static DefaultListModel StrToList(String input, String delimiter) {
        DefaultListModel dlmtemp = new DefaultListModel();
        input = input.trim();
        delimiter = delimiter.trim();
        while (input.toLowerCase().contains(delimiter.toLowerCase())) {
            int index = input.toLowerCase().indexOf(delimiter.toLowerCase());
            dlmtemp.addElement(input.substring(0, index).trim());
            input = input.substring(index + delimiter.length(), input.length()).trim();
        }
        return dlmtemp;
    }

    public static String ListToStr(DefaultListModel list, String delimiter) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            result = list.getElementAt(i).toString() + delimiter;
        }
        result = result.trim();
        return result;
    }

    public static String LoadFile(String inputfile) throws IOException {
        int len;
        char[] chr = new char[4096];
        final StringBuffer buffer = new StringBuffer();
        final FileReader reader = new FileReader(new File(inputfile));
        try {
            while ((len = reader.read(chr)) > 0) {
                buffer.append(chr, 0, len);
            }
        } finally {
            reader.close();
        }
        return buffer.toString();
    }

    public static void SaveFile(String outputfile, String outputstring) {
        try {
            FileWriter f0 = new FileWriter(new File(outputfile));
            f0.write(outputstring);
            f0.flush();
            f0.close();
        } catch (IOException ex) {
            Logger.getLogger(StringList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

OutputAs methods are for outputting an entry as int, double, etc... so that you don't have to convert from string on the other side.

SaveFile & LoadFile are to save and load strings to and from files.

StrToList & ListToStr are to place delimiters between each entry.

ex. 1<>2<>3<>4<> if "<>" is the delimiter and 1 2 3 & 4 are the entries.

AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.

RemoveEntry is to delete a string from the DefaultListModel.

You use the DefaultListModel instead of an array here like this:

DefaultListModel list = new DefaultListModel();
//now that you have a list, you can run it through the above class methods.

Uncaught ReferenceError: React is not defined

If you're using TypeScript, make sure that your tsconfig.json has "jsx": "react" within "compilerOptions".

How to change scroll bar position with CSS?

Try this out. Hope this helps

<div id="single" dir="rtl">
    <div class="common">Single</div>
</div>

<div id="both" dir="ltr">
    <div class="common">Both</div>
</div>



#single, #both{
    width: 100px;
    height: 100px;
    overflow: auto;
    margin: 0 auto;
    border: 1px solid gray;
}


.common{
    height: 150px;
    width: 150px;
}

TypeError: window.initMap is not a function

I had a similar error. The answers here helped me figure out what to do.

index.html

 <!--The div element for the map -->
 <div id="map"></div>

<!--The link to external javascript file that has initMap() function-->
 <script src="main.js">

<!--Google api, this calls initMap() function-->
 <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEYWY&callback=initMap">
</script>

main.js // This gives error


// The initMap function has not been executed
const initMap = () => {
const mapDisplayElement = document.getElementById('map');
  // The address is Uluru
const address = {lat: -25.344, lng: 131.036};
  // The zoom property specifies the zoom level for the map. Zoom: 0 is the lowest zoom,and displays the entire earth.
const map = new google.maps.Map(mapDisplayElement, { zoom: 4, center: address });
const marker = new google.maps.Marker({ position: address, map });
};

The answers here helped me figure out a solution. I used an immediately invoked the function (IIFE ) to work around it.

The error is as at the time of calling the google maps api the initMap() function has not executed.

main.js // This works

const mapDisplayElement = document.getElementById('map');
// The address is Uluru
// Run the initMap() function imidiately, 
(initMap = () => {
  const address = {lat: -25.344, lng: 131.036};
  // The zoom property specifies the zoom level for the map. Zoom: 0 is the lowest zoom,and displays the entire earth.
  const map = new google.maps.Map(mapDisplayElement, { zoom: 4, center: address });
  const marker = new google.maps.Marker({ position: address, map });
})();

How can I remove the first line of a text file using bash/sed script?

You can edit the files in place: Just use perl's -i flag, like this:

perl -ni -e 'print unless $. == 1' filename.txt

This makes the first line disappear, as you ask. Perl will need to read and copy the entire file, but it arranges for the output to be saved under the name of the original file.

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Implicit and Explicit Waits

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

List of remotes for a Git repository?

If you only need the names of the remote repositories (and not any of the other data), a simple git remote is enough.

$ git remote
iqandreas
octopress
origin

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

MySQL select where column is not empty

Another alternative is to look specifically at the CHAR_LENGTH of the column values. (not to be confused with LENGTH)

Using a criteria where the character length is greater than 0, will avoid false positives when the column values can be falsey, such as in the event of an integer column with a value of 0 or NULL. Behaving more consistently across varying data-types.

Which results in any value that is at least 1 character long, or otherwise not empty.

Example https://www.db-fiddle.com/f/iQvEhY1SH6wfruAvnmWdj5/1

SELECT phone, phone2
FROM users
WHERE phone LIKE '813%'
AND CHAR_LENGTH(phone2) > 0

Table Data

users
phone (varchar 12) | phone2 (int 10)
"813-123-4567"     | NULL
"813-123-4567"     | 1
"813-123-4567"     | 0

users2
phone (varchar 12) | phone2 (varchar 12)
"813-123-4567"     | NULL
"813-123-4567"     | "1"
"813-123-4567"     | "0"
"813-123-4567"     | ""

CHAR_LENGTH(phone2) > 0 Results (same)

users
813-123-4567       | 1
813-123-4567       | 0

users2
813-123-4567       | 1
813-123-4567       | 0

Alternatives

phone2 <> '' Results (different)

users
813-123-4567       | 1

users2
813-123-4567       | 1
813-123-4567       | 0

phone2 > '' Results (different)

users
813-123-4567       | 1

users2
813-123-4567       | 1
813-123-4567       | 0

COALESCE(phone2, '') <> '' Results (same)
Note: the results differ from phone2 IS NOT NULL AND phone2 <> '' which is not expected

users
813-123-4567       | 1
813-123-4567       | 0

users2
813-123-4567       | 1
813-123-4567       | 0

phone2 IS NOT NULL AND phone2 <> '' Results (different)

users
813-123-4567       | 1

users2
813-123-4567       | 1
813-123-4567       | 0

How do I change a TCP socket to be non-blocking?

On Linux and BSD you can directly create the socket in non-blocking mode (https://www.man7.org/linux/man-pages/man7/socket.7.html):

int fd = socket(res->ai_family, res->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, res->ai_protocol);
if (fd == -1) {
    perror("socket");
    return -1;
}

When accepting connections you can use the accept4 function to directly accept new connections in non-blocking mode (https://man7.org/linux/man-pages/man2/accept.2.html):

int fd = accept4(lfd, NULL, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (fd == -1) {
    perror("accept4");
    return -1;
}

I don't know why the accepted answer doesn't mention this.

How to locate the Path of the current project directory in Java (IDE)?

YOU CANT.

Java-Projects does not have ONE path! Java-Projects has multiple pathes even so one Class can have multiple locations in different classpath's in one "Project".

So if you have a calculator.jar located in your JRE/lib and one calculator.jar with the same classes on a CD: if you execute the calculator.jar the classes from the CD, the java-vm will take the classes from the JRE/lib!

This problem often comes to programmers who like to load resources deployed inside of the Project. In this case,

System.getResource("/likebutton.png") 

is taken for example.

Add regression line equation and R^2 on graph

Inspired by the equation style provided in this answer, a more generic approach (more than one predictor + latex output as option) can be:

print_equation= function(model, latex= FALSE, ...){
    dots <- list(...)
    cc= model$coefficients
    var_sign= as.character(sign(cc[-1]))%>%gsub("1","",.)%>%gsub("-"," - ",.)
    var_sign[var_sign==""]= ' + '

    f_args_abs= f_args= dots
    f_args$x= cc
    f_args_abs$x= abs(cc)
    cc_= do.call(format, args= f_args)
    cc_abs= do.call(format, args= f_args_abs)
    pred_vars=
        cc_abs%>%
        paste(., x_vars, sep= star)%>%
        paste(var_sign,.)%>%paste(., collapse= "")

    if(latex){
        star= " \\cdot "
        y_var= strsplit(as.character(model$call$formula), "~")[[2]]%>%
            paste0("\\hat{",.,"_{i}}")
        x_vars= names(cc_)[-1]%>%paste0(.,"_{i}")
    }else{
        star= " * "
        y_var= strsplit(as.character(model$call$formula), "~")[[2]]        
        x_vars= names(cc_)[-1]
    }

    equ= paste(y_var,"=",cc_[1],pred_vars)
    if(latex){
        equ= paste0(equ," + \\hat{\\varepsilon_{i}} \\quad where \\quad \\varepsilon \\sim \\mathcal{N}(0,",
                    summary(MetamodelKdifEryth)$sigma,")")%>%paste0("$",.,"$")
    }
    cat(equ)
}

The model argument expects an lm object, the latex argument is a boolean to ask for a simple character or a latex-formated equation, and the ... argument pass its values to the format function.

I also added an option to output it as latex so you can use this function in a rmarkdown like this:


```{r echo=FALSE, results='asis'}
print_equation(model = lm_mod, latex = TRUE)
```

Now using it:

df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
df$z <- 8 + 3 * df$x + rnorm(100, sd = 40)
lm_mod= lm(y~x+z, data = df)

print_equation(model = lm_mod, latex = FALSE)

This code yields: y = 11.3382963933174 + 2.5893419 * x + 0.1002227 * z

And if we ask for a latex equation, rounding the parameters to 3 digits:

print_equation(model = lm_mod, latex = TRUE, digits= 3)

This yields: latex equation

How to open a file for both reading and writing?

I have tried something like this and it works as expected:

f = open("c:\\log.log", 'r+b')
f.write("\x5F\x9D\x3E")
f.read(100)
f.close()

Where:

f.read(size) - To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string.

And:

f.write(string) writes the contents of string to the file, returning None.

Also if you open Python tutorial about reading and writing files you will find that:

'r+' opens the file for both reading and writing.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.

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

If you are using plain LINQ-to-objects and don't want to take a dependency on an external library it is not hard to achieve what you want.

The OrderBy() clause accepts a Func<TSource, TKey> that gets a sort key from a source element. You can define the function outside the OrderBy() clause:

Func<Item, Object> orderByFunc = null;

You can then assign it to different values depending on the sort criteria:

if (sortOrder == SortOrder.SortByName)
  orderByFunc = item => item.Name;
else if (sortOrder == SortOrder.SortByRank)
  orderByFunc = item => item.Rank;

Then you can sort:

var sortedItems = items.OrderBy(orderByFunc);

This example assumes that the source type is Item that have properties Name and Rank.

Note that in this example TKey is Object to not constrain the property types that can be sorted on. If the func returns a value type (like Int32) it will get boxed when sorting and that is somewhat inefficient. If you can constrain TKey to a specific value type you can work around this problem.

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

scanf needs to know the size of the data being pointed at by &d to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf is always getting a double.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

How do I create a GUI for a windows application using C++?

For such a simple application even MFC would be overkill. If don't want to introduce another dependency just do it in plain vanilla Win32. It will be easier for you if you have never used MFC.

Check out the classic "Programming Windows" by Charles Petzold or some online tutorial (e.g. http://www.winprog.org/tutorial/) and you are ready to go.

MySQL - Rows to Columns

I figure out one way to make my reports converting rows to columns almost dynamic using simple querys. You can see and test it online here.

The number of columns of query is fixed but the values are dynamic and based on values of rows. You can build it So, I use one query to build the table header and another one to see the values:

SELECT distinct concat('<th>',itemname,'</th>') as column_name_table_header FROM history order by 1;

SELECT
     hostid
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue else '' end) as col1
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue else '' end) as col2
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue else '' end) as col3
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 3,1) then itemvalue else '' end) as col4
FROM history order by 1;

You can summarize it, too:

SELECT
     hostid
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue end) as A
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue end) as B
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue end) as C
FROM history group by hostid order by 1;
+--------+------+------+------+
| hostid | A    | B    | C    |
+--------+------+------+------+
|      1 |   10 |    3 | NULL |
|      2 |    9 | NULL |   40 |
+--------+------+------+------+

Results of RexTester:

Results of RexTester

http://rextester.com/ZSWKS28923

For one real example of use, this report bellow show in columns the hours of departures arrivals of boat/bus with a visual schedule. You will see one additional column not used at the last col without confuse the visualization: sistema venda de passagens online e consumidor final e controle de frota - xsl tecnologia - xsl.com.br ** ticketing system to of sell ticket online and presential

LINQ: combining join and group by

Once you've done this

group p by p.SomeId into pg  

you no longer have access to the range variables used in the initial from. That is, you can no longer talk about p or bp, you can only talk about pg.

Now, pg is a group and so contains more than one product. All the products in a given pg group have the same SomeId (since that's what you grouped by), but I don't know if that means they all have the same BaseProductId.

To get a base product name, you have to pick a particular product in the pg group (As you are doing with SomeId and CountryCode), and then join to BaseProducts.

var result = from p in Products                         
 group p by p.SomeId into pg                         
 // join *after* group
 join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id         
 select new ProductPriceMinMax { 
       SomeId = pg.FirstOrDefault().SomeId, 
       CountryCode = pg.FirstOrDefault().CountryCode, 
       MinPrice = pg.Min(m => m.Price), 
       MaxPrice = pg.Max(m => m.Price),
       BaseProductName = bp.Name  // now there is a 'bp' in scope
 };

That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.

Forbidden :You don't have permission to access /phpmyadmin on this server

You could simply go to phpmyadmin.conf file and change "deny from all" to "allow from all". Well it worked for me, hope it works for you as well.

Angular Material: mat-select not selecting default

A comparison between a number and a string use to be false, so, cast you selected value to a string within ngOnInit and it will work.

I had same issue, I filled the mat-select with an enum, using

Object.keys(MyAwesomeEnum).filter(k => !isNaN(Number(k)));

and I had the enum value I wanted to select...

I spent few hours struggling my mind trying to identify why it wasn't working. And I did it just after rendering all the variables being used in the mat-select, the keys collection and the selected... if you have ["0","1","2"] and you want to select 1 (which is a number) 1=="1" is false and because of that nothing is selected.

so, the solution is to cast you selected value to a string within ngOnInit and it will work.

Current user in Magento?

Found under "app/code/core/Mage/Page/Block/Html/Header.php":

public function getWelcome()
{
    if (empty($this->_data['welcome'])) {
        if (Mage::app()->isInstalled() && Mage::getSingleton('customer/session')->isLoggedIn()) {
            $this->_data['welcome'] = $this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getName());
        } else {
            $this->_data['welcome'] = Mage::getStoreConfig('design/header/welcome');
        }
    }

    return $this->_data['welcome'];
}

So it looks like Mage::getSingleton('customer/session')->getCustomer() will get your current logged in customer ;)

To get the currently logged in admin:

Mage::getSingleton('admin/session')->getUser();

How to list files in an android directory?

Your path is not within the assets folder. Either you enumerate files within the assets folder by means of AssetManager.list() or you enumerate files on your SD card by means of File.list()

How to append one DataTable to another DataTable

Merge takes a DataTable, Load requires an IDataReader - so depending on what your data layer gives you access to, use the required method. My understanding is that Load will internally call Merge, but not 100% sure about that.

If you have two DataTables, use Merge.

How to split a dos path into its components in Python

Just like others explained - your problem stemmed from using \, which is escape character in string literal/constant. OTOH, if you had that file path string from another source (read from file, console or returned by os function) - there wouldn't have been problem splitting on '\\' or r'\'.

And just like others suggested, if you want to use \ in program literal, you have to either duplicate it \\ or the whole literal has to be prefixed by r, like so r'lite\ral' or r"lite\ral" to avoid the parser converting that \ and r to CR (carriage return) character.

There is one more way though - just don't use backslash \ pathnames in your code! Since last century Windows recognizes and works fine with pathnames which use forward slash as directory separator /! Somehow not many people know that.. but it works:

>>> var = "d:/stuff/morestuff/furtherdown/THEFILE.txt"
>>> var.split('/')
['d:', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']

This by the way will make your code work on Unix, Windows and Mac... because all of them do use / as directory separator... even if you don't want to use the predefined constants of module os.

batch file to copy files to another location?

Open Notepad.

Type the following lines into it (obviously replace the folders with your ones)

@echo off
rem you could also remove the line above, because it might help you to see what happens

rem /i option is needed to avoid the batch file asking you whether destination folder is a file or a folder
rem /e option is needed to copy also all folders and subfolders
xcopy "c:\New Folder" "c:\Copy of New Folder" /i /e

Save the file as backup.bat (not .txt)

Double click on the file to run it. It will backup the folder and all its contents files/subfolders.

Now if you want the batch file to be run everytime you login in Windows, you should place it in Windows Startup menu. You find it under: Start > All Program > Startup To place the batch file in there either drag it into the Startup menu or RIGH click on the Windows START button and select Explore, go in Programs > Startup, and copy the batch file into there.

To run the batch file everytime the folder is updated you need an application, it can not be done with just a batch file.

Package opencv was not found in the pkg-config search path

I installed opencv following the steps on https://docs.opencv.org/trunk/d7/d9f/tutorial_linux_install.html

Except on Step 2, use: cmake -D CMAKE_BUILD_TYPE=Release -D OPENCV_GENERATE_PKGCONFIG=YES -D CMAKE_INSTALL_PREFIX=/path/to/opencv/ ..

Then locate the opencv4.pc file, mine was in opencv/build/unix-install/

Now run: $ export PKG_CONFIG_PATH=/path/to/the/file

variable is not declared it may be inaccessible due to its protection level

I have suffered a similar problem, with a Sub not accessible in runtime, but absolutely legal in editor. It was solved by changing destination Framework from 4.5.1 to 4.5. It seems that my IIS only had 4.5 version.

:)

Java, Calculate the number of days between two dates

My best solution (so far) for calculating the number of days difference:

//  This assumes that you already have two Date objects: startDate, endDate
//  Also, that you want to ignore any time portions

Calendar startCale=new GregorianCalendar();
Calendar endCal=new GregorianCalendar();

startCal.setTime(startDate);
endCal.setTime(endDate);

endCal.add(Calendar.YEAR,-startCal.get(Calendar.YEAR));
endCal.add(Calendar.MONTH,-startCal.get(Calendar.MONTH));
endCal.add(Calendar.DATE,-startCal.get(Calendar.DATE));

int daysDifference=endCal.get(Calendar.DAY_OF_YEAR);

Note, however, that this assumes less than a year's difference!

How to get docker-compose to always re-create containers from fresh images?

The only solution that worked for me was this command :

docker-compose build --no-cache

This will automatically pull fresh image from repo and won't use the cache version that is prebuild with any parameters you've been using before.

How to check if curl is enabled or disabled

Hope this helps.

<?php
    function _iscurl() {
        return function_exists('curl_version');
    }
?>

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

How do I get the n-th level parent of an element in jQuery?

Since parents() returns the ancestor elements ordered from the closest to the outer ones, you can chain it into eq():

$('#element').parents().eq(0);  // "Father".
$('#element').parents().eq(2);  // "Great-grandfather".

LINQ .Any VS .Exists - What's the difference?

When you correct the measurements - as mentioned above: Any and Exists, and adding average - we'll get following output:

Executing search Exists() 1000 times ... 
Average Exists(): 35566,023
Fastest Exists() execution: 32226 

Executing search Any() 1000 times ... 
Average Any(): 58852,435
Fastest Any() execution: 52269 ticks

Benchmark finished. Press any key.

How to change CSS using jQuery?

_x000D_
_x000D_
$(function(){ _x000D_
$('.bordered').css({_x000D_
"border":"1px solid #EFEFEF",_x000D_
"margin":"0 auto",_x000D_
"width":"80%"_x000D_
});_x000D_
_x000D_
$('h1').css({_x000D_
"margin-left":"10px"_x000D_
});_x000D_
_x000D_
$('#myParagraph').css({_x000D_
"margin-left":"10px",_x000D_
"font-family":"sans-serif"_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<div class="bordered">_x000D_
<h1>Header</h1>_x000D_
<p id="myParagraph">This is some paragraph text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I get the current array index in a foreach loop?

foreach($array as $key=>$value) {
    // do stuff
}

$key is the index of each $array element

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

If you can afford to restart your machine then do it, this fixed my issue after almost an hour of trying to fix this issue with no hope.

How to check if a file exists from inside a batch file

Try something like the following example, quoted from the output of IF /? on Windows XP:

IF EXIST filename. (
    del filename.
) ELSE (
    echo filename. missing.
)

You can also check for a missing file with IF NOT EXIST.

The IF command is quite powerful. The output of IF /? will reward careful reading. For that matter, try the /? option on many of the other built-in commands for lots of hidden gems.  

How to add parameters to a HTTP GET request in Android?

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","value1");

String query = URLEncodedUtils.format(params, "utf-8");

URI url = URIUtils.createURI(scheme, userInfo, authority, port, path, query, fragment); //can be null
HttpGet httpGet = new HttpGet(url);

URI javadoc

Note: url = new URI(...) is buggy

declaring a priority_queue in c++ with a custom comparator

You should declare a class Compare and overload operator() for it like this:

class Foo
{

};

class Compare
{
public:
    bool operator() (Foo, Foo)
    {
        return true;
    }
};

int main()
{
    std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
    return 0;
}

Or, if you for some reasons can't make it as class, you could use std::function for it:

class Foo
{

};

bool Compare(Foo, Foo)
{
    return true;
}

int main()
{
    std::priority_queue<Foo, std::vector<Foo>, std::function<bool(Foo, Foo)>> pq(Compare);
    return 0;
}

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I had this problem running unit tests (xunit) in Visual Studio 2015 and came across the following fix:

Menu Bar -> Test -> Test Settings -> Default Processor Architecture -> X64

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

You have the wrong table set on the command. You should use the following on your setup:

ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Changing the child element's CSS when the parent is hovered

I have what i think is a better solution, since it is scalable to more levels, as many as wanted, not only two or three.

I use borders, but it can also be done with whateever style wanted, like background-color.

With the border, the idea is to:

  • Have a different border color only one div, the div over where the mouse is, not on any parent, not on any child, so it can be seen only such div border in a different color while the rest stays on white.

You can test it at: http://jsbin.com/ubiyo3/13

And here is the code:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Hierarchie Borders MarkUp</title>
<style>

  .parent { display: block; position: relative; z-index: 0;
            height: auto; width: auto; padding: 25px;
          }

  .parent-bg { display: block; height: 100%; width: 100%; 
               position: absolute; top: 0px; left: 0px; 
               border: 1px solid white; z-index: 0; 
             }
  .parent-bg:hover { border: 1px solid red; }

  .child { display: block; position: relative; z-index: 1; 
           height: auto; width: auto; padding: 25px;
         }

  .child-bg { display: block; height: 100%; width: 100%; 
              position: absolute; top: 0px; left: 0px; 
              border: 1px solid white; z-index: 0; 
            }
  .child-bg:hover { border: 1px solid red; }

  .grandson { display: block; position: relative; z-index: 2; 
              height: auto; width: auto; padding: 25px;
            }

  .grandson-bg { display: block; height: 100%; width: 100%; 
                 position: absolute; top: 0px; left: 0px; 
                 border: 1px solid white; z-index: 0; 
               }
  .grandson-bg:hover { border: 1px solid red; }

</style>
</head>
<body>
  <div class="parent">
    Parent
    <div class="child">
      Child
      <div class="grandson">
        Grandson
        <div class="grandson-bg"></div>
      </div>
      <div class="child-bg"></div>
    </div>
    <div class="parent-bg"></div>
  </div>
</body>
</html>

Android Color Picker

Here's another library:

https://github.com/eltos/SimpleDialogFragments

Features color wheel and pallet picker dialogs

Where and why do I have to put the "template" and "typename" keywords?

C++11

Problem

While the rules in C++03 about when you need typename and template are largely reasonable, there is one annoying disadvantage of its formulation

template<typename T>
struct A {
  typedef int result_type;

  void f() {
    // error, "this" is dependent, "template" keyword needed
    this->g<float>();

    // OK
    g<float>();

    // error, "A<T>" is dependent, "typename" keyword needed
    A<T>::result_type n1;

    // OK
    result_type n2; 
  }

  template<typename U>
  void g();
};

As can be seen, we need the disambiguation keyword even if the compiler could perfectly figure out itself that A::result_type can only be int (and is hence a type), and this->g can only be the member template g declared later (even if A is explicitly specialized somewhere, that would not affect the code within that template, so its meaning cannot be affected by a later specialization of A!).

Current instantiation

To improve the situation, in C++11 the language tracks when a type refers to the enclosing template. To know that, the type must have been formed by using a certain form of name, which is its own name (in the above, A, A<T>, ::A<T>). A type referenced by such a name is known to be the current instantiation. There may be multiple types that are all the current instantiation if the type from which the name is formed is a member/nested class (then, A::NestedClass and A are both current instantiations).

Based on this notion, the language says that CurrentInstantiation::Foo, Foo and CurrentInstantiationTyped->Foo (such as A *a = this; a->Foo) are all member of the current instantiation if they are found to be members of a class that is the current instantiation or one of its non-dependent base classes (by just doing the name lookup immediately).

The keywords typename and template are now not required anymore if the qualifier is a member of the current instantiation. A keypoint here to remember is that A<T> is still a type-dependent name (after all T is also type dependent). But A<T>::result_type is known to be a type - the compiler will "magically" look into this kind of dependent types to figure this out.

struct B {
  typedef int result_type;
};

template<typename T>
struct C { }; // could be specialized!

template<typename T>
struct D : B, C<T> {
  void f() {
    // OK, member of current instantiation!
    // A::result_type is not dependent: int
    D::result_type r1;

    // error, not a member of the current instantiation
    D::questionable_type r2;

    // OK for now - relying on C<T> to provide it
    // But not a member of the current instantiation
    typename D::questionable_type r3;        
  }
};

That's impressive, but can we do better? The language even goes further and requires that an implementation again looks up D::result_type when instantiating D::f (even if it found its meaning already at definition time). When now the lookup result differs or results in ambiguity, the program is ill-formed and a diagnostic must be given. Imagine what happens if we defined C like this

template<>
struct C<int> {
  typedef bool result_type;
  typedef int questionable_type;
};

A compiler is required to catch the error when instantiating D<int>::f. So you get the best of the two worlds: "Delayed" lookup protecting you if you could get in trouble with dependent base classes, and also "Immediate" lookup that frees you from typename and template.

Unknown specializations

In the code of D, the name typename D::questionable_type is not a member of the current instantiation. Instead the language marks it as a member of an unknown specialization. In particular, this is always the case when you are doing DependentTypeName::Foo or DependentTypedName->Foo and either the dependent type is not the current instantiation (in which case the compiler can give up and say "we will look later what Foo is) or it is the current instantiation and the name was not found in it or its non-dependent base classes and there are also dependent base classes.

Imagine what happens if we had a member function h within the above defined A class template

void h() {
  typename A<T>::questionable_type x;
}

In C++03, the language allowed to catch this error because there could never be a valid way to instantiate A<T>::h (whatever argument you give to T). In C++11, the language now has a further check to give more reason for compilers to implement this rule. Since A has no dependent base classes, and A declares no member questionable_type, the name A<T>::questionable_type is neither a member of the current instantiation nor a member of an unknown specialization. In that case, there should be no way that that code could validly compile at instantiation time, so the language forbids a name where the qualifier is the current instantiation to be neither a member of an unknown specialization nor a member of the current instantiation (however, this violation is still not required to be diagnosed).

Examples and trivia

You can try this knowledge on this answer and see whether the above definitions make sense for you on a real-world example (they are repeated slightly less detailed in that answer).

The C++11 rules make the following valid C++03 code ill-formed (which was not intended by the C++ committee, but will probably not be fixed)

struct B { void f(); };
struct A : virtual B { void f(); };

template<typename T>
struct C : virtual B, T {
  void g() { this->f(); }
};

int main() { 
  C<A> c; c.g(); 
}

This valid C++03 code would bind this->f to A::f at instantiation time and everything is fine. C++11 however immediately binds it to B::f and requires a double-check when instantiating, checking whether the lookup still matches. However when instantiating C<A>::g, the Dominance Rule applies and lookup will find A::f instead.

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

This is nice but doesn't answer the question:

"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

What does "subject" mean in certificate?

Subject is the certificate's common name and is a critical property for the certificate in a lot of cases if it's a server certificate and clients are looking for a positive identification.

As an example on an SSL certificate for a web site the subject would be the domain name of the web site.

Where does this come from: -*- coding: utf-8 -*-

In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.

SQL Query for Student mark functionality

Using a Subquery:

select m.subid, m.stid, m.mark
from marks m,
    (select m2.subid, max(m2.mark) max_mark
    from marks m2
    group by subid) subq

where subq.subid = m.subid
and subq.max_mark = m.mark
order by 1,2;

Using Rank with Partition:

select subid, stid, mark
from (select m.subid, m.stid, m.mark,
rank() over (partition by m.subid order by m.mark desc) Mark_Rank
from marks m)
where Mark_Rank = 1
order by 1,2;

String.Replace ignoring case

You can also try the Regex class.

var regex = new Regex( "camel", RegexOptions.IgnoreCase ); var newSentence = regex.Replace( sentence, "horse" );

htaccess - How to force the client's browser to clear the cache?

I got your problem...

Although we can clear client browser cache completely but you can add some code to your application so that your recent changes reflect to client browser.

In your <head>:

<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

Source: http://goo.gl/JojsO

Plot two graphs in same plot in R

You can use points for the overplot, that is.

plot(x1, y1,col='red')

points(x2,y2,col='blue')

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Coming here from first Google hit:

You can turn off the behavior AND and warning by exporting GIT_DISCOVERY_ACROSS_FILESYSTEM=1.

On heroku, if you heroku config:set GIT_DISCOVERY_ACROSS_FILESYSTEM=1 the warning will go away.

It's probably because you are building a gem from source and the gemspec shells out to git, like many do today. So, you'll still get the warning fatal: Not a git repository (or any of the parent directories): .git but addressing that is for another day :)

My answer is a duplicate of: - comment GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Display curl output in readable JSON format in Unix shell script

Check out curljson

$ pip install curljson
$ curljson -i <the-json-api-url>

AngularJS routing without the hash '#'

In Angular 6, with your router you can use:

RouterModule.forRoot(routes, { useHash: false })

Apply CSS rules to a nested class inside a div

If you need to target multiple classes use:

#main_text .title, #main_text .title2 {
  /* Properties */
}