Programs & Examples On #.app

.app is an extension given to application bundles on Mac OS X.

How to get .app file of a xcode application

I know as for Appium Mobile Automation you need .app file to run ios app on Simulator.So as like me many of you face this problem. So I explain how to create that .app file and where it is located.

1.Open Xcode.

2.Click on your sample project.(If you don't have then click on create new xcode project)

3.In left panel inside screen you will see products folder then click and expand that, you will see the list.

  1. Then right click on .app file and click on Show in Finder and thats your .app file. Now you can copy or use that path in capabilities for appium desktop or in framework.

Check the attached screenshot for detail

Setting Margin Properties in code

Margin = new Thickness(0, 0, 0, 0);

OnChange event using React JS for drop down

The change event is triggered on the <select> element, not the <option> element. However, that's not the only problem. The way you defined the change function won't cause a rerender of the component. It seems like you might not have fully grasped the concept of React yet, so maybe "Thinking in React" helps.

You have to store the selected value as state and update the state when the value changes. Updating the state will trigger a rerender of the component.

var MySelect = React.createClass({
     getInitialState: function() {
         return {
             value: 'select'
         }
     },
     change: function(event){
         this.setState({value: event.target.value});
     },
     render: function(){
        return(
           <div>
               <select id="lang" onChange={this.change} value={this.state.value}>
                  <option value="select">Select</option>
                  <option value="Java">Java</option>
                  <option value="C++">C++</option>
               </select>
               <p></p>
               <p>{this.state.value}</p>
           </div>
        );
     }
});

React.render(<MySelect />, document.body);

Also note that <p> elements don't have a value attribute. React/JSX simply replicates the well-known HTML syntax, it doesn't introduce custom attributes (with the exception of key and ref). If you want the selected value to be the content of the <p> element then simply put inside of it, like you would do with any static content.

Learn more about event handling, state and form controls:

What is "Advanced" SQL?

I suppose subqueries and PIVOT would qualify, as well as multiple joins, unions and the like.

Applying a single font to an entire website with CSS

Please place this in the head of your Page(s) if the "body" needs the use of 1 and the same font:

<style type="text/css">
body {font-family:FONT-NAME ;
     }
</style>

Everything between the tags <body> and </body>will have the same font

JUnit Eclipse Plugin?

JUnit is part of Eclipse Java Development Tools (JDT). So, either install the JDT via Software Updates or download and install Eclipse IDE for Java Developers (actually, I'd recommend installing Eclipse IDE for Java EE Developers if you want a complete built-in environment for server side development).

You add it to a project by right clicking the project in the Package Explorer and selecting Build Path -> Add Libraries... Then simply select JUnit and click Next >.

for loop in Python

Here are some example to iterate over integer range and string:

#(initial,final but not included,gap)
for i in range(1,10,2): 
  print(i); 
1,3,5,7,9

# (initial, final but not included)  
# note: 4 not included
for i in range (1,4): 
   print(i);
1,2,3 

#note: 5 not included
for i in range (5):
  print (i);
0,1,2,3,4 

# you can also iterate over strings
myList = ["ml","ai","dl"];  

for i in myList:
  print(i);
output:  ml,ai,dl

How do I fix 'ImportError: cannot import name IncompleteRead'?

This should work for you. Follow these simple steps.

First, let's remove the pip which is already installed so it won't cause any error.

Open Terminal.

Type: sudo apt-get remove python-pip

It removes pip that is already installed.

Method-1

Step: 1 sudo easy_install -U pip

It will install pip latest version.

And will return its address: Installed /usr/local/lib/python2.7/dist-packages/pip-6.1.1-py2.7.egg

or

Method-2

Step: 1 go to this link.

Step: 2 Right click >> Save as.. with name get-pip.py .

Step: 3 use: cd to go to the same directory as your get-pip.py file

Step: 4 use: sudo python get-pip.py

It will install pip latest version.

or

Method-3

Step: 1 use: sudo apt-get install python-pip

It will install pip latest version.

C++ Double Address Operator? (&&)

&& is new in C++11, and it signifies that the function accepts an RValue-Reference -- that is, a reference to an argument that is about to be destroyed.

How do I plot list of tuples in Python?

In matplotlib it would be:

import matplotlib.pyplot as plt

data =  [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

x_val = [x[0] for x in data]
y_val = [x[1] for x in data]

print x_val
plt.plot(x_val,y_val)
plt.plot(x_val,y_val,'or')
plt.show()

which would produce:

enter image description here

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

Should it be LIBRARY_PATH instead of LD_LIBRARY_PATH. gcc checks for LIBRARY_PATH which can be seen with -v option

Why shouldn't I use "Hungarian Notation"?

Apps Hungarian is Greek to me--in a good way

As an engineer, not a programmer, I immediately took to Joel's article on the merits of Apps Hungarian: "Making Wrong Code Look Wrong". I like Apps Hungarian because it mimics how engineering, science, and mathematics represent equations and formulas using sub- and super-scripted symbols (like Greek letters, mathematical operators, etc.). Take a particular example of Newton's Law of Universal Gravity: first in standard mathematical notation, and then in Apps Hungarian pseudo-code:

Newton's Universal law of gravity for Earth and Mars

frcGravityEarthMars = G * massEarth * massMars / norm(posEarth - posMars)

In the mathematical notation, the most prominent symbols are those representing the kind of information stored in the variable: force, mass, position vector, etc. The subscripts play second fiddle to clarify: position of what? This is exactly what Apps Hungarian is doing; it's telling you the kind of thing stored in the variable first and then getting into specifics--about the closest code can get to mathematical notation.

Clearly strong typing can resolve the safe vs. unsafe string example from Joel's essay, but you wouldn't define separate types for position and velocity vectors; both are double arrays of size three and anything you're likely to do to one might apply to the other. Furthermore, it make perfect sense to concatenate position and velocity (to make a state vector) or take their dot product, but probably not to add them. How would typing allow the first two and prohibit the second, and how would such a system extend to every possible operation you might want to protect? Unless you were willing to encode all of math and physics in your typing system.

On top of all that, lots of engineering is done in weakly typed high-level languages like Matlab, or old ones like Fortran 77 or Ada.

So if you have a fancy language and IDE and Apps Hungarian doesn't help you then forget it--lots of folks apparently have. But for me, a worse than a novice programmer who is working in weakly or dynamically typed languages, I can write better code faster with Apps Hungarian than without.

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

You have to add this permission in Info.plist for iOS 10.

Photo :

Key       :  Privacy - Photo Library Usage Description    
Value   :  $(PRODUCT_NAME) photo use

Microphone :

Key        :  Privacy - Microphone Usage Description    
Value    :  $(PRODUCT_NAME) microphone use

Camera :

Key       :  Privacy - Camera Usage Description   
Value   :  $(PRODUCT_NAME) camera use

How do you monitor network traffic on the iPhone?

I use Charles Web Debugging Proxy it costs but they have a trial version.

It is very simple to set up if your iPhone/iPad share the same Wifi network as your Mac.

  1. Install Charles on your Mac
  2. Get the IP address for your Mac - use the Mac "Network utility"
  3. On your iPhone/iPad open the Wifi settings and under the "HTTP Proxy" change to manual and enter the IP from step (2) and then Port to 8888 (Charles default Port)
  4. Open Charles and under the Proxy Settings dialogmake sure the “Enable Mac OS X Proxy” and “Use HTTP Proxy” are ticked
  5. You should now see the traffic appearing within Charles
  6. If you want to look at HTTPS traffic you need to do the additional 2 steps download the Charles Certificate Bundle and then email the .crt file to your iPhone/iPad and install.
  7. In the Proxy Settings Dialog SSL tab, add the specific https top level domains you want to sniff with port 443.

If your Mac and iOS device are not on the same Wifi network you can set up your Mac as a Wifi router using the "Internet Sharing" option under Sharing in the System Preferences. You then connect your device to that "Wifi" network and follow the steps above.

How to get input text value from inside td

Ah I think a understand now. Have a look if this really is what you want:

$(".start").keyup(function(){
    $(this).closest('tr').find("input").each(function() {
        alert(this.value)
    });
});

This will give you all input values of a row.

Update:
To get the value of not all elements you can use :not():

$(this).closest('tr').find("input:not([name^=desc][name^=phone])").each(function() {
     alert(this.value)
});

Actually I am not 100% sure whether it works this way, maybe you have to use two nots instead of this one combining both conditions.

Run AVD Emulator without Android Studio

The way to run the emulator from the console (I assume that you installed it before, using Android Studio) is:

run

cd ~/Android/Sdk/tools/bin && ./avdmanager list avd

OR

cd ~/Android/Sdk/tools && ./emulator -list-avds

You will get the list od your virtual installed devices. In my case it was:

Available Android Virtual Devices:
  Name: Galaxy_Nexus_API_17
  Device: Galaxy Nexus (Google)
  Path: /home/piotr/.android/avd/Galaxy_Nexus_API_17.avd
  Target: Google APIs (Google Inc.)
  Based on: Android 4.2 (Jelly Bean) Tag/ABI: google_apis/x86
  Skin: galaxy_nexus
  Sdcard: /home/piotr/.android/avd/Galaxy_Nexus_API_17.avd/sdcard.img

Copy name of the device you want to run and then

cd ~/Android/Sdk/tools && ./emulator -avd NAME_OF_YOUR_DEVICE

in my case:

cd ~/Android/Sdk/tools && ./emulator -avd Nexus_5X_API_23

ASP.NET MVC 404 Error Handling

What I can recomend is to look on FilterAttribute. For example MVC already has HandleErrorAttribute. You can customize it to handle only 404. Reply if you are interesed I will look example.

BTW

Solution(with last route) that you have accepted in previous question does not work in much of the situations. Second solution with HandleUnknownAction will work but require to make this change in each controller or to have single base controller.

My choice is a solution with HandleUnknownAction.

How to write dynamic variable in Ansible playbook

I am sure there is a smarter way for doing what you want but this should work:

- name         : Test var
  hosts        : all
  gather_facts : no
  vars:
    myvariable : false
  tasks:
    - name: param1
      set_fact:
        myvariable: "{{param1}}"
      when: param1 is defined

    - name: param2
      set_fact:
        myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
      when: param2 is defined

    - name: param3
      set_fact:
        myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
      when: param3 is defined

    - name: default
      set_fact:
        myvariable: "default"
      when: not myvariable

    - debug:
       var=myvariable

Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible

How to sort rows of HTML table that are called from MySQL

The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.

The HTML would look like this:

<th><a href="mypage.php?sort=type">Type:</a></th>
<th><a href="mypage.php?sort=desc">Description:</a></th>
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th>
<th><a href="mypage.php?sort=added">Added Date:</a></th>

And in the php code, do something like this:

<?php

$sql = "SELECT * FROM MyTable";

if ($_GET['sort'] == 'type')
{
    $sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
    $sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
    $sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
    $sql .= " ORDER BY DateAdded";
}

$>

Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

I was facing the same problem and non of the above solutions helped me. In my Web Api 2 project, I had actually updated my database and had placed a unique constraint on an SQL table column. That was actually causing the problem. Simply Checking the the duplicate column values before inserting helped me fix the problem!

How to convert binary string value to decimal

import java.util.*;
public class BinaryToDecimal
{
  public static void main()
  {
    Scanner sc=new Scanner(System.in);
    System.out.println("enter the binary number");
    double s=sc.nextDouble();
    int c=0;
    long s1=0;
    while(s>0)
    {
        s1=s1+(long)(Math.pow(2,c)*(long)(s%10));
        s=(long)s/10;
        c++;
    }
    System.out.println("The respective decimal number is : "+s1);
  }
}

How to replace specific values in a oracle database column?

Use REPLACE:

SELECT REPLACE(t.column, 'est1', 'rest1')
  FROM MY_TABLE t

If you want to update the values in the table, use:

UPDATE MY_TABLE t
   SET column = REPLACE(t.column, 'est1', 'rest1')

Escaping quotes and double quotes

I found myself in a similar predicament today while trying to run a command through a Node.js module:

I was using the PowerShell and trying to run:

command -e 'func($a)'

But with the extra symbols, PowerShell was mangling the arguments. To fix, I back-tick escaped double-quote marks:

command -e `"func($a)`"

Log4j2 configuration - No log4j2 configuration file found

Was following the documentations - Apache Log4j2 Configuratoin and Apache Log4j2 Maven in configuring log4j2 with yaml. As per the documentation, the following maven dependencies are required:

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.1</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.1</version>
  </dependency>

and

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.8.6</version>
</dependency>

Just adding these didn't pick the configuration and always gave error. The way of debugging configuration by adding -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE helped in seeing the logs. Later had to download the source using Maven and debugging helped in understanding the depended classes of log4j2. They are listed in org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory:

com.fasterxml.jackson.databind.ObjectMapper
com.fasterxml.jackson.databind.JsonNode
com.fasterxml.jackson.core.JsonParser
com.fasterxml.jackson.dataformat.yaml.YAMLFactory

Adding dependency mapping for jackson-dataformat-yaml will not have the first two classes. Hence, add the jackson-databind dependency to get yaml configuration working:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>

You may add the version by referring to the Test Dependencies section of log4j-api version item from MVN Repository. E.g. for 2.8.1 version of log4j-api, refer this link and locate the jackson-databind version.

Moreover, you can use the below Java code to check if the classes are available in the classpath:

System.out.println(ClassLoader.getSystemResource("log4j2.yml")); //Check if file is available in CP
ClassLoader cl = Thread.currentThread().getContextClassLoader(); //Code as in log4j2 API. Version: 2.8.1
 String [] classes = {"com.fasterxml.jackson.databind.ObjectMapper",
 "com.fasterxml.jackson.databind.JsonNode",
 "com.fasterxml.jackson.core.JsonParser",
 "com.fasterxml.jackson.dataformat.yaml.YAMLFactory"};

 for(String className : classes) {
     cl.loadClass(className);
 }

Error QApplication: no such file or directory

Make sure you have qmake in your path (which qmake), and that it works (qmake -v) (IF you have to kill it with ctr-c then there is something wrong with your environment).

Then follow this: http://developer.qt.nokia.com/doc/qt-4.8/gettingstartedqt.html

Disabling the button after once click

protected void Page_Load(object sender, EventArgs e)
    {
        // prevent user from making operation twice
        btnSave.Attributes.Add("onclick", 
                               "this.disabled=true;" + GetPostBackEventReference(btnSave).ToString() + ";");

        // ... etc. 
    }

How do I disable fail_on_empty_beans in Jackson?

If you wish to get JSON object without any extra fields - please add this annotation to your class, it worked perfect for me.

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

You can also add in your application.properties file this row, but it will add an extra field to your JSON.

spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false

swift 3.0 Data to String?

I found the way to do it. You need to convert Data to NSData:

let characterSet = CharacterSet(charactersIn: "<>")
let nsdataStr = NSData.init(data: deviceToken)
let deviceStr = nsdataStr.description.trimmingCharacters(in: characterSet).replacingOccurrences(of: " ", with: "")
print(deviceStr)

SQL LIKE condition to check for integer?

Assuming that you're looking for "numbers that start with 7" rather than "strings that start with 7," maybe something like

select * from books where convert(char(32), book_id) like '7%'

Or whatever the Postgres equivalent of convert is.

Get the generated SQL statement from a SqlCommand object?

This solution works for me right now. Maybe it is usefull to someone. Please excuse all the redundancy.

    Public Shared Function SqlString(ByVal cmd As SqlCommand) As String
    Dim sbRetVal As New System.Text.StringBuilder()
    For Each item As SqlParameter In cmd.Parameters
        Select Case item.DbType
            Case DbType.String
                sbRetVal.AppendFormat("DECLARE {0} AS VARCHAR(255)", item.ParameterName)
                sbRetVal.AppendLine()
                sbRetVal.AppendFormat("SET {0} = '{1}'", item.ParameterName, item.Value)
                sbRetVal.AppendLine()

            Case DbType.DateTime
                sbRetVal.AppendFormat("DECLARE {0} AS DATETIME", item.ParameterName)
                sbRetVal.AppendLine()
                sbRetVal.AppendFormat("SET {0} = '{1}'", item.ParameterName, item.Value)
                sbRetVal.AppendLine()

            Case DbType.Guid
                sbRetVal.AppendFormat("DECLARE {0} AS UNIQUEIDENTIFIER", item.ParameterName)
                sbRetVal.AppendLine()
                sbRetVal.AppendFormat("SET {0} = '{1}'", item.ParameterName, item.Value)
                sbRetVal.AppendLine()

            Case DbType.Int32
                sbRetVal.AppendFormat("DECLARE {0} AS int", item.ParameterName)
                sbRetVal.AppendLine()
                sbRetVal.AppendFormat("SET {0} = {1}", item.ParameterName, item.Value)
                sbRetVal.AppendLine()

            Case Else
                Stop

        End Select
    Next

    sbRetVal.AppendLine("")
    sbRetVal.AppendLine(cmd.CommandText)

    Return sbRetVal.ToString()
End Function

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

Ping with timestamp on Windows CLI

You can do this in Bash (e.g. Linux or WSL):

ping 10.0.0.1 | while read line; do echo `date` - $line; done

Although it doesn't give the statistics you usually get when you hit ^C at the end.

Django: List field in model?

You can convert it into string by using JSON and store it as string.

For example,

In [3]: json.dumps([[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]])

Out[3]: '[[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]'

You can add a method into your class to convert it automatically for you.

import json


class Foobar(models.Model):
    foo = models.CharField(max_length=200)

    def set_foo(self, x):
        self.foo = json.dumps(x)

    def get_foo(self):
        return json.loads(self.foo)

If you're using Django 1.9 and postgresql, there is a new class called JSONField, you should use it instead. Here is a link to it

There is a good talk about PostgreSQL JSONs and Arrays on youtube. Watch it, it has very good information.

How can I find the latitude and longitude from address?

Geocoder coder = new Geocoder(this);
        List<Address> addresses;
        try {
            addresses = coder.getFromLocationName(address, 5);
            if (addresses == null) {
            }
            Address location = addresses.get(0);
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            Log.i("Lat",""+lat);
            Log.i("Lng",""+lng);
            LatLng latLng = new LatLng(lat,lng);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            googleMap.addMarker(markerOptions);
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,12));
        } catch (IOException e) {
            e.printStackTrace();
        }

How to find rows that have a value that contains a lowercase letter

Logically speaking Rohit's solution should have worked, but it didn't. I think SQL Management Studio messed up when trying to optimize this.

But by modifying the string before comparing them I was able to get the right results. This worked for me:

SELECT [ExternalId]
FROM [EquipmentSerialsMaster] where LOWER('0'+[ExternalId]) COLLATE Latin1_General_CS_AS != '0'+[ExternalId]

How to get everything after last slash in a URL?

You can do like this:

head, tail = os.path.split(url)

Where tail will be your file name.

golang why don't we have a set datastructure

Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...

The other reason is, that it's not clear at all what the "right" implementation of a set is:

  1. There is a functional approach:

    func IsInEvenNumbers(n int) bool {
        if n % 2 == 0 {
            return true
        }
       return false
    }
    

This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.

  1. Or you do a has-like approach like Dali showed.

A map does not have that problem, since you store something associated with the value.

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

You need some Administrator privilege to your account if your machine in local area network then you apply some administrator privilege to your User else you should start ide as Administrator...

How to create a new component in Angular 4 using CLI

If you want to create new component without .spec file, you can use

ng g c component-name --spec false

You can find these options using ng g c --help

Correct way to import lodash

import has from 'lodash/has'; is better because lodash holds all it's functions in a single file, so rather than import the whole 'lodash' library at 100k, it's better to just import lodash's has function which is maybe 2k.

How to declare a variable in a template in Angular

If you need autocomplete support from within in your templates from the Angular Language Service:

Synchronous:

myVar = { hello: '' };

<ng-container *ngIf="myVar; let var;">
  {{var.hello}}
</ng-container>

Using async pipe:

myVar$ = of({ hello: '' });

<ng-container *ngIf="myVar$ | async; let var;">
  {{var.hello}}
</ng-container>

invalid use of non-static member function

You shall pass a this pointer to tell the function which object to work on because it relies on that as opposed to a static member function.

How can I convert spaces to tabs in Vim or Linux?

If you have GNU coreutils installed, consider %!unexpand --first-only or for 4-space tabs, consider %!unexpand -t 4 --first-only (--first-only is present just in case you were accidentally invoking unexpand with --all).

Note that this will only replace the spaces preceding the prescribed tab stops, not the spaces that follow them; you will see no visual difference in vim unless you display tabs more literally; for example, my ~/.vimrc contains set list listchars=tab:?? (I suspect this is why you thought unexpand didn't work).

How can I restore the MySQL root user’s full privileges?

i also remove privileges of root and database not showing in mysql console when i was a root user, so changed user by mysql>mysql -u 'userName' -p; and password;

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';

FLUSH PRIVILEGES;

after this command it all show database's in root .

Thanks

How to ignore certain files in Git

By creating a .gitignore file. See here for details: Git Book - Ignoring files

Also check this one out: How do you make Git ignore files without using .gitignore?

what do these symbolic strings mean: %02d %01d?

Instead of Googling for %02d you should have been searching for sprintf() function.

%02d means "format the integer with 2 digits, left padding it with zeroes", so:

Format  Data   Result
%02d    1      01
%02d    11     11

Can I send a ctrl-C (SIGINT) to an application on Windows?

// Send [CTRL-C] to interrupt a batch file running in a Command Prompt window, even if the Command Prompt window is not visible,
// without bringing the Command Prompt window into focus.
// [CTRL-C] will have an effect on the batch file, but not on the Command Prompt  window itself -- in other words,
// [CTRL-C] will not have the same visible effect on a Command Prompt window that isn't running a batch file at the moment
// as bringing a Command Prompt window that isn't running a batch file into focus and pressing [CTRL-C] on the keyboard.
ulong ulProcessId = 0UL;
// hwC = Find Command Prompt window HWND
GetWindowThreadProcessId (hwC, (LPDWORD) &ulProcessId);
AttachConsole ((DWORD) ulProcessId);
SetConsoleCtrlHandler (NULL, TRUE);
GenerateConsoleCtrlEvent (CTRL_C_EVENT, 0UL);
SetConsoleCtrlHandler (NULL, FALSE);
FreeConsole ();

CSS: borders between table columns only

Borders on tables are always a bit flaky. One possibility would be to add a border-right declaration to each table cell except for the ones in right-most column. If you're using any kind of table-spacing this won't work very well.

Another option would be to use a 1px high background image with the borders inside it, but that'll only work if you can guarantee the width of each cell at all times.

Another possibility is to experiment with colgroup / col. This had fairly horrible support cross-browser the last time i looked at it but could have improved since then: http://www.webmasterworld.com/forum83/6826.htm

How to add a where clause in a MySQL Insert statement?

A conditional insert for use typically in a MySQL script would be:

insert into t1(col1,col2,col3,...)
select val1,val2,val3,...
  from dual
 where [conditional predicate];

You need to use dummy table dual.

In this example, only the second insert-statement will actually insert data into the table:

create table t1(col1 int);
insert into t1(col1) select 1 from dual where 1=0;
insert into t1(col1) select 2 from dual where 1=1;
select * from t1;
+------+
| col1 |
+------+
|    2 |
+------+
1 row in set (0.00 sec)

Active Directory LDAP Query by sAMAccountName and Domain

"Domain" is not a property of an LDAP object. It is more like the name of the database the object is stored in.

So you have to connect to the right database (in LDAP terms: "bind to the domain/directory server") in order to perform a search in that database.

Once you bound successfully, your query in it's current shape is all you need.

BTW: Choosing "ObjectCategory=Person" over "ObjectClass=user" was a good decision. In AD, the former is an "indexed property" with excellent performance, the latter is not indexed and a tad slower.

Add php variable inside echo statement as href link address?

Basically like this,

<?php
$link = ""; // Link goes here!
print "<a href="'.$link.'">Link</a>";
?>

Adjust icon size of Floating action button (fab)

The design guidelines defines two sizes and unless there is a strong reason to deviate from using either, the size can be controlled with the fabSize XML attribute of the FloatingActionButton component.

Consider specifying using either app:fabSize="normal" or app:fabSize="mini", e.g.:

<android.support.design.widget.FloatingActionButton
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:src="@drawable/ic_done_white_24px"
   app:fabSize="mini" />

Select records from NOW() -1 Day

Judging by the documentation for date/time functions, you should be able to do something like:

SELECT * FROM FOO
WHERE MY_DATE_FIELD >= NOW() - INTERVAL 1 DAY

What's the right way to create a date in Java?

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

'Source code does not match the bytecode' when debugging on a device

My app is compiled on API LEVEL 29, but debugging on real device on API LEVEL 28.I got the warning source code does not match the bytecode in AndroidStudio.I fixed it thought these steps:

  1. Go to Preferences>Instant Run: uncheck the instant run

  2. Go to Build>Clean Build

  3. Re-RUN the app

Now, the debug runs normal.

How to save username and password in Git?

just use

git config --global credential.helper store

and do the git pull, it will ask for username and password, from now on it will not provide any prompt for username and password it will store the details

How should you diagnose the error SEHException - External component has thrown an exception

Yes. This error is a structured exception that wasn't mapped into a .NET error. It's probably your DataGrid mapping throwing a native exception that was uncaught.

You can tell what exception is occurring by looking at the ExternalException.ErrorCode property. I'd check your stack trace, and if it's tied to the DevExpress grid, report the problem to them.

Adding click event for a button created dynamically using jQuery

Use a delegated event handler bound to the container:

$('#pg_menu_content').on('click', '#btn_a', function(){
    console.log(this.value);
});

That is, bind to an element that exists at the moment that the JS runs (I'm assuming #pg_menu_content exists when the page loads), and supply a selector in the second parameter to .on(). When a click occurs on #pg_menu_content element jQuery checks whether it applied to a child of that element which matches the #btn_a selector.

Either that or bind a standard (non-delegated) click handler after creating the button.

Either way, within the click handler this will refer to the button in question, so this.value will give you its value.

HTML Image not displaying, while the src url works

Your file needs to be located inside your www directory. For example, if you're using wamp server on Windows, j3evn.jpg should be located,

C:/wamp/www/img/j3evn.jpg

and you can access it in html via

<img class="sealImage" alt="Image of Seal" src="../img/j3evn.jpg">

Look for the www, public_html, or html folder belonging to your web server. Place all your files and resources inside that folder.

Hope this helps!

Merging cells in Excel using Apache POI

i made a method that merge cells and put border.

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    sheet.addMergedRegion(cellMerge);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);
    }

}



protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

How to create a Date in SQL Server given the Day, Month and Year as Integers

So, you can try this solution:

DECLARE @DAY INT = 25
DECLARE @MONTH INT  = 10 
DECLARE @YEAR INT = 2016
DECLARE @DATE AS DATETIME

SET @DATE = CAST(RTRIM(@YEAR * 10000 + @MONTH * 100 + @DAY) AS DATETIME) 

SELECT REPLACE(CONVERT(VARCHAR(10), @DATE, 102), '.', '-') AS EXPECTDATE

Or you can try this a few lines of code:

DECLARE @DAY INT = 25
DECLARE @MONTH INT  = 10 
DECLARE @YEAR INT = 2016

SELECT CAST(RTRIM(@YEAR * 10000 +'-' +  @MONTH * 100+ '-' + @DAY) AS DATE) AS EXPECTDATE

How to read barcodes with the camera on Android?

module app:

implementation 'com.google.zxing:core:3.2.1'

implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'

AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button BarCode;

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

        BarCode = findViewById(R.id.button_barcode);
        final Activity activity = this;

        BarCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IntentIntegrator intentIntegrator = new IntentIntegrator(activity);
                intentIntegrator.setDesiredBarcodeFormats(intentIntegrator.ALL_CODE_TYPES);
                intentIntegrator.setBeepEnabled(false);
                intentIntegrator.setCameraId(0);
                intentIntegrator.setPrompt("SCAN");
                intentIntegrator.setBarcodeImageEnabled(false);
                intentIntegrator.initiateScan();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        IntentResult Result = IntentIntegrator.parseActivityResult(requestCode , resultCode ,data);
        if(Result != null){
            if(Result.getContents() == null){
                Log.d("MainActivity" , "cancelled scan");
                Toast.makeText(this, "cancelled", Toast.LENGTH_SHORT).show();
            }
            else {
                Log.d("MainActivity" , "Scanned");
                Toast.makeText(this,"Scanned -> " + Result.getContents(), Toast.LENGTH_SHORT).show();
            }
        }
        else {
            super.onActivityResult(requestCode , resultCode , data);
        }
    }
}

select2 onchange event only works once

Apparently the change event is not fired if a selection already exists when using data. I ended up updating the data manually on select to resolve the problem.

$("#search_code").on("select2-selecting", function(e) {
    $("#search_code").select2("data",e.choice);
});

I know this is pretty late but hopefully this answer will save others time.

No Activity found to handle Intent : android.intent.action.VIEW

This exception can raise when you handle Deep linking or URL for a browser, if there is no default installed. In case of Deep linking there may be no application installed that can process a link in format myapp://mylink.

You can use the tangerine solution for API up to 29:

private fun openUrl(url: String) {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    val activityInfo = intent.resolveActivityInfo(packageManager, intent.flags)
    if (activityInfo?.exported == true) {
        startActivity(intent)
    } else {
        Toast.makeText(
            this,
            "No application that can handle this link found",
            Toast.LENGTH_SHORT
        ).show()
    }
}

For API >= 30 see intent.resolveActivity returns null in API 30.

Storing files in SQL Server

There's a really good paper by Microsoft Research called To Blob or Not To Blob.

Their conclusion after a large number of performance tests and analysis is this:

  • if your pictures or document are typically below 256K in size, storing them in a database VARBINARY column is more efficient

  • if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)

  • in between those two, it's a bit of a toss-up depending on your use

If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.

For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".

Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:

 CREATE TABLE dbo.YourTable
     (....... define the fields here ......)
     ON Data                   -- the basic "Data" filegroup for the regular data
     TEXTIMAGE_ON LARGE_DATA   -- the filegroup for large chunks of data

Check out the MSDN intro on filegroups, and play around with it!

Run a batch file with Windows task scheduler

Make sure "Start In" does NOT end with a BACKSLASH.

How can I directly view blobs in MySQL Workbench

I pieced a few of the other posts together, as the workbench 'preferences' fix did not work for me. (WB 6.3)

SELECT CAST(`column` AS CHAR(10000) CHARACTER SET utf8) FROM `table`;

Get Root Directory Path of a PHP project

I want to point to the way Wordpress handles this:

define( 'ABSPATH', dirname( __FILE__ ) . '/' );

As Wordpress is very heavy used all over the web and also works fine locally I have much trust in this method. You can find this definition on the bottom of your wordpress wp-config.php file

What equivalents are there to TortoiseSVN, on Mac OSX?

Have a look at this archived question: TortoiseSVN for Mac? at superuser. (Original question was removed, so only archive remains.)

Have a look at this page for more likely up to date alternatives to TortoiseSVN for Mac: Alternative to: TortoiseSVN

ConcurrentModificationException for ArrayList

I like a reverse order for loop such as:

int size = list.size();
for (int i = size - 1; i >= 0; i--) {
    if(remove){
        list.remove(i);
    }
}

because it doesn't require learning any new data structures or classes.

Bootstrap number validation

you can use PATTERN:

<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors?.pattern">Is not a number</div>
</div>

getting the X/Y coordinates of a mouse click on an image with jQuery

Here is a better script:

$('#mainimage').click(function(e)
{   
    var offset_t = $(this).offset().top - $(window).scrollTop();
    var offset_l = $(this).offset().left - $(window).scrollLeft();

    var left = Math.round( (e.clientX - offset_l) );
    var top = Math.round( (e.clientY - offset_t) );

    alert("Left: " + left + " Top: " + top);

});

How can I install Python's pip3 on my Mac?

I ran the below where <user>:<group> matched the other <user>:<group> for other files in the /usr/local/lib/python3.7/site-packages/ directory:

sudo chown -R <user>:<group> /usr/local/lib/python3.7/site-packages/pip*
brew postinstall python3

What is the purpose of Order By 1 in SQL select statement?

This will sort your results by the first column returned. In the example it will sort by payment_date.

Darken background image on hover

you can use this:

box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);

as seen on: https://stackoverflow.com/a/24084708/8953378

Why doesn't catching Exception catch RuntimeException?

catch (Exception ex) { ... }

WILL catch RuntimeException.

Whatever you put in catch block will be caught as well as the subclasses of it.

SQL order string as number

If you are using AdonisJS and have mixed IDs such as ABC-202, ABC-201..., you can combine raw queries with Query Builder and implement the solution above (https://stackoverflow.com/a/25061144/4040835) as follows:

const sortField =
  'membership_id'
const sortDirection =
  'asc'
const subquery = UserProfile.query()
  .select(
    'user_profiles.id',
    'user_profiles.user_id',
    'user_profiles.membership_id',
    'user_profiles.first_name',
    'user_profiles.middle_name',
    'user_profiles.last_name',
    'user_profiles.mobile_number',
    'countries.citizenship',
    'states.name as state_of_origin',
    'user_profiles.gender',
    'user_profiles.created_at',
    'user_profiles.updated_at'
  )
  .leftJoin(
    'users',
    'user_profiles.user_id',
    'users.id'
  )
  .leftJoin(
    'countries',
    'user_profiles.nationality',
    'countries.id'
  )
  .leftJoin(
    'states',
    'user_profiles.state_of_origin',
    'states.id'
  )
  .orderByRaw(
    `SUBSTRING(:sortField:,3,15)*1 ${sortDirection}`,
    {
      sortField: sortField,
    }
  )
  .paginate(
    page,
    per_page
  )

NOTES: In this line: SUBSTRING(:sortField:,3,15)*1 ${sortDirection},

  1. '3' stands for the index number of the last non-numerical character before the digits. If your mixed ID is "ABC-123," your index number will be 4.
  2. '15' is used to catch as any number of digits as possible after the hyphen.
  3. '1' performs a mathematical operation on the substring which effectively casts the substring to a number.

Ref 1: You can read more about parameter bindings in raw queries here: https://knexjs.org/#Raw-Bindings Ref 2: Adonis Raw Queries: https://adonisjs.com/docs/4.1/query-builder#_raw_queries

Clean out Eclipse workspace metadata

In some cases, I could prevent Eclipse from crashing during startup by deleting a .snap file in your workspace meta-data (.metadata/.plugins/org.eclipse.core.resources/.snap).

See also https://bugs.eclipse.org/bugs/show_bug.cgi?id=149121 (the bug has been closed, but happened to me recently)

Android fastboot waiting for devices

The short version of the page linked by D Shu (and without the horrible popover ads) is that this "waiting for device" problem happens when the USB device node is not accessible to your current user. The USB id is different in fastboot mode, so you can easily have permission to it in adb but not in fastboot.

To fix it (on Ubuntu; other systems may be slightly different):

Run lsusb -v | less and find the relevant section which will look something like this:

Bus 001 Device 027: ID 18d1:4e30 Google Inc. 
Couldn't open device, some information will be missing
Device Descriptor:
...
  idVendor           0x18d1 Google Inc.

Now do

sudo vi /etc/udev/rules.d/11-android.rules

it's ok if that file does not yet exist; create it with a line like this, inserting your own username and vendor id:

SUBSYSTEMS=="usb", ATTRS{idVendor}=="18d1", MODE="0640", OWNER="mbp"

then

sudo service udev restart

then verify the device node permissions have changed:

ls -Rl /dev/bus/usb

The even shorter cheesy version is to just run fastboot as root. But then you need to run every command that talks to the device as root, which tends to cause other complications. Simpler just to fix the permissions in the long run.

Output of git branch in tree like fashion

You can use a tool called gitk.

How to refresh an access form

You can repaint and / or requery:

On the close event of form B:

Forms!FormA.Requery

Is this what you mean?

Count number of lines in a git repository

xargs will do what you want:

git ls-files | xargs cat | wc -l

But with more information and probably better, you can do:

git ls-files | xargs wc -l

Share application "link" in Android

To automatically fill in the application name and application id you could use this:

int applicationNameId = context.getApplicationInfo().labelRes;
final String appPackageName = context.getPackageName();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, activity.getString(applicationNameId));
String text = "Install this cool application: ";
String link = "https://play.google.com/store/apps/details?id=" + appPackageName;
i.putExtra(Intent.EXTRA_TEXT, text + " " + link);
startActivity(Intent.createChooser(i, "Share link:"));

How can I fill out a Python string with spaces?

You can do this with str.ljust(width[, fillchar]):

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).

>>> 'hi'.ljust(10)
'hi        '

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

You may convert latitude-longitude to UTM format which is metric format that may help you to calculate distances. Then you can easily decide if point falls into specific location.

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

Same error, different situation. I'm posting this here because someone might be in same situation as mine.

I was using context API like below.

export const withDB = Component => props => {
    <DBContext.Consumer>
        {db => <Component {...props} db={db} />}
    </DBContext.Consumer>
}

So basically the error message is giving you the answer.

Nothing was returned from render. This usually means a return statement is missing

withDB should return a html block. But it wasn't returning anything. Revising my code to below solved my issue.

export const withDB = Component => props => {
  return (
    <DBContext.Consumer>
        {db => <Component {...props} db={db} />}
    </DBContext.Consumer>
  )
}

Can you overload controller methods in ASP.NET MVC?

If this is an attempt to use one GET action for several views that POST to several actions with different models, then try add a GET action for each POST action that redirects to the first GET to prevent 404 on refresh.

Long shot but common scenario.

What's the best way to select the minimum value from several columns?

I know that question is old, but I was still in the need of the answer and was not happy with other answers so I had to devise my own which is a twist on @paxdiablo´s answer.


I came from land of SAP ASE 16.0, and I only needed a peek at statistics of certain data which are IMHO validly stored in different columns of a single row (they represent different times - when arrival of something was planned, what it was expected when the action started and finally what was the actual time). Thus I had transposed columns into the rows of temporary table and preformed my query over this as usually.

N.B. Not the one-size-fits-all solution ahead!

CREATE TABLE #tempTable (ID int, columnName varchar(20), dataValue int)

INSERT INTO #tempTable 
  SELECT ID, 'Col1', Col1
    FROM sourceTable
   WHERE Col1 IS NOT NULL
INSERT INTO #tempTable 
  SELECT ID, 'Col2', Col2
    FROM sourceTable
   WHERE Col2 IS NOT NULL
INSERT INTO #tempTable 
  SELECT ID, 'Col3', Col3
    FROM sourceTable
   WHERE Col3 IS NOT NULL

SELECT ID
     , min(dataValue) AS 'Min'
     , max(dataValue) AS 'Max'
     , max(dataValue) - min(dataValue) AS 'Diff' 
  FROM #tempTable 
  GROUP BY ID

This took some 30 seconds on source set of 630000 rows and used only index-data, so not the thing to run in time-critical process but for things like one-time data inspection or end-of-the-day report you might be fine (but verify this with your peers or superiors, please!). Main bonus of this style for me was that I could readily use more/less columns and change grouping, filtering, etc., especially once data was copyied over.

The additional data (columnName, maxes, ...) were to aid me in my search, so you might not need them; I left them here to maybe spark some ideas :-).

Can't drop table: A foreign key constraint fails

Try this:

SELECT * 
FROM information_schema.KEY_COLUMN_USAGE 
WHERE REFERENCED_TABLE_NAME = 'YourTable';

This should deliver you which Tables have references to the table you want to drop, once you drop these references, or the datasets which reference datasets in this table you will be able to drop the table

How to install requests module in Python 3.4, instead of 2.7

On Windows with Python v3.6.5

py -m pip install requests

How do I get the App version and build number using Swift?

if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            self.lblAppVersionValue.text = version
        }

Creating a JSON array in C#

You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:

public class Item
{
    public string name { get; set; }
    public string index { get; set; }
    public string optional { get; set; }
}

public class RootObject
{
    public List<Item> items { get; set; }
}

Usage:

var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item> 
                          {
                             new Item { name = "test1", index = "index1" },
                             new Item { name = "test2", index = "index2" }
                          };

And in the result you won't have to change things several times if you need to change data-structure.

p.s. Here's very nice tool for complex jsons

Virtual Memory Usage from Java under Linux, too much memory used

No, you can't configure memory amount needed by VM. However, note that this is virtual memory, not resident, so it just stays there without harm if not actually used.

Alernatively, you can try some other JVM then Sun one, with smaller memory footprint, but I can't advise here.

Call Python function from MATLAB

The simplest way to do this is to use MATLAB's system function.

So basically, you would execute a Python function on MATLAB as you would do on the command prompt (Windows), or shell (Linux):

system('python pythonfile.py')

The above is for simply running a Python file. If you wanted to run a Python function (and give it some arguments), then you would need something like:

system('python pythonfile.py argument')

For a concrete example, take the Python code in Adrian's answer to this question, and save it to a Python file, that is test.py. Then place this file in your MATLAB directory and run the following command on MATLAB:

system('python test.py 2')

And you will get as your output 4 or 2^2.

Note: MATLAB looks in the current MATLAB directory for whatever Python file you specify with the system command.

This is probably the simplest way to solve your problem, as you simply use an existing function in MATLAB to do your bidding.

Change font color and background in html on mouseover

You'd better use CSS for this:

td{
    background-color:black;
    color:white;
}
td:hover{
    background-color:white;
    color:black;
}

If you want to use these styles for only a specific set of elements, you should give your td a class (or an ID, if it's the only element which'll have that style).

Example :

HTML

<td class="whiteHover"></td>

CSS

.whiteHover{
    /* Same style as above */
}

Here's a reference on MDN for :hover pseudo class.

how to load url into div tag

<html>
<head>
<script type="text/javascript">
    $(document).ready(function(){
    $("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content"></div>
</body>
</html>

Benefits of using the conditional ?: (ternary) operator

There is some performance benefit of using the the ? operator in eg. MS Visual C++, but this is a really a compiler specific thing. The compiler can actually optimize out the conditional branch in some cases.

How to calculate the sum of the datatable column in asp.net?

  public decimal Total()
    {
      decimal decTotal=(datagridview1.DataSource as DataTable).Compute("Sum(FieldName)","");
      return decTotal;
    }

PHP FPM - check if running

Assuming you are on Linux, check if php-fpm is running by searching through the process list:

ps aux | grep php-fpm

If running over IP (as opposed to over Unix socket) then you can also check for the port:

netstat -an | grep :9000

Or using nmap:

nmap localhost -p 9000

Lastly, I've read that you can request the status, but in my experience this has proven unreliable:

/etc/init.d/php5-fpm status

How can I change the default width of a Twitter Bootstrap modal box?

Achieved expected result using,

.modal-dialog {
    width: 41% !important;
}

How to use apply a custom drawable to RadioButton?

In programmatically, add the background image

minSdkVersion 16

RadioGroup rg = new RadioGroup(this);
RadioButton radioButton = new RadioButton(this);
radioButton.setBackground(R.drawable.account_background);
rg.addView(radioButton);

How to hide 'Back' button on navigation bar on iPhone?

It wasn't working for me in all cases when I set

self.navigationItem.hidesBackButton = YES;

in viewWillAppear or ViewDidLoad, but worked perfectly when I set it in init of the viewController.

How should I edit an Entity Framework connection string?

Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.

Fatal error: unexpectedly found nil while unwrapping an Optional values

You can prevent the crash from happening by safely unwrapping cell.labelTitle with an if let statement.

if let label = cell.labelTitle{
    label.text = "This is a title"
}

You will still have to do some debugging to see why you are getting a nil value there though.

Delete specific line number(s) from a text file using sed?

I would like to propose a generalization with awk.

When the file is made by blocks of a fixed size and the lines to delete are repeated for each block, awk can work fine in such a way

awk '{nl=((NR-1)%2000)+1; if ( (nl<714) || ((nl>1025)&&(nl<1029)) ) print  $0}'
 OriginFile.dat > MyOutputCuttedFile.dat

In this example the size for the block is 2000 and I want to print the lines [1..713] and [1026..1029].

  • NR is the variable used by awk to store the current line number.
  • % gives the remainder (or modulus) of the division of two integers;
  • nl=((NR-1)%BLOCKSIZE)+1 Here we write in the variable nl the line number inside the current block. (see below)
  • || and && are the logical operator OR and AND.
  • print $0 writes the full line

Why ((NR-1)%BLOCKSIZE)+1:
(NR-1) We need a shift of one because 1%3=1, 2%3=2, but 3%3=0.
  +1   We add again 1 because we want to restore the desired order.

+-----+------+----------+------------+
| NR  | NR%3 | (NR-1)%3 | (NR-1)%3+1 |
+-----+------+----------+------------+
|  1  |  1   |    0     |     1      |
|  2  |  2   |    1     |     2      |
|  3  |  0   |    2     |     3      |
|  4  |  1   |    0     |     1      |
+-----+------+----------+------------+

Manage toolbar's navigation and back button from fragment in android

(Kotlin) In the activity hosting the fragment(s):

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            onBackPressed()
            return true
        }
    }
    return super.onOptionsItemSelected(item)
}

I have found that when I add fragments to a project, they show the action bar home button by default, to remove/disable it put this in onViewCreated() (use true to enable it if it is not showing):

val actionBar = this.requireActivity().actionBar
    actionBar?.setDisplayHomeAsUpEnabled(false)

Reordering Chart Data Series

These are the buttons UP/DOWN

enter image description here

Resize on div element

Just try this func (it may work not only for divs):

function resized(elem, func = function(){}, args = []){
    elem = jQuery(elem);
    func = func.bind(elem);
    var h = -1, w = -1;
    setInterval(function(){
        if (elem.height() != h || elem.width() != w){
            h = elem.height();
            w = elem.width();
            func.apply(null, args);
        }
    }, 100);
}

You can use it like this

resized(/*element*/ '.advs-columns-main > div > div', /*callback*/ function(a){
    console.log(a);
    console.log(this); //for accessing the jQuery element you passed
}, /*callback arguments in array*/ ['I\'m the first arg named "a"!']);

UPDATE: You can also use more progressive watcher (it can work for any objects, not only DOM elements):

function changed(elem, propsToBeChanged, func = function(){}, args = [], interval = 100){
        func = func.bind(elem);
        var currentVal = {call: {}, std: {}};
        $.each(propsToBeChanged, (property, needCall)=>{
            needCall = needCall ? 'call' : 'std';
            currentVal[needCall][property] = new Boolean(); // is a minimal and unique value, its equivalent comparsion with each other will always return false
        });
        setInterval(function(){
            $.each(propsToBeChanged, (property, needCall)=>{
                try{
                    var currVal = needCall ? elem[property]() : elem[property];
                } catch (e){ // elem[property] is not a function anymore
                    var currVal = elem[property];
                    needCall = false;
                    propsToBeChanged[property] = false;
                }
                needCall = needCall ? 'call' : 'std';
                if (currVal !== currentVal[needCall][property]){
                    currentVal[needCall][property] = currVal;
                    func.apply(null, args);
                }
            });
        }, interval);
    }

Just try it:

var b = '2',
    a = {foo: 'bar', ext: ()=>{return b}};
changed(a, {
// prop name || do eval like a function?
    foo:        false,
    ext:        true
}, ()=>{console.log('changed')})

It will log 'changed' every time when you change b, a.foo or a.ext directly

Get everything after and before certain character in SQL Server

I know this has been a while.. but here is an idea

declare @test varchar(25) = 'images/test.jpg'

select
 @test as column_name
 , parsename(replace(@test,'/','.'),1) as jpg
 ,parsename(replace(@test,'/','.'),2) as test
  ,parsename(replace(@test,'/','.'),3) as images

Is there a css cross-browser value for "width: -moz-fit-content;"?

In similar case I used: white-space: nowrap;

Run a command shell in jenkins

Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"

*Don't write bin at the end

SQL Query to search schema of all tables

  select object_name(c.object_id) as table_name
    , schema_name(t.schema_id) as schema_name
    from sys.columns c
    join sys.tables t on c.object_id = t.object_id
     where c.name=N'CreatedDate';

It gets a little more complicated if you want alsoother table properties, but you'll refer to the object catalog views like sys.tables, sys.columns etc.

How to enable TLS 1.2 in Java 7

The stated answers are correct, but I'm just sharing one additional gotcha that was applicable to my case: in addition to using setProtocol/withProtocol, you may have some nasty jars that won't go away even if have the right jars plus an old one:

Remove

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

Retain

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.6</version>
</dependency>

Java is backward compatible, but most libraries are not. Each day that passes the more I wish shared libraries were outlawed with this lack of accountability.

Further info

java version "1.7.0_80"
Java(TM) SE Runtime Environment (build 1.7.0_80-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.80-b11, mixed mode)

Combine :after with :hover

in scss

&::after{
content: url(images/RelativeProjectsArr.png);
margin-left:30px;
}

&:hover{
    background-color:$turkiz;
    color:#e5e7ef;

    &::after{
    content: url(images/RelativeProjectsArrHover.png);
    }
}

Generate your own Error code in swift 3

 let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invaild UserName or Password"]) as Error
            self.showLoginError(error)

create an NSError object and typecast it to Error ,show it anywhere

private func showLoginError(_ error: Error?) {
    if let errorObj = error {
        UIAlertController.alert("Login Error", message: errorObj.localizedDescription).action("OK").presentOn(self)
    }
}

Check if date is a valid one

Here you go: Working Fidddle

$(function(){
  var dateFormat = 'DD-MM-YYYY';
  alert(moment(moment("2012-10-19").format(dateFormat),dateFormat,true).isValid());
});

powershell - extract file name and extension

PS C:\Windows\System32\WindowsPowerShell\v1.0>split-path "H:\Documents\devops\tp-mkt-SPD-38.4.10.msi" -leaf
tp-mkt-SPD-38.4.10.msi

PS C:\Windows\System32\WindowsPowerShell\v1.0> $psversiontable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5477
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

How to change the default encoding to UTF-8 for Apache?

For completeness, on Apache2 on Ubuntu, you will find the default charset in charset.conf in conf-available.

Uncomment the line

AddDefaultCharset UTF-8

Error loading the SDK when Eclipse starts

The issue is still coming for API 23. To get rid from this we have to uninstall android Wear packages for both API 22 and API 23 also (till current update).

enter image description here

Renaming columns in Pandas

df = pd.DataFrame({'$a': [1], '$b': [1], '$c': [1], '$d': [1], '$e': [1]})

If your new list of columns is in the same order as the existing columns, the assignment is simple:

new_cols = ['a', 'b', 'c', 'd', 'e']
df.columns = new_cols
>>> df
   a  b  c  d  e
0  1  1  1  1  1

If you had a dictionary keyed on old column names to new column names, you could do the following:

d = {'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}
df.columns = df.columns.map(lambda col: d[col])  # Or `.map(d.get)` as pointed out by @PiRSquared.
>>> df
   a  b  c  d  e
0  1  1  1  1  1

If you don't have a list or dictionary mapping, you could strip the leading $ symbol via a list comprehension:

df.columns = [col[1:] if col[0] == '$' else col for col in df]

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

One word answer: asynchronicity.

Forewords

This topic has been iterated at least a couple of thousands of times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:


The answer to the question at hand

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been canceled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, the asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

async code highlighted

In short, the callback functions are created synchronously but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs too inside the callback function would output the expected result, because the result is available at that point.

Implementing your own callback logic

Often you need to do more things with the result from an asynchronous function or do different things with the result depending on where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Code snippet of the above example:

_x000D_
_x000D_
// 1. Call helloCatAsync passing a callback function,_x000D_
//    which will be called receiving the result from the async operation_x000D_
console.log("1. function called...")_x000D_
helloCatAsync(function(result) {_x000D_
    // 5. Received the result from the async function,_x000D_
    //    now do whatever you want with it:_x000D_
    console.log("5. result is: ", result);_x000D_
});_x000D_
_x000D_
// 2. The "callback" parameter is a reference to the function which_x000D_
//    was passed as argument from the helloCatAsync call_x000D_
function helloCatAsync(callback) {_x000D_
    console.log("2. callback here is the function passed as argument above...")_x000D_
    // 3. Start async operation:_x000D_
    setTimeout(function() {_x000D_
    console.log("3. start async operation...")_x000D_
    console.log("4. finished async operation, calling the callback, passing the result...")_x000D_
        // 4. Finished async operation,_x000D_
        //    call the callback passing the result as argument_x000D_
        callback('Nya');_x000D_
    }, Math.random() * 2000);_x000D_
}
_x000D_
_x000D_
_x000D_

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Promises

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of the asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:


More reading material about JavaScript asynchronicity


Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputations can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

Setting a windows batch file variable to the day of the week

Rem Remove the end comma and add /A to set for this line worked for me.
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10 

CSS I want a div to be on top of everything

Yes, in order for the z-index to work, you'll need to give the element a position: absolute or a position: relative property.

But... pay attention to parents!

You have to go up the nodes of the elements to check if at the level of the common parent the first descendants have a defined z-index.

All other descendants can never be in the foreground if at the base there is a lower definite z-index.

In this snippet example, div1-2-1 has a z-index of 1000 but is nevertheless under the div1-1-1 which has a z-index of 3.

This is because div1-1 has a z-index greater than div1-2.

enter image description here

_x000D_
_x000D_
.div {
  
}

#div1 {
  z-index: 1;
  position: absolute;
  width: 500px;
  height: 300px;
  border: 1px solid black;
}

#div1-1 {
  z-index: 2;
  position: absolute;
  left: 230px;
  width: 200px;
  height: 200px;
  top: 31px;
  background-color: indianred;
}

#div1-1-1 {
  z-index: 3;
  position: absolute;
  top: 50px;
  width: 100px;
  height: 100px;
  background-color: burlywood;
}

#div1-2 {
  z-index: 1;
  position: absolute;
  width: 200px;
  height: 200px;
  left: 80px;
  top: 5px;
  background-color: red;
}

#div1-2-1 {
  z-index: 1000;
  position: absolute;
  left: 70px;
  width: 120px;
  height: 100px;
  top: 10px;
  color: red;
  background-color: lightyellow;
}

.blink {
  animation: blinker 1s linear infinite;
}

@keyframes blinker {
  50% {
    opacity: 0;
  }
}

.rotate {
  writing-mode: vertical-rl;
  padding-left: 50px;
  font-weight: bold;
  font-size: 20px;
}
_x000D_
<div class="div" id="div1">div1</br>z-index: 1
  <div class="div" id="div1-1">div1-1</br>z-index: 2
    <div class="div" id="div1-1-1">div1-1-1</br>z-index: 3</div>
  </div>
  
  <div class="div" id="div1-2">div1-2</br>z-index: 1</br><span class='rotate blink'><=</span>
    <div class="div" id="div1-2-1"><span class='blink'>z-index: 1000!!</span></br>div1-2-1</br><span class='blink'> because =></br>(same</br>   parent)</span></div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to present popover properly in iOS 8

In iOS9 UIPopoverController is depreciated. So can use the below code for Objective-C version above iOS9.x,

- (IBAction)onclickPopover:(id)sender {
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *viewController = [sb instantiateViewControllerWithIdentifier:@"popover"];

viewController.modalPresentationStyle = UIModalPresentationPopover;
viewController.popoverPresentationController.sourceView = self.popOverBtn;
viewController.popoverPresentationController.sourceRect = self.popOverBtn.bounds;
viewController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
[self presentViewController:viewController animated:YES completion:nil]; }

Python safe method to get value of nested dictionary

def safeget(_dct, *_keys):
    if not isinstance(_dct, dict): raise TypeError("Is not instance of dict")
    def foo(dct, *keys):
        if len(keys) == 0: return dct
        elif not isinstance(_dct, dict): return None
        else: return foo(dct.get(keys[0], None), *keys[1:])
    return foo(_dct, *_keys)

assert safeget(dict()) == dict()
assert safeget(dict(), "test") == None
assert safeget(dict([["a", 1],["b", 2]]),"a", "d") == None
assert safeget(dict([["a", 1],["b", 2]]),"a") == 1
assert safeget({"a":{"b":{"c": 2}},"d":1}, "a", "b")["c"] == 2

Install an apk file from command prompt?

Open Terminal in Android Studio

You might see

C:\Users\nikhil\AppData\Local\Android\Sdk\platform-tools>

copy and paste your apk which you want to install on above path inside platform-tools. In my case app-qa-debug.apk I kept inside platform-tools folder.

install command

adb install app-qa-debug.apk

so in the terminal you could see something

C:\Users\nikhil\AppData\Local\Android\Sdk\platform-tools>adb install app-qa-debug.apk

post-installation you could get the message as

Performing Streamed

Install Success

Converting a PDF to PNG

To convert pdf to image files use following commands:

For PNG gs -sDEVICE=png16m -dTextAlphaBits=4 -r300 -o a.png a.pdf

For JPG gs -sDEVICE=jpeg -dTextAlphaBits=4 -r300 -o a.jpg a.pdf

If you have multiple pages add to name %03d gs -o a%03d.jpg a.pdf

What each option means:

  • sDEVICE={jpeg,pngalpha,png16m...} - filetype
  • -o - output file (%stdout to stdout)
  • -dTextAlphaBits=4 - font antialiasing.
  • -r300 - 300 dpi

Custom CSS Scrollbar for Firefox

Here I have tried this CSS for all major browser & tested: Custom color are working fine on scrollbar.

Yes, there are limitations on several versions of different browsers.

_x000D_
_x000D_
/* Only Chrome */
html::-webkit-scrollbar {width: 17px;}
html::-webkit-scrollbar-thumb {background-color: #0064a7; background-clip: padding-box; border: 1px solid #8ea5b5;}
html::-webkit-scrollbar-track {background-color: #8ea5b5; }
::-webkit-scrollbar-button {background-color: #8ea5b5;}
/* Only IE */
html {scrollbar-face-color: #0064a7; scrollbar-shadow-color: #8ea5b5; scrollbar-highlight-color: #8ea5b5;}
/* Only FireFox */
html {scrollbar-color: #0064a7 #8ea5b5;}
/* View Scrollbar */
html {overflow-y: scroll;overflow-x: hidden;}
_x000D_
<!doctype html>
<html lang="en" class="no-js">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <header>
        <div id="logo"><img src="/logo.png">HTML5&nbsp;Layout</div>
        <nav>  
            <ul>
                <li><a href="/">Home</a>
                <li><a href="https://html-css-js.com/">HTML</a>
                <li><a href="https://html-css-js.com/css/code/">CSS</a>
                <li><a href="https://htmlcheatsheet.com/js/">JS</a>
            </ul>
        </nav>
    </header>
    <section>
        <strong>Demonstration of a simple page layout using HTML5 tags: header, nav, section, main, article, aside, footer, address.</strong>
    </section>
    <section id="pageContent">
        <main role="main">
            <article>
                <h2>Stet facilis ius te</h2>
                <p>Lorem ipsum dolor sit amet, nonumes voluptatum mel ea, cu case ceteros cum. Novum commodo malorum vix ut. Dolores consequuntur in ius, sale electram dissentiunt quo te. Cu duo omnes invidunt, eos eu mucius fabellas. Stet facilis ius te, quando voluptatibus eos in. Ad vix mundi alterum, integre urbanitas intellegam vix in.</p>
            </article>
            <article>
                <h2>Illud mollis moderatius</h2>
                <p>Eum facete intellegat ei, ut mazim melius usu. Has elit simul primis ne, regione minimum id cum. Sea deleniti dissentiet ea. Illud mollis moderatius ut per, at qui ubique populo. Eum ad cibo legimus, vim ei quidam fastidii.</p>
            </article>
            <article>
                <h2>Ex ignota epicurei quo</h2>
                <p>Quo debet vivendo ex. Qui ut admodum senserit partiendo. Id adipiscing disputando eam, sea id magna pertinax concludaturque. Ex ignota epicurei quo, his ex doctus delenit fabellas, erat timeam cotidieque sit in. Vel eu soleat voluptatibus, cum cu exerci mediocritatem. Malis legere at per, has brute putant animal et, in consul utamur usu.</p>
            </article>
            <article>
                <h2>His at autem inani volutpat</h2>
                <p>Te has amet modo perfecto, te eum mucius conclusionemque, mel te erat deterruisset. Duo ceteros phaedrum id, ornatus postulant in sea. His at autem inani volutpat. Tollit possit in pri, platonem persecuti ad vix, vel nisl albucius gloriatur no.</p>
            </article>
        </main>
        <aside>
            <div>Sidebar 1</div>
            <div>Sidebar 2</div>
            <div>Sidebar 3</div>
        </aside>
    </section>
    <footer>
        <p>&copy; You can copy, edit and publish this template but please leave a link to our website | <a href="https://html5-templates.com/" target="_blank" rel="nofollow">HTML5 Templates</a></p>
        <address>
            Contact: <a href="mailto:[email protected]">Mail me</a>
        </address>
    </footer>


</body>

</html>
_x000D_
_x000D_
_x000D_

Iterating over every property of an object in javascript using Prototype?

There's no need for Prototype here: JavaScript has for..in loops. If you're not sure that no one messed with Object.prototype, check hasOwnProperty() as well, ie

for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
        doSomethingWith(obj[prop]);
}

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

How to verify a Text present in the loaded page through WebDriver

For Ruby programmers here is how you can assert. Have to include Minitest to get the asserts

    assert(@driver.find_element(:tag_name => "body").text.include?("Name"))

Checking if a character is a special character in Java

Take a look at class java.lang.Character static member methods (isDigit, isLetter, isLowerCase, ...)

Example:

String str = "Hello World 123 !!";
int specials = 0, digits = 0, letters = 0, spaces = 0;
for (int i = 0; i < str.length(); ++i) {
   char ch = str.charAt(i);
   if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) {
      ++specials;
   } else if (Character.isDigit(ch)) {
      ++digits;
   } else if (Character.isSpace(ch)) {
      ++spaces;
   } else {
      ++letters;
   }
}

How to convert a string of numbers to an array of numbers?

My 2 cents for golfers:

b="1,2,3,4".split`,`.map(x=>+x)

backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(','). The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x (which is even shorter than the Number function (5 chars instead of 6)) is equivalent to :

function(x){return parseInt(x,10)}// version from techfoobar
(x)=>{return parseInt(x)}         // lambda are shorter and parseInt default is 10
(x)=>{return +x}                  // diff. with parseInt in SO but + is better in this case
x=>+x                             // no multiple args, just 1 function call

I hope it is a bit more clear.

Accessing private member variables from prototype-defined functions

I'm late to the party, but I think I can contribute. Here, check this out:

_x000D_
_x000D_
// 1. Create closure_x000D_
var SomeClass = function() {_x000D_
  // 2. Create `key` inside a closure_x000D_
  var key = {};_x000D_
  // Function to create private storage_x000D_
  var private = function() {_x000D_
    var obj = {};_x000D_
    // return Function to access private storage using `key`_x000D_
    return function(testkey) {_x000D_
      if(key === testkey) return obj;_x000D_
      // If `key` is wrong, then storage cannot be accessed_x000D_
      console.error('Cannot access private properties');_x000D_
      return undefined;_x000D_
    };_x000D_
  };_x000D_
  var SomeClass = function() {_x000D_
    // 3. Create private storage_x000D_
    this._ = private();_x000D_
    // 4. Access private storage using the `key`_x000D_
    this._(key).priv_prop = 200;_x000D_
  };_x000D_
  SomeClass.prototype.test = function() {_x000D_
    console.log(this._(key).priv_prop); // Using property from prototype_x000D_
  };_x000D_
  return SomeClass;_x000D_
}();_x000D_
_x000D_
// Can access private property from within prototype_x000D_
var instance = new SomeClass();_x000D_
instance.test(); // `200` logged_x000D_
_x000D_
// Cannot access private property from outside of the closure_x000D_
var wrong_key = {};_x000D_
instance._(wrong_key); // undefined; error logged
_x000D_
_x000D_
_x000D_

I call this method accessor pattern. The essential idea is that we have a closure, a key inside the closure, and we create a private object (in the constructor) that can only be accessed if you have the key.

If you are interested, you can read more about this in my article. Using this method, you can create per object properties that cannot be accessed outside of the closure. Therefore, you can use them in constructor or prototype, but not anywhere else. I haven't seen this method used anywhere, but I think it's really powerful.

scale fit mobile web content using viewport meta tag

For Android there is the addition of target-density tag.

target-densitydpi=device-dpi

So, the code would look like

<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />

Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.

Styling an input type="file" button

Maybe a lot of awnsers. But I like this in pure CSS with fa-buttons:

_x000D_
_x000D_
.divs {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
    background-color: #fcc;_x000D_
}_x000D_
_x000D_
.inputs {_x000D_
    position:absolute;_x000D_
    left: 0px;_x000D_
    height: 100%;_x000D_
    width: 100%;_x000D_
    opacity: 0;_x000D_
    background: #00f;_x000D_
    z-index:999;_x000D_
}_x000D_
_x000D_
.icons {_x000D_
    position:relative;_x000D_
}
_x000D_
<div class="divs">_x000D_
<input type='file' id='image' class="inputs">_x000D_
<i class="fa fa-image fa-2x icons"></i>_x000D_
</div>_x000D_
_x000D_
<div class="divs">_x000D_
<input type='file' id='book' class="inputs">_x000D_
<i class="fa fa-book fa-5x icons"></i>_x000D_
</div>_x000D_
<br><br><br>_x000D_
<div class="divs">_x000D_
<input type='file' id='data' class="inputs">_x000D_
<i class="fa fa-id-card fa-3x icons"></i>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
_x000D_
_x000D_
_x000D_

Fiddle: https://jsfiddle.net/zoutepopcorn/v2zkbpay/1/

Fatal error: Call to undefined function mb_strlen()

For me the following command did the trick

sudo apt install php-mbstring

How to have Java method return generic list of any type?

You can simply cast to List and then check if every element can be casted to T.

public <T> List<T> asList(final Class<T> clazz) {
    List<T> values = (List<T>) this.value;
    values.forEach(clazz::cast);
    return values;
}

Pie chart with jQuery

Flot

Limitations: lines, points, filled areas, bars, pie and combinations of these

From an interaction perspective, Flot by far will get you as close as possible to Flash graphing as you can get with jQuery. Whilst the graph output is pretty slick, and great looking, you can also interact with data points. What I mean by this is you can have the ability to hover over a data point and get visual feedback on the value of that point in the graph.

The trunk version of flot supports pie charts.

Flot Zoom capability.

On top of this, you also have the ability to select a chunk of the graph to get data back for a particular “zone”. As a secondary feature to this “zoning”, you can also select an area on a graph and zoom in to see the data points a little more closely. Very cool.


Sparklines

Limitations: Pie, Line, Bar, Combination

Sparklines is my favourite mini graphing tool out there. Really great for dashboard style graphs (think Google Analytics dashboard next time you login). Because they’re so tiny, they can be included in line (as in the example above). Another nice idea which can be used in all graphing plugins is the self-refresh capabilities. Their Mouse-Speed demo shows you the power of live charting at its best.


Query Chart 0.21

Limitations: Area, Line, Bar and combinations of these

jQuery Chart 0.21 isn’t the nicest looking charting plugin out there it has to be said. It’s pretty basic in functionality when it comes to the charts it can handle, however it can be flexible if you can put in some time and effort into it.

Adding values into a chart is relatively simple:

.chartAdd({

    "label"  : "Leads",
    "type"   : "Line",
    "color"  : "#008800",
    "values" : ["100","124","222","44","123","23","99"]
});

jQchart

Limitations: Bar, Line

jQchart is an odd one, they’ve built in animation transistions and drag/drop functionality into the chart, however it’s a little clunky – and seemingly pointless. It does generate nice looking charts if you get the CSS setup right, but there are better out there.


TufteGraph

Limitations: Bar and Stacked Bar

Tuftegraph sells itself as “pretty bar graphs that you would show your mother”. It comes close, Flot is prettier, but Tufte does lend itself to be very lightweight. Although with that comes restrictions – there are few options to choose from, so you get what you’re given. Check it out for a quick win bar chart.

Location of WSDL.exe

In case anyone using VS 2008 (.NET 3.5) is also looking for the wsdl.exe. I found it here:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\wsdl.exe

How to Generate Unique ID in Java (Integer)?

Just generate ID and check whether it is already present or not in your list of generated IDs.

How to add a vertical Separator?

From http://social.msdn.microsoft.com/Forums/vstudio/en-US/12ead5d4-1d57-4dbb-ba81-bc13084ba370/how-can-i-add-a-line-as-a-visual-separator-to-the-content-control-like-grid?forum=wpf:

Try this example and see if it fits your needs, there are three main aspects to it.

  1. Line.Stretch is set to fill.

  2. For horizontal lines the VerticalAlignment of the line is set Bottom, and for VerticalLines the HorizontalAlignment is set to Right.

  3. We then need to tell the line how many rows or columns to span, this is done by binding to either RowDefinitions or ColumnDefintions count property.



        <Style x:Key="horizontalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">  
            <Setter Property="X2" Value="1" /> 
            <Setter Property="VerticalAlignment" Value="Bottom" /> 
            <Setter Property="Grid.ColumnSpan" 
                    Value="{Binding   
                                Path=ColumnDefinitions.Count,  
                                RelativeSource={RelativeSource AncestorType=Grid}}"/> 
        </Style> 
    
        <Style x:Key="verticalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">  
            <Setter Property="Y2" Value="1" /> 
            <Setter Property="HorizontalAlignment" Value="Right" /> 
            <Setter Property="Grid.RowSpan"   
                    Value="{Binding   
                                Path=RowDefinitions.Count,  
                                RelativeSource={RelativeSource AncestorType=Grid}}"/> 
        </Style> 
    </Grid.Resources>        
    
    <Grid.RowDefinitions> 
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
    </Grid.RowDefinitions> 
    
    <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
    </Grid.ColumnDefinitions> 
    
    <Line Grid.Column="0" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="1" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="2" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="3" Style="{StaticResource verticalLineStyle}"/>  
    
    <Line Grid.Row="0" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="1" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="2" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="3" Style="{StaticResource horizontalLineStyle}"/>  
    

Count number of occurrences for each unique value

You should change the query to:

SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col

This vl works correctly.

Combine Multiple child rows into one row MYSQL

If you really need multiple columns in your result, and the amount of options is limited, you can even do this:

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  if(ordered_options.id=1,Ordered_Options.Value,null) as `Option1`,
  if(ordered_options.id=2,Ordered_Options.Value,null) as `Option2`,
  if(ordered_options.id=43,Ordered_Options.Value,null) as `Option43`,
  if(ordered_options.id=44,Ordered_Options.Value,null) as `Option44`,
  GROUP_CONCAT(if(ordered_options.id not in (1,2,43,44),Ordered_Options.Value,null)) as `OtherOptions`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Action Filters, jquery stringify, bleh...

Peter, this functionality is native to MVC. That's one of things that makes MVC so great.

$.post('SomeController/Batch', { 'ids': ['1', '2', '3']}, function (r) {
   ...
});

And in the action,

[HttpPost]
public ActionResult Batch(string[] ids)
{
}

Works like a charm:

enter image description here

If you're using jQuery 1.4+, then you want to look into setting traditional mode:

jQuery.ajaxSettings.traditional = true;

As described here: http://www.dovetailsoftware.com/blogs/kmiller/archive/2010/02/24/jquery-1-4-breaks-asp-net-mvc-actions-with-array-parameters

This even works for complex objects. If you're interested, you should look into the MVC documentation about Model Binding: http://msdn.microsoft.com/en-us/library/dd410405.aspx

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

ListView with OnItemClickListener

listPaired = (ListView) findViewById( R.id.listView1 );
listPairedData = new ArrayList < String >();
araPaired = new ArrayAdapter( this, android.R.layout.simple_list_item_1, listPairedData );
listPaired.setAdapter( araPaired );
listPaired.setOnItemClickListener( listPairedClickItem );

private OnItemClickListener listPairedClickItem = new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > arg0, View arg1, int arg2, long arg3) {

        String info = ( (TextView) arg1 ).getText().toString();
        Toast.makeText( getBaseContext(), "Item " + info, Toast.LENGTH_LONG ).show();
    }
};

how to add button click event in android studio

SetOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)

This means in other words (due to your current scenario) that your MainActivity need to implement OnClickListener:

public class Main extends ActionBarActivity implements View.OnClickListener {
   // do your stuff
}

This:

buttonname.setOnClickListener(this);

means that you want to assign listener for your Button "on this instance" -> this instance represents OnClickListener and for this reason your class have to implement that interface.

It's similar with anonymous listener class (that you can also use):

buttonname.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

   }
});

String formatting: % vs. .format vs. string literal

I would add that since version 3.6, we can use fstrings like the following

foo = "john"
bar = "smith"
print(f"My name is {foo} {bar}")

Which give

My name is john smith

Everything is converted to strings

mylist = ["foo", "bar"]
print(f"mylist = {mylist}")

Result:

mylist = ['foo', 'bar']

you can pass function, like in others formats method

print(f'Hello, here is the date : {time.strftime("%d/%m/%Y")}')

Giving for example

Hello, here is the date : 16/04/2018

Apk location in New Android Studio

Click on Build-Build Bundles/Apks-Build Apk.

A notification will which shows app location when you click on 'locate' on the notification.

If you have already done creating apk, goto : C:\Users\\AndroidStudioProjects\\app\build\outputs\apk\debug

How to use GROUP BY to concatenate strings in SQL Server?

This kind of question is asked here very often, and the solution is going to depend a lot on the underlying requirements:

https://stackoverflow.com/search?q=sql+pivot

and

https://stackoverflow.com/search?q=sql+concatenate

Typically, there is no SQL-only way to do this without either dynamic sql, a user-defined function, or a cursor.

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources" For example:

_x000D_
_x000D_
<GlobalNamingResources>_x000D_
    <!-- Editable user database that can also be used by_x000D_
         UserDatabaseRealm to authenticate users_x000D_
    -->_x000D_
  <!-- Other previus resouces -->_x000D_
    <Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
    maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
    type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
  </GlobalNamingResources>
_x000D_
_x000D_
_x000D_ In your web application you need a link to that resource (ResourceLink):

project explore

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
   <ResourceLink name="jdbc/your_jndi"_x000D_
      global="jdbc/your_jndi"_x000D_
      auth="Container"_x000D_
      type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
_x000D_
_x000D_

So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml

persistence.xml location

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
 version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
 <persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
  <provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
  <properties>_x000D_
   <property name="javax.persistence.jdbc.driver"   value="org.postgresql.Driver" />_x000D_
   <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
   _x000D_
   <!--  <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
   <property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
   <property name="hibernate.show_sql" value="false" />_x000D_
   <property name="hibernate.format_sql" value="true"/>     _x000D_
  </properties>_x000D_
 </persistence-unit>_x000D_
</persistence>
_x000D_
_x000D_
_x000D_

So in your spring.xml you can do that:

_x000D_
_x000D_
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
   <property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
  </bean>_x000D_
     _x000D_
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
              <property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
              <property name="dataSource" ref="postGresDataSource" />_x000D_
              <property name="jpaVendorAdapter"> _x000D_
                 <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
              </property>_x000D_
        </bean>
_x000D_
_x000D_
_x000D_ Look above that entityManagerFactory bean refers to your UNIT_NAME configured at persistence xml and the bean postGresDataSource has a property that points to your JNDI resource in Tomcat.

_x000D_
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
_x000D_
_x000D_

In this example I used spring with xml but you can do this programmaticaly if you prefer.

That's it, I hope helped.

Defining Z order of views of RelativeLayout in Android

Check if you have any elevation on one of the Views in XML. If so, add elevation to the other item or remove the elevation to solve the issue. From there, it's the order of the views that dictates what comes above the other.

How to pass arguments to entrypoint in docker-compose.yml

I was facing the same issue with jenkins ssh slave 'jenkinsci/ssh-slave'. However, my case was a bit complicated because it was necessary to pass an argument which contained spaces. I've managed to do it like below (entrypoint in dockerfile is in exec form):

command: ["some argument with space which should be treated as one"]

How can I implement rate limiting with Apache? (requests per second)

As stated in this blog post it seems possible to use mod_security to implement a rate limit per second.

The configuration is something like this:

SecRuleEngine On

<LocationMatch "^/somepath">
  SecAction initcol:ip=%{REMOTE_ADDR},pass,nolog
  SecAction "phase:5,deprecatevar:ip.somepathcounter=1/1,pass,nolog"
  SecRule IP:SOMEPATHCOUNTER "@gt 60" "phase:2,pause:300,deny,status:509,setenv:RATELIMITED,skip:1,nolog"
  SecAction "phase:2,pass,setvar:ip.somepathcounter=+1,nolog"
  Header always set Retry-After "10" env=RATELIMITED
</LocationMatch>

ErrorDocument 509 "Rate Limit Exceeded"

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

It usually because in connection manager it may be still of 50 char , hence I have resolved the problem by going to Connection Manager--> Advanced and then change to 100 or may be 1000 if its big enough

How can I divide two integers stored in variables in Python?

The 1./2 syntax works because 1. is a float. It's the same as 1.0. The dot isn't a special operator that makes something a float. So, you need to either turn one (or both) of the operands into floats some other way -- for example by using float() on them, or by changing however they were calculated to use floats -- or turn on "true division", by using from __future__ import division at the top of the module.

Defining lists as global variables in Python

No, you can specify the list as a keyword argument to your function.

alist = []
def fn(alist=alist):
    alist.append(1)
fn()
print alist    # [1]

I'd say it's bad practice though. Kind of too hackish. If you really need to use a globally available singleton-like data structure, I'd use the module level variable approach, i.e. put 'alist' in a module and then in your other modules import that variable:

In file foomodule.py:

alist = []

In file barmodule.py:

import foomodule
def fn():
    foomodule.alist.append(1)
print foomodule.alist    # [1]

Is there a way to detect if an image is blurry?

Another very simple way to estimate the sharpness of an image is to use a Laplace (or LoG) filter and simply pick the maximum value. Using a robust measure like a 99.9% quantile is probably better if you expect noise (i.e. picking the Nth-highest contrast instead of the highest contrast.) If you expect varying image brightness, you should also include a preprocessing step to normalize image brightness/contrast (e.g. histogram equalization).

I've implemented Simon's suggestion and this one in Mathematica, and tried it on a few test images:

test images

The first test blurs the test images using a Gaussian filter with a varying kernel size, then calculates the FFT of the blurred image and takes the average of the 90% highest frequencies:

testFft[img_] := Table[
  (
   blurred = GaussianFilter[img, r];
   fft = Fourier[ImageData[blurred]];
   {w, h} = Dimensions[fft];
   windowSize = Round[w/2.1];
   Mean[Flatten[(Abs[
       fft[[w/2 - windowSize ;; w/2 + windowSize, 
         h/2 - windowSize ;; h/2 + windowSize]]])]]
   ), {r, 0, 10, 0.5}]

Result in a logarithmic plot:

fft result

The 5 lines represent the 5 test images, the X axis represents the Gaussian filter radius. The graphs are decreasing, so the FFT is a good measure for sharpness.

This is the code for the "highest LoG" blurriness estimator: It simply applies an LoG filter and returns the brightest pixel in the filter result:

testLaplacian[img_] := Table[
  (
   blurred = GaussianFilter[img, r];
   Max[Flatten[ImageData[LaplacianGaussianFilter[blurred, 1]]]];
   ), {r, 0, 10, 0.5}]

Result in a logarithmic plot:

laplace result

The spread for the un-blurred images is a little better here (2.5 vs 3.3), mainly because this method only uses the strongest contrast in the image, while the FFT is essentially a mean over the whole image. The functions are also decreasing faster, so it might be easier to set a "blurry" threshold.

Detecting user leaving page with react-router

react-router v4 introduces a new way to block navigation using Prompt. Just add this to the component that you would like to block:

import { Prompt } from 'react-router'

const MyComponent = () => (
  <React.Fragment>
    <Prompt
      when={shouldBlockNavigation}
      message='You have unsaved changes, are you sure you want to leave?'
    />
    {/* Component JSX */}
  </React.Fragment>
)

This will block any routing, but not page refresh or closing. To block that, you'll need to add this (updating as needed with the appropriate React lifecycle):

componentDidUpdate = () => {
  if (shouldBlockNavigation) {
    window.onbeforeunload = () => true
  } else {
    window.onbeforeunload = undefined
  }
}

onbeforeunload has various support by browsers.

How to rename a pane in tmux?

Also when scripting, you can specify a name when creating the window with -n <window name>. For example:

# variable to store the session name
SESSION="my_session"

# set up session
tmux -2 new-session -d -s $SESSION

# create window; split into panes
tmux new-window -t $SESSION:0 -n 'My Window with a Name'

Read and write into a file using VBScript

Don't think so...you can only use openTextFile for reading (1), writing (2), or appending (8). Reference here.

If you were using VB6 instead of VBScript, you could do:

Open "Filename" [For Mode] [AccessRestriction] [LockType] As #FileNumber

Using the Random mode. For example:

Open "C:\New\maddy.txt" For Random As #1

private final static attribute vs private final attribute

The static one is the same member on all of the class instances and the class itself.
The non-static is one for every instance (object), so in your exact case it's a waste of memory if you don't put static.

Run "mvn clean install" in Eclipse

Right click on pom.xml, Run As, you should see the list of m2 options if you have Maven installed, you can select Maven Clean from there

Docker-compose: node_modules not present in a volume after npm install succeeds

Installing node_modules in container to different from project folder, and setting NODE_PATH to your node_modules folder helps me (u need to rebuild container).

I'm using docker-compose. My project file structure:

-/myproject
--docker-compose.yml
--nodejs/
----Dockerfile

docker-compose.yml:

version: '2'
services:
  nodejs:
    image: myproject/nodejs
    build: ./nodejs/.
    volumes:
      - ./nodejs:/workdir
    ports:
      - "23005:3000"
    command: npm run server

Dockerfile in nodejs folder:

FROM node:argon
RUN mkdir /workdir
COPY ./package.json /workdir/.
RUN mkdir /data
RUN ln -s /workdir/package.json /data/.
WORKDIR /data
RUN npm install
ENV NODE_PATH /data/node_modules/
WORKDIR /workdir

Can I use a min-height for table, tr or td?

In CSS 2.1, the effect of 'min-height' and 'max-height' on tables, inline tables, table cells, table rows, and row groups is undefined.

So try wrapping the content in a div, and give the div a min-height jsFiddle here

<table cellspacing="0" cellpadding="0" border="0" style="width:300px">
    <tbody>
        <tr>
            <td>
                <div style="min-height: 100px; background-color: #ccc">
                    Hello World !
                </div>
            </td>
            <td>
                <div style="min-height: 100px; background-color: #f00">
                    Good Morning !
                </div>
            </td>
        </tr>
    </tbody>
</table>

Jquery UI tooltip does not support html content

add html = true to the tooltip options

$({selector}).tooltip({html: true});

Update
it's not relevant for jQuery ui tooltip property - it's true in bootstrap ui tooltip - my bad!

iReport not starting using JRE 8

It works only with JRE 1.7 just download it and extract to your prefered location

and use the following command to open the iReport

ireport --jdkhome Path To JDK Home

Get the date (a day before current time) in Bash

Advanced Bash-scripting Guide

date +%Y:%m:%d -d "yesterday"

For details about the date format see the man page for date

date --date='-1 day'

What are the "spec.ts" files generated by Angular CLI for?

The spec files are unit tests for your source files. The convention for Angular applications is to have a .spec.ts file for each .ts file. They are run using the Jasmine javascript test framework through the Karma test runner (https://karma-runner.github.io/) when you use the ng test command.

You can use this for some further reading:

https://angular.io/guide/testing

How can I center text (horizontally and vertically) inside a div block?

<div class="small-container">
    <span>Text centered</span>
</div>

<style>
.small-container {
    width:250px;
    height:250px;
    border:1px green solid;
    text-align:center;
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
.small-container span{
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
</style>

Best way to add Gradle support to IntelliJ Project

Add:

build.gradle 

in your root project folder, and use plugin for example:

apply plugin: 'idea'
//and standard one
apply plugin: 'java'

and with this fire from command line:

gradle cleanIdea 

and after that:

gradle idea

After that everything should work

What are some ways of accessing Microsoft SQL Server from Linux?

pymssql is a DB-API Python module, based on FreeTDS. It worked for me. Create some helper functions, if you need, and use it from Python shell.

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

https://tools.ietf.org/html/rfc7230#section-5.4

IndentationError: unexpected unindent WHY?

@MaxPython The answer above is missing ":"

try:
   #do something
except:
  # print 'error/exception'

def printError(e): print e

Calling a method every x minutes

Example of using a Timer:

using System;
using System.Timers;

static void Main(string[] args)
{
    Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    t.Start();
}

// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("..."); 
}

Properties file with a list as the value for an individual key

Create a wrapper around properties and assume your A value has keys A.1, A.2, etc. Then when asked for A your wrapper will read all the A.* items and build the list. HTH

How do I get the path of the Python script I am running in?

The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:

os.path.dirname(sys.argv[0])

Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

MSDN Article: "The Dictionary<TKey, TValue> class has the same functionality as the Hashtable class. A Dictionary<TKey, TValue> of a specific type (other than Object) has better performance than a Hashtable for value types because the elements of Hashtable are of type Object and, therefore, boxing and unboxing typically occur if storing or retrieving a value type".

Link: http://msdn.microsoft.com/en-us/library/4yh14awz(v=vs.90).aspx

JavaScript calculate the day of the year (1 - 366)

I would like to provide a solution that does calculations adding the days for each previous month:

_x000D_
_x000D_
function getDayOfYear(date) {_x000D_
    var month = date.getMonth();_x000D_
    var year = date.getFullYear();_x000D_
    var days = date.getDate();_x000D_
    for (var i = 0; i < month; i++) {_x000D_
        days += new Date(year, i+1, 0).getDate();_x000D_
    }_x000D_
    return days;_x000D_
}_x000D_
var input = new Date(2017, 7, 5);_x000D_
console.log(input);_x000D_
console.log(getDayOfYear(input));
_x000D_
_x000D_
_x000D_

This way you don't have to manage the details of leap years and daylight saving.

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

Update for angularJS 4:

Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3000/node_modules/@angular/platform-browser/bundles/platform-browser.umd.js/animations

Solution:

**cli:** (command/terminal)
npm install @angular/animations@latest --save

**systemjs.config.js** (edit file)
'@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',

**app.module.ts** (edit file)
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@NgModule({
  imports:      [ BrowserModule,BrowserAnimationsModule ],
...

ImportError: No module named pandas

It might be too late to answer this but I just had the problem and I kept installing and uninstalling, it turns out the the problem happens when you're installing pandas to a version of python and trying to run the program using another python version

So to start off, run:

which python
python --version
which pip

make sure both are aligned, most probably, python is 2.7 and pip is working on 3.x or pip is coming from anaconda's python version which is highly likely to be 3.x as well

Incase of python redirects to 2.7, and pip redirects to pip3, install pandas using pip install pandas and use python3 file_name.py to run the program.

Passing 'this' to an onclick event

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

New og:image size for Facebook share?

The aspect ratio for a Facebook post image is 41:20.

To find the appropriate widths and height for your photo, you can use the Aspect Ratio Calculator.

Here you can select different ratios under “Common ratios:” which includes the option “1200 x 630 (Facebook)". So if the width of your photo is 1800, plug that number into the “W2” slot and it will tell you what the respective height should be.

node.js require all files in a folder?

Expanding on this glob solution. Do this if you want to import all modules from a directory into index.js and then import that index.js in another part of the application. Note that template literals aren't supported by the highlighting engine used by stackoverflow so the code might look strange here.

const glob = require("glob");

let allOfThem = {};
glob.sync(`${__dirname}/*.js`).forEach((file) => {
  /* see note about this in example below */
  allOfThem = { ...allOfThem, ...require(file) };
});
module.exports = allOfThem;

Full Example

Directory structure

globExample/example.js
globExample/foobars/index.js
globExample/foobars/unexpected.js
globExample/foobars/barit.js
globExample/foobars/fooit.js

globExample/example.js

const { foo, bar, keepit } = require('./foobars/index');
const longStyle = require('./foobars/index');

console.log(foo()); // foo ran
console.log(bar()); // bar ran
console.log(keepit()); // keepit ran unexpected

console.log(longStyle.foo()); // foo ran
console.log(longStyle.bar()); // bar ran
console.log(longStyle.keepit()); // keepit ran unexpected

globExample/foobars/index.js

const glob = require("glob");
/*
Note the following style also works with multiple exports per file (barit.js example)
but will overwrite if you have 2 exports with the same
name (unexpected.js and barit.js have a keepit function) in the files being imported. As a result, this method is best used when
your exporting one module per file and use the filename to easily identify what is in it.

Also Note: This ignores itself (index.js) by default to prevent infinite loop.
*/

let allOfThem = {};
glob.sync(`${__dirname}/*.js`).forEach((file) => {
  allOfThem = { ...allOfThem, ...require(file) };
});

module.exports = allOfThem;

globExample/foobars/unexpected.js

exports.keepit = () => 'keepit ran unexpected';

globExample/foobars/barit.js

exports.bar = () => 'bar run';

exports.keepit = () => 'keepit ran';

globExample/foobars/fooit.js

exports.foo = () => 'foo ran';

From inside project with glob installed, run node example.js

$ node example.js
foo ran
bar run
keepit ran unexpected
foo ran
bar run
keepit ran unexpected

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

For Java Web Start Execution we can use Andy Guibert's suggestion like this:

<j2se version="1.6+" 
      java-vm-args="-XX:+IgnoreUnrecognizedVMOptions --add-modules=java.se.ee"/>

Note the extra "=" in the --add-modules. See this OpenJDK Ticket or the last note in "Understanding Runtime Access Warnings" of the Java Platform, Standard Edition Oracle JDK 9 Migration Guide.

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

Commands out of sync; you can't run this command now

I ran into this error using Doctrine DBAL QueryBuilder.

I created a query with QueryBuilder that uses column subselects, also created with QueryBuilder. The subselects were only created via $queryBuilder->getSQL() and not executed. The error happened on creating the second subselect. By provisionally executing each subselect with $queryBuilder->execute() before using $queryBuilder->getSQL(), everything worked. It is as if the connection $queryBuilder->connection remains in an invalid state for creating a new SQL before executing the currently prepared SQL, despite the new QueryBuilder instance on each subselect.

My solution was to write the subselects without QueryBuilder.

How do I execute a Shell built-in command with a C function?

You should execute sh -c echo $PWD; generally sh -c will execute shell commands.

(In fact, system(foo) is defined as execl("sh", "sh", "-c", foo, NULL) and thus works for shell built-ins.)

If you just want the value of PWD, use getenv, though.

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

Reading all files in a directory, store them in objects, and send the object

For the code to work smoothy in different enviroments, path.resolve can be used in places where path is manipulated. Here is code which works better.

Reading part:

var fs = require('fs');

function readFiles(dirname, onFileContent, onError) {
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
      onError(err);
      return;
    }
    filenames.forEach(function(filename) {
      fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
        if (err) {
          onError(err);
          return;
        }
        onFileContent(filename, content);
      });
    });
  });
}

Storing part:

var data = {};
readFiles(path.resolve(__dirname, 'dirname/'), function(filename, content) {
  data[filename] = content;
}, function(error) {
  throw err;
});

Cordova app not displaying correctly on iPhone X (Simulator)

Just a note that the constant keyword use for safe-area margins has been updated to env for 11.2 beta+

https://webkit.org/blog/7929/designing-websites-for-iphone-x/

gcc warning" 'will be initialized after'

Make sure the members appear in the initializer list in the same order as they appear in the class

Class C {
   int a;
   int b;
   C():b(1),a(2){} //warning, should be C():a(2),b(1)
}

or you can turn -Wno-reorder