Programs & Examples On #Multiboot

GNU Multiboot is a specification of the interactions between bootloaders and kernels. It is designed to ease the writing of kernels and to create a richer interface for a just booted kernel than the raw BIOS interfaces.

List tables in a PostgreSQL schema

In all schemas:

=> \dt *.*

In a particular schema:

=> \dt public.*

It is possible to use regular expressions with some restrictions

\dt (public|s).(s|t)
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | s    | table | cpn
 public | t    | table | cpn
 s      | t    | table | cpn

Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for . which is taken as a separator as mentioned above, * which is translated to the regular-expression notation .*, ? which is translated to ., and $ which is matched literally. You can emulate these pattern characters at need by writing ? for ., (R+|) for R*, or (R|) for R?. $ is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words, $ is automatically appended to your pattern). Write * at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of \do).

Javascript/jQuery detect if input is focused

Did you try:

$(this).is(':focus');

Take a look at Using jQuery to test if an input has focus it features some more examples

Foreign key referring to primary keys across multiple tables?

You can probably add two foreign key constraints (honestly: I've never tried it), but it'd then insist the parent row exist in both tables.

Instead you probably want to create a supertype for your two employee subtypes, and then point the foreign key there instead. (Assuming you have a good reason to split the two types of employees, of course).

                 employee       
employees_ce     ————————       employees_sn
————————————     type           ————————————
empid —————————> empid <——————— empid
name               /|\          name
                    |  
                    |  
      deductions    |  
      ——————————    |  
      empid ————————+  
      name

type in the employee table would be ce or sn.

How do you comment an MS-access Query?

If you have a query with a lot of criteria, it can be tricky to remember what each one does. I add a text field into the original table - call it "comments" or "documentation". Then I include it in the query with a comment for each criteria.

Comments need to be written like like this so that all relevant rows are returned. Unfortunately, as I'm a new poster, I can't add a screenshot!

So here goes without

Field:   | Comment              |ContractStatus     | ProblemDealtWith | ...... |

Table:   | ElecContracts        |ElecContracts      | ElecContracts    | ...... |

Sort:  

Show:  

Criteria | <> "all problems are | "objection" Or |

         | picked up with this  | "rejected" Or  |

         | criteria" OR Is Null | "rolled"       |

         | OR ""

<> tells the query to choose rows that are not equal to the text you entered, otherwise it will only pick up fields that have text equal to your comment i.e. none!

" " enclose your comment in quotes

OR Is Null OR "" tells your query to include any rows that have no data in the comments field , otherwise it won't return anything!

How can I make a link from a <td> table cell

Yes, that's possible, albeit not literally the <td>, but what's in it. The simple trick is, to make sure that the content extends to the borders of the cell (it won't include the borders itself though).

As already explained, this isn't semantically correct. An a element is an inline element and should not be used as block-level element. However, here's an example (but JavaScript plus a td:hover CSS style will be much neater) that works in most browsers:

<td>
  <a href="http://example.com">
    <div style="height:100%;width:100%">
      hello world
    </div>
  </a>
</td>

PS: it's actually neater to change a in a block-level element using CSS as explained in another solution in this thread. it won't work well in IE6 though, but that's no news ;)

Alternative (non-advised) solution

If your world is only Internet Explorer (rare, nowadays), you can violate the HTML standard and write this, it will work as expected, but will be highly frowned upon and be considered ill-advised (you haven't heard this from me). Any other browser than IE will not render the link, but will show the table correctly.

<table>
    <tr>
        <a href="http://example.com"><td  width="200">hello world</td></a>
    </tr>
</table>

JavaFX Location is not set error message

I converted a simple NetBeans 8 Java FXML application to the Maven-driven one. Then I got problems, because the getResource() methods weren't able to find the .fxml files. In mine original application the fxmls were scattered through the package tree - each beside its controller class file. After I made Clean and build in NetBeans, I checked the result .jar in the target folder - the .jar didn't contain any fxml at all. All the fxmls were strangely disappeared.

Then I put all fxmls into the resources/fxml folder and set the getResource method parameters accordingly, for example: FXMLLoader(App.class.getClassLoader().getResource("fxml/ObjOverview.fxml")); In this case everything went OK. The fxml folder appeared int the .jar's root and it contained all my fxmls. The program was working as expected.

How do you read from stdin?

There's a few ways to do it.

  • sys.stdin is a file-like object on which you can call functions read or readlines if you want to read everything or you want to read everything and split it by newline automatically. (You need to import sys for this to work.)

  • If you want to prompt the user for input, you can use raw_input in Python 2.X, and just input in Python 3.

  • If you actually just want to read command-line options, you can access them via the sys.argv list.

You will probably find this Wikibook article on I/O in Python to be a useful reference as well.

how to set "camera position" for 3d plots using python/matplotlib?

Minimal example varying azim, dist and elev

To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245

Here is my test program:

#!/usr/bin/env python3

import sys

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

if len(sys.argv) > 1:
    azim = int(sys.argv[1])
else:
    azim = None
if len(sys.argv) > 2:
    dist = int(sys.argv[2])
else:
    dist = None
if len(sys.argv) > 3:
    elev = int(sys.argv[3])
else:
    elev = None

# Make data.
X = np.arange(-5, 6, 1)
Y = np.arange(-5, 6, 1)
X, Y = np.meshgrid(X, Y)
Z = X**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

# Labels.
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

if azim is not None:
    ax.azim = azim
if dist is not None:
    ax.dist = dist
if elev is not None:
    ax.elev = elev

print('ax.azim = {}'.format(ax.azim))
print('ax.dist = {}'.format(ax.dist))
print('ax.elev = {}'.format(ax.elev))

plt.savefig(
    'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
    format='png',
    bbox_inches='tight'
)

Running it without arguments gives the default values:

ax.azim = -60
ax.dist = 10
ax.elev = 30

main_-60_10_30.png

enter image description here

Vary azim

The azimuth is the rotation around the z axis e.g.:

  • 0 means "looking from +x"
  • 90 means "looking from +y"

main_-60_10_30.png

enter image description here

main_0_10_30.png

enter image description here

main_60_10_30.png

enter image description here

Vary dist

dist seems to be the distance from the center visible point in data coordinates.

main_-60_10_30.png

enter image description here

main_-60_5_30.png

enter image description here

main_-60_20_-30.png

enter image description here

Vary elev

From this we understand that elev is the angle between the eye and the xy plane.

main_-60_10_60.png

enter image description here

main_-60_10_30.png

enter image description here

main_-60_10_0.png

enter image description here

main_-60_10_-30.png

enter image description here

Tested on matpotlib==3.2.2.

creating batch script to unzip a file without additional zip tools

Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

To unzip file you can use this script :

zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no

How to compare types

If your instance is a Type:

Type typeFiled;
if (typeField == typeof(string))
{ 
    ... 
}

but if your instance is an object and not a Type use the as operator:

object value;
string text = value as string;
if (text != null)
{
    // value is a string and you can do your work here
}

this has the advantage to convert value only once into the specified type.

Angular ng-if="" with multiple arguments

For people looking to do if statements with multiple 'or' values.

<div ng-if="::(a || b || c || d || e || f)"><div>

How do I run Selenium in Xvfb?

If you use Maven, you can use xvfb-maven-plugin to start xvfb before tests, run them using related DISPLAY environment variable, and stop xvfb after all.

How do I get the domain originating the request in express.js?

Instead of:

var host = req.get('host');
var origin = req.get('origin');

you can also use:

var host = req.headers.host;
var origin = req.headers.origin;

PHP upload image

This code is very easy to upload file by php. In this code I am performing uploading task in same page that mean our html and php both code resides in the same file. This code generates new name of image name.

first of all see the html code

<form action="index.php" method="post" enctype="multipart/form-data">
 <input type="file" name="banner_image" >
 <input type="submit" value="submit">
 </form>

now see the php code

<?php
$image_name=$_FILES['banner_image']['name'];
       $temp = explode(".", $image_name);
        $newfilename = round(microtime(true)) . '.' . end($temp);
       $imagepath="uploads/".$newfilename;
       move_uploaded_file($_FILES["banner_image"]["tmp_name"],$imagepath);
?>

How to output in CLI during execution of PHP Unit tests?

You should really think about your intentions: If you need the information now when debugging to fix the test, you will need it next week again when the tests break.

This means that you will need the information always when the test fails - and adding a var_dump to find the cause is just too much work. Rather put the data into your assertions.

If your code is too complex for that, split it up until you reach a level where one assertion (with a custom message) tells you enough to know where it broke, why and how to fix the code.

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

(Built-in) way in JavaScript to check if a string is a valid number

This is built on some of the previous answers and comments. The following covers all the edge cases and fairly concise as well:

const isNumRegEx = /^-?(\d*\.)?\d+$/;

function isNumeric(n, allowScientificNotation = false) {
    return allowScientificNotation ? 
                !Number.isNaN(parseFloat(n)) && Number.isFinite(n) :
                isNumRegEx.test(n);
}

Prevent textbox autofill with previously entered values

For firefox

Either:

<asp:TextBox id="Textbox1" runat="server" autocomplete="off"></asp:TextBox>

Or from the CodeBehind:

Textbox1.Attributes.Add("autocomplete", "off");

RESTful web service - how to authenticate requests from other services?

5. Something else - there must be other solutions out there?

You're right, there is! And it is called JWT (JSON Web Tokens).

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

I highly recommend looking into JWTs. They're a much simpler solution to the problem when compared against alternative solutions.

https://jwt.io/introduction/

How can I get dictionary key as variable directly in Python (not by searching from value)?

The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this

Based on the above requirement this is what I would suggest:

keys = mydictionary.keys()
keys.sort()

for each in keys:
    print "%s: %s" % (each, mydictionary.get(each))

How to resolve TypeError: can only concatenate str (not "int") to str

Problem is you are doing the following

str(chr(char + 7429146))

where char is a string. You cannot add a int with a string. this will cause that error

maybe if you want to get the ascii code and add it with a constant number. if so , you can just do ord(char) and add it to a number. but again, chr can take values between 0 and 1114112

NULL values inside NOT IN clause

this is for Boy:

select party_code 
from abc as a
where party_code not in (select party_code 
                         from xyz 
                         where party_code = a.party_code);

this works regardless of ansi settings

How do I get which JRadioButton is selected from a ButtonGroup

import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;

public class RadioButton extends JRadioButton {

    public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
        public Object[] getSelectedObjects() {
            if ( isSelected() ) {
                return new Object[] { RadioButton.this };
            } else {
                return new Object[0];
            }
        }

        public RadioButton getButton() { return RadioButton.this; }
    }

    public RadioButton() { super(); setModel(new RadioButtonModel()); }
    public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }

    public static void main(String[] args) {
        RadioButton b1 = new RadioButton("A");
        RadioButton b2 = new RadioButton("B");
        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);
        b2.setSelected(true);
        RadioButtonModel model = (RadioButtonModel)group.getSelection();
        System.out.println(model.getButton().getText());
    }
}

IF... OR IF... in a windows batch file

It's possible to use a function, which evaluates the OR logic and returns a single value.

@echo off
set var1=3
set var2=5
call :logic_or orResult "'%var1%'=='4'" "'%var2%'=='5'"
if %orResult%==1 ( 
    echo At least one expression is true
) ELSE echo All expressions are false
exit /b

:logic_or <resultVar> expression1 [[expr2] ... expr-n] 
SETLOCAL
set "logic_or.result=0"
set "logic_or.resultVar=%~1"

:logic_or_loop 
if "%~2"=="" goto :logic_or_end 
if %~2 set "logic_or.result=1"
SHIFT 
goto :logic_or_loop 

:logic_or_end 
( 
  ENDLOCAL 
  set "%logic_or.resultVar%=%logic_or.result%"
  exit /b
) 

Apache Tomcat :java.net.ConnectException: Connection refused

Not sure if your issue was fixed and how. But I faced the same issue while trying to make a tomcat instance running.

  • The port was not in use.
  • There was no firewall issue.
  • Tomcat instance was starting up fine.

I changed the custom shutdown script and this issue was fixed. Old Script:-

export CATALINA_HOME=/home/lrsprod/ELA/tomcat6/apache-tomcat-6.0.35 $CATALINA_HOME/bin/catalina.sh stop

Added catalina base to it.

export CATALINA_BASE=/home/lrsprod/ELA/tomcat6/ela_instance export CATALINA_HOME=/home/lrsprod/ELA/tomcat6/apache-tomcat-6.0.35 $CATALINA_HOME/bin/catalina.sh stop

That did the trick.

How can I determine the status of a job?

You haven't specified how would you like to see these details.

For the first sight I would suggest to check Server Management Studio.

You can see the jobs and current statuses in the SQL Server Agent part, under Jobs. If you pick a job, the Property page shows a link to the Job History, where you can see the start and end time, if there any errors, which step caused the error, and so on.

You can specify alerts and notifications to email you or to page you when the job finished successfully or failed.

There is a Job Activity Monitor, but actually I never used it. You can have a try.

If you want to check it via T-SQL, then I don't know how you can do that.

Add Keypair to existing EC2 instance

This happened to me earlier (didn't have access to an EC2 instance someone else created but had access to AWS web console) and I blogged the answer: http://readystate4.com/2013/04/09/aws-gaining-ssh-access-to-an-ec2-instance-you-lost-access-to/

Basically, you can detached the EBS drive, attach it to an EC2 that you do have access to. Add your SSH pub key to ~ec2-user/.ssh/authorized_keys on this attached drive. Then put it back on the old EC2 instance. step-by-step in the link using Amazon AMI.

No need to make snapshots or create a new cloned instance.

MVC 4 @Scripts "does not exist"

One more for the pot - spent ages trying to work out the same problem - even though it was defined in the web.config for root and the root of Views. Turns out I'd mistakenly added it to the <system.web><pages><namespaces>, and not <system.web**.webPages.razor**><pages><namespaces> element.

Really easy to miss that!

How can I find the number of years between two dates?

I apparently can't comment yet, but I think you can just use the DAY_OF_YEAR to workout if you should adjust the years down one (copied and modified from current best answer)

public static int getDiffYears(Date first, Date last) {
    Calendar a = getCalendar(first);
    Calendar b = getCalendar(last);
    int diff = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
    if (a.get(Calendar.DAY_OF_YEAR) > b.get(Calendar.DAY_OF_YEAR)) {
        diff--;
    }
    return diff;
}

public static Calendar getCalendar(Date date) {
    Calendar cal = Calendar.getInstance(Locale.US);
    cal.setTime(date);
    return cal;
}

Similarly you could probably just diff the ms representations of the time and divide by the number of ms in a year. Just keep everything in longs and that should be good enough most of the time (leap years, ouch) but it depends on your application for the number of years and how performant that function has to be weather it would be worth that kind of hack.

Check if a Bash array contains a value

Here is a small contribution :

array=(word "two words" words)  
search_string="two"  
match=$(echo "${array[@]:0}" | grep -o $search_string)  
[[ ! -z $match ]] && echo "found !"  

Note: this way doesn't distinguish the case "two words" but this is not required in the question.

Extracting a parameter from a URL in WordPress

In the call back function, use the $request parameter

$parameters = $request->get_params();
echo $parameters['ppc'];

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

How to find common elements from multiple vectors?

There might be a cleverer way to go about this, but

intersect(intersect(a,b),c)

will do the job.

EDIT: More cleverly, and more conveniently if you have a lot of arguments:

Reduce(intersect, list(a,b,c))

New Array from Index Range Swift

One more variant using extension and argument name range

This extension uses Range and ClosedRange

extension Array {

    subscript (range r: Range<Int>) -> Array {
        return Array(self[r])
    }


    subscript (range r: ClosedRange<Int>) -> Array {
        return Array(self[r])
    }
}

Tests:

func testArraySubscriptRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1..<arr.count] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

func testArraySubscriptClosedRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1...arr.count - 1] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Documentation for crypto: http://nodejs.org/api/crypto.html

const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')

Static variables in JavaScript

There are other similar answers, but none of them quite appealed to me. Here's what I ended up with:

var nextCounter = (function () {
  var counter = 0;
  return function() {
    var temp = counter;
    counter += 1;
    return temp;
  };
})();

How can I restart a Java application?

Strictly speaking, a Java program cannot restart itself since to do so it must kill the JVM in which it is running and then start it again, but once the JVM is no longer running (killed) then no action can be taken.

You could do some tricks with custom classloaders to load, pack, and start the AWT components again but this will likely cause lots of headaches with regard to the GUI event loop.

Depending on how the application is launched, you could start the JVM in a wrapper script which contains a do/while loop, which continues while the JVM exits with a particular code, then the AWT app would have to call System.exit(RESTART_CODE). For example, in scripting pseudocode:

DO
  # Launch the awt program
  EXIT_CODE = # Get the exit code of the last process
WHILE (EXIT_CODE == RESTART_CODE)

The AWT app should exit the JVM with something other than the RESTART_CODE on "normal" termination which doesn't require restart.

How can I save an image with PIL?

The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as BMP.

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

import sys
import numpy
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')

im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))

visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())

result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')

Java 8 lambda Void argument

I don't think it is possible, because function definitions do not match in your example.

Your lambda expression is evaluated exactly as

void action() { }

whereas your declaration looks like

Void action(Void v) {
    //must return Void type.
}

as an example, if you have following interface

public interface VoidInterface {
    public Void action(Void v);
}

the only kind of function (while instantiating) that will be compatibile looks like

new VoidInterface() {
    public Void action(Void v) {
        //do something
        return v;
    }
}

and either lack of return statement or argument will give you a compiler error.

Therefore, if you declare a function which takes an argument and returns one, I think it is impossible to convert it to function which does neither of mentioned above.

How can I make an image transparent on Android?

Set transparency using setAlpha(float alpha). The below code works for me were I used an alpha value in float, 0 - 1.

  • 0: Full Transparent
  • 0.5 - 50%: Transparent
  • 1: Full Opaque

    ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView); imageView.setImageResource(mResources[position]); imageView.setAlpha(.80f);

Specifying content of an iframe instead of the src attribute to a page

iframe now supports srcdoc which can be used to specify the HTML content of the page to show in the inline frame.

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

Height equal to dynamic width (CSS fluid layout)

width: 80vmin; height: 80vmin;

CSS does 80% of the smallest view, height or width

http://caniuse.com/#feat=viewport-units

ASP.NET Core Web API exception handling

To Configure exception handling behavior per exception type you can use Middleware from NuGet packages:

Code sample:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddExceptionHandlingPolicies(options =>
    {
        options.For<InitializationException>().Rethrow();

        options.For<SomeTransientException>().Retry(ro => ro.MaxRetryCount = 2).NextPolicy();

        options.For<SomeBadRequestException>()
        .Response(e => 400)
            .Headers((h, e) => h["X-MyCustomHeader"] = e.Message)
            .WithBody((req,sw, exception) =>
                {
                    byte[] array = Encoding.UTF8.GetBytes(exception.ToString());
                    return sw.WriteAsync(array, 0, array.Length);
                })
        .NextPolicy();

        // Ensure that all exception types are handled by adding handler for generic exception at the end.
        options.For<Exception>()
        .Log(lo =>
            {
                lo.EventIdFactory = (c, e) => new EventId(123, "UnhandlerException");
                lo.Category = (context, exception) => "MyCategory";
            })
        .Response(null, ResponseAlreadyStartedBehaviour.GoToNextHandler)
            .ClearCacheHeaders()
            .WithObjectResult((r, e) => new { msg = e.Message, path = r.Path })
        .Handled();
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseExceptionHandlingPolicies();
    app.UseMvc();
}

Getting HTTP code in PHP using curl

curl_exec is necessary. Try CURLOPT_NOBODY to not download the body. That might be faster.

Where does Visual Studio look for C++ header files?

There seems to be a bug in Visual Studio 2015 community. For a 64-bit project, the include folder isn't found unless it's in the win32 bit configuration Additional Include Folders list.

Split String into an array of String

You need a regular expression like "\\s+", which means: split whenever at least one whitespace is encountered. The full Java code is:

try {
    String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
    // 
}

When to use self over $this?

$this-> is used to refer to a specific instance of a class's variables (member variables) or methods.

Example: 
$derek = new Person();

$derek is now a specific instance of Person. Every Person has a first_name and a last_name, but $derek has a specific first_name and last_name (Derek Martin). Inside the $derek instance, we can refer to those as $this->first_name and $this->last_name

ClassName:: is used to refer to that type of class, and its static variables, static methods. If it helps, you can mentally replace the word "static" with "shared". Because they are shared, they cannot refer to $this, which refers to a specific instance (not shared). Static Variables (i.e. static $db_connection) can be shared among all instances of a type of object. For example, all database objects share a single connection (static $connection).

Static Variables Example: Pretend we have a database class with a single member variable: static $num_connections; Now, put this in the constructor:

function __construct()
{
    if(!isset $num_connections || $num_connections==null)
    {
        $num_connections=0;
    }
    else
    {
        $num_connections++;
    }
}

Just as objects have constructors, they also have destructors, which are executed when the object dies or is unset:

function __destruct()
{
    $num_connections--;
}

Every time we create a new instance, it will increase our connection counter by one. Every time we destroy or stop using an instance, it will decrease the connection counter by one. In this way, we can monitor the number of instances of the database object we have in use with:

echo DB::num_connections;

Because $num_connections is static (shared), it will reflect the total number of active database objects. You may have seen this technique used to share database connections among all instances of a database class. This is done because creating the database connection takes a long time, so it's best to create just one, and share it (this is called a Singleton Pattern).

Static Methods (i.e. public static View::format_phone_number($digits)) can be used WITHOUT first instantiating one of those objects (i.e. They do not internally refer to $this).

Static Method Example:

public static function prettyName($first_name, $last_name)
{
    echo ucfirst($first_name).' '.ucfirst($last_name);
}

echo Person::prettyName($derek->first_name, $derek->last_name);

As you can see, public static function prettyName knows nothing about the object. It's just working with the parameters you pass in, like a normal function that's not part of an object. Why bother, then, if we could just have it not as part of the object?

  1. First, attaching functions to objects helps you keep things organized, so you know where to find them.
  2. Second, it prevents naming conflicts. In a big project, you're likely to have two developers create getName() functions. If one creates a ClassName1::getName(), and the other creates ClassName2::getName(), it's no problem at all. No conflict. Yay static methods!

SELF:: If you are coding outside the object that has the static method you want to refer to, you must call it using the object's name View::format_phone_number($phone_number); If you are coding inside the object that has the static method you want to refer to, you can either use the object's name View::format_phone_number($pn), OR you can use the self::format_phone_number($pn) shortcut

The same goes for static variables: Example: View::templates_path versus self::templates_path

Inside the DB class, if we were referring to a static method of some other object, we would use the object's name: Example: Session::getUsersOnline();

But if the DB class wanted to refer to its own static variable, it would just say self: Example: self::connection;

Hope that helps clear things up :)

How to allow Cross domain request in apache2

Ubuntu Apache2 solution that worked for me .htaccess edit did not work for me I had to modify the conf file.

nano /etc/apache2/sites-available/mydomain.xyz.conf

my config that worked to allow CORS Support

<IfModule mod_ssl.c>
    <VirtualHost *:443>

        ServerName mydomain.xyz
        ServerAlias www.mydomain.xyz

        ServerAdmin [email protected]
        DocumentRoot /var/www/mydomain.xyz/public

        ### following three lines are for CORS support
        Header add Access-Control-Allow-Origin "*"
        Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
        Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        SSLCertificateFile /etc/letsencrypt/live/mydomain.xyz/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.xyz/privkey.pem

    </VirtualHost>
</IfModule>

then type the following command

a2enmod headers

make sure cache is clear before trying

What is the difference between JOIN and UNION?

UNION combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union.

By using JOINs, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how SQL should use data from one table to select the rows in another table.

The UNION operation is different from using JOINs that combine columns from two tables.

UNION Example:

SELECT 1 AS [Column1], 2 AS [Column2]
UNION
SELECT 3 AS [Column1], 4 AS [Column2]

Output:

Column1    Column2
-------------------
1          2
3          4

JOIN Example:

SELECT a.Column1, b.Column2 FROM TableA a INNER JOIN TableB b ON a.Id = b.AFKId

This will output all the rows from both the tables for which the condition a.Id = b.AFKId is true.

Displaying output of a remote command with Ansible

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

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

Visual Studio 2015 installer hangs during install?

For Windows10:

1) Kill VS2015 Process if hung

2) Disable Windows Defender

3) Open VS2015 as Administrator

4) Enable Windows Defender

5) Initial VS2015 startup is complete

Recommendation for compressing JPG files with ImageMagick

@JavisPerez -- Is there any way to compress that image to 150kb at least? Is that possible? What ImageMagick options can I use?

See the following links where there is an option in ImageMagick to specify the desired output file size for writing to JPG files.

http://www.imagemagick.org/Usage/formats/#jpg_write http://www.imagemagick.org/script/command-line-options.php#define

-define jpeg:extent={size} As of IM v6.5.8-2 you can specify a maximum output filesize for the JPEG image. The size is specified with a suffix. For example "400kb".

convert image.jpg -define jpeg:extent=150kb result.jpg

You will lose some quality by decompressing and recompressing in addition to any loss due to lowering -quality value from the input.

Relative instead of Absolute paths in Excel VBA

Here's my quick and simple function for getting the absolute path from a relative path.

The difference from the accepted answer is that this function can handle relative paths that moves up to parent folders.

Example:

Workbooks.Open FileName:=GetAbsolutePath("..\..\TRICATEndurance Summary.html")

Code:

' Gets an absolute path from a relative path in the active workbook
Public Function GetAbsolutePath(relativePath As String) As String
    
    Dim absPath As String
    Dim pos As Integer
    
    absPath = ActiveWorkbook.Path
    
    ' Make sure paths are in correct format
    relativePath = Replace(relativePath, "/", "\")
    absPath = Replace(absPath, "/", "\")
    
    Do While Left$(relativePath, 3) = "..\"
    
        ' Remove level from relative path
        relativePath = Mid$(relativePath, 4)
        
        ' Remove level from absolute path
        pos = InStrRev(absPath, "\")
        absPath = Left$(absPath, pos - 1)
    
    Loop
    
    GetAbsolutePath = PathCombine(absPath, relativePath)
    
End Function

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

In the relevant page which makes a mixed content https to http call which is not accessible we can add the following entry in the relevant and get rid of the mixed content error.

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

What is the iPhone 4 user-agent?

You cannot identify the (hardware) version of an iPhone by user agent.

It's only possible to recognize that it's an iPhone and which software versions it's running.

Using the Safari User Agent String

Not even WURLF can.

Converting .NET DateTime to JSON

The previous answers all state that you can do the following:

var d = eval(net_datetime.slice(1, -1));

However, this doesn't work in either Chrome or FF because what's getting evaluated literally is:

// returns the current timestamp instead of the specified epoch timestamp
var d = Date([epoch timestamp]);

The correct way to do this is:

var d = eval("new " + net_datetime.slice(1, -1)); // which parses to

var d = new Date([epoch timestamp]); 

Permission to write to the SD card

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory();

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Excel VBA Run-time Error '32809' - Trying to Understand it

In my case, the error occurred executing a macro in: Sheets("own sheet one").Select

copy the sheet into another with other name, ie. "oso", then delete the original sheet and renamed the new one as "own sheet one"

Excel 2013

Java - get the current class name?

The combination of both answers. Also prints a method name:

Class thisClass = new Object(){}.getClass();
String className = thisClass.getEnclosingClass().getSimpleName();
String methodName = thisClass.getEnclosingMethod().getName();
Log.d("app", className + ":" + methodName);

How to scroll to top of a div using jQuery?

I don't know why but you have to add a setTimeout with at least for me 200ms:

setTimeout( function() {$("#DIV_ID").scrollTop(0)}, 200 );

Tested with Firefox / Chrome / Edge.

What is the purpose of Looper and how to use it?

I will try to explain the purpose of looper class as simple as possible. With a normal thread of Java when the run method completes the execution we say the thread has done it's job and thread lives no longer after that. what if we want to execute more tasks throughout our program with that same thread which is not living anymore? Oh there is a problem now right? Yes because we want to execute more tasks but the thread in not alive anymore. It is where the Looper comes in to rescue us. Looper as the name suggests loops. Looper is nothing more than an infinite loop inside your thread. So, it keeps the thread alive for an infinite time until we explicitly calls quit() method. Calling quit() method on the infinitely alive thread will make the condition false in the infinite loop inside the thread thus, infinite loop will exit. so, the thread will die or will no longer be alive. And it's critical to call the quit() method on our Thread to which looper is attached otherwise they will be there in your system just like Zombies. So, for example if we want to create a background thread to do some multiple tasks over it. we will create a simple Java's thread and will use Looper class to prepare a looper and attach the prepared looper with that thread so that our thread can live as longer as we want them because we can always call quit() anytime whenever we want to terminate our thread. So our the looper will keep our thread alive thus we will be able to execute multiple tasks with the same thread and when we are done we will call quit() to terminate the thread. What if we want our Main thread or UI thread to display the results computed by the background thread or non-UI thread on some UI elements? for that purpose there comes in the concept of Handlers; via handlers we can do inter-process communication or say via handlers two threads can communicate with each other. So, the main thread will have an associated Handler and Background thread will communicate with Main Thread via that handler to get the task done of displaying the results computed by it on some UI elements on Main thread. I know I am explaining only theory here but try to understand the concept because understanding the concept in depth is very important. And I am posting a link below which will take you to a small video series about Looper, Handler and HandlerThread and I will highly recommend watching it and all these concepts will get cleared with examples there.

https://www.youtube.com/watch?v=rfLMwbOKLRk&list=PL6nth5sRD25hVezlyqlBO9dafKMc5fAU2&index=1

How do I get the calling method name and type using reflection?

Technically, you can use StackTrace, but this is very slow and will not give you the answers you expect a lot of the time. This is because during release builds optimizations can occur that will remove certain method calls. Hence you can't be sure in release whether stacktrace is "correct" or not.

Really, there isn't any foolproof or fast way of doing this in C#. You should really be asking yourself why you need this and how you can architect your application, so you can do what you want without knowing which method called it.

jquery can't get data attribute value

Iyap . Its work Case sensitive in data name data-x10

var variable = $('#myButton').data("x10"); // we get the value of custom data attribute

Select first occurring element after another element

I use latest CSS and "+" didn't work for me so I end up with

:first-child

MVC 4 Data Annotations "Display" Attribute

One of the benefits is you can use it in multiple views and have a consistent label text. It is also used by asp.net MVC scaffolding to generate the labels text and makes it easier to generate meaningful text

[Display(Name = "Wild and Crazy")]
public string WildAndCrazyProperty { get; set; }

"Wild and Crazy" shows up consistently wherever you use the property in your application.

Sometimes this is not flexible as you might want to change the text in some view. In that case, you will have to use custom markup like in your second example

How can I render repeating React elements?

You can put expressions inside braces. Notice in the compiled JavaScript why a for loop would never be possible inside JSX syntax; JSX amounts to function calls and sugared function arguments. Only expressions are allowed.

(Also: Remember to add key attributes to components rendered inside loops.)

JSX + ES2015:

render() {
  return (
    <table className="MyClassName">
      <thead>
        <tr>
          {this.props.titles.map(title =>
            <th key={title}>{title}</th>
          )}
        </tr>
      </thead>
      <tbody>
        {this.props.rows.map((row, i) =>
          <tr key={i}>
            {row.map((col, j) =>
              <td key={j}>{col}</td>
            )}
          </tr>
        )}
      </tbody>
    </table>
  );
} 

JavaScript:

render: function() {
  return (
    React.DOM.table({className: "MyClassName"}, 
      React.DOM.thead(null, 
        React.DOM.tr(null, 
          this.props.titles.map(function(title) {
            return React.DOM.th({key: title}, title);
          })
        )
      ), 
      React.DOM.tbody(null, 
        this.props.rows.map(function(row, i) {
          return (
            React.DOM.tr({key: i}, 
              row.map(function(col, j) {
                return React.DOM.td({key: j}, col);
              })
            )
          );
        })
      )
    )
  );
} 

Output array to CSV in Ruby

To a file:

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

To a string:

require 'csv'
csv_string = CSV.generate do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

Xcode Error: "The app ID cannot be registered to your development team."

My problem was I was modifying the settings for the wrong version of my app.

enter image description here

I had "Debug" selected instead of "Release", so my bundle identifier was not accurate when it came time to Archive.

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I was facing the similar type of issue: Code Snippet :

<c:forEach items="${orderList}" var="xx"> ${xx.id} <br>
</c:forEach>

There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.

So make sure about space. They play crucial role sometimes. :p

Python spacing and aligning strings

@IronMensan's format method answer is the way to go. But in the interest of answering your question about ljust:

>>> def printit():
...     print 'Location: 10-10-10-10'.ljust(40) + 'Revision: 1'
...     print 'District: Tower'.ljust(40) + 'Date: May 16, 2012'
...     print 'User: LOD'.ljust(40) + 'Time: 10:15'
...
>>> printit()
Location: 10-10-10-10                   Revision: 1
District: Tower                         Date: May 16, 2012
User: LOD                               Time: 10:15

Edit to note this method doesn't require you to know how long your strings are. .format() may also, but I'm not familiar enough with it to say.

>>> uname='LOD'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: LOD                               Time: 10:15'
>>> uname='Tiddlywinks'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: Tiddlywinks                       Time: 10:15'

How to fill the whole canvas with specific color?

You can change the background of the canvas by doing this:

<head>
    <style>
        canvas {
            background-color: blue;
        }
    </style>
</head>

How do I set/unset a cookie with jQuery?

You can use a plugin available here..

https://plugins.jquery.com/cookie/

and then to write a cookie do $.cookie("test", 1);

to access the set cookie do $.cookie("test");

How to add values in a variable in Unix shell scripting?

the above script may not run in ksh. you have to use the 'let' opparand to assing the value and then echo it.

val1=4

val2=3

let val3=$val1+$val2

echo $val3 

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

Vector of Vectors to create matrix

You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:

// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));

This creates a vector of RR size CC vectors, filled with 0.

How to get subarray from array?

_x000D_
_x000D_
const array_one = [11, 22, 33, 44, 55];_x000D_
const start = 1;_x000D_
const end = array_one.length - 1;_x000D_
const array_2 = array_one.slice(start, end);_x000D_
console.log(array_2);
_x000D_
_x000D_
_x000D_

Using C# to check if string contains a string in string array

Try this

string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };

var t = lines.ToList().Find(c => c.Contains(stringToCheck));

It will return you the line with the first incidence of the text that you are looking for.

How to write LDAP query to test if user is member of a group?

I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

Converting JSON String to Dictionary Not List

You can use the following:

import json

 with open('<yourFile>.json', 'r') as JSON:
       json_dict = json.load(JSON)

 # Now you can use it like dictionary
 # For example:

 print(json_dict["username"])

Rails Active Record find(:all, :order => ) issue

The problem is that date is a reserved sqlite3 keyword. I had a similar problem with time, also a reserved keyword, which worked fine in PostgreSQL, but not in sqlite3. The solution is renaming the column.

See this: Sqlite3 activerecord :order => "time DESC" doesn't sort

Change EditText hint color when using TextInputLayout

From the documentation:

The hint should be set on the TextInputLayout, rather than the EditText. If a hint is specified on the child EditText in XML, the TextInputLayout might still work correctly; TextInputLayout will use the EditText's hint as its floating label. However, future calls to modify the hint will not update TextInputLayout's hint. To avoid unintended behavior, call setHint(CharSequence) and getHint() on TextInputLayout, instead of on EditText.

Try setting android:hint and app:hintTextColor on TextInputLayout instead of on TextInputEditText.

Making a Sass mixin with optional arguments

I am new to css compilers, hope this helps,

        @mixin positionStyle($params...){

            $temp:nth($params,1);
            @if $temp != null{
            position:$temp;
            }

             $temp:nth($params,2);
            @if $temp != null{
            top:$temp;
            }

             $temp:nth($params,3);
            @if $temp != null{
            right:$temp;
            }

             $temp:nth($params,4);
            @if $temp != null{
            bottom:$temp;
            }

            $temp:nth($params,5);
            @if $temp != null{
            left:$temp;
            }

    .someClass{
    @include positionStyle(absolute,30px,5px,null,null);
    }

//output

.someClass{
position:absolute;
 top: 30px;
 right: 5px;
}

How do I make a "div" button submit the form its sitting in?

To keep the scripting in one place rather than using onClick in the HTML tag, add the following code to your script block:

$('#id-of-the-button').click(function() {document.forms[0].submit()});

Which assumes you just have the one form on the page.

Ignoring SSL certificate in Apache HttpClient 4.3

Initially, i was able to disable for localhost using trust strategy, later i added NoopHostnameVerifier. Now it will work for both localhost and any machine name

SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext, NoopHostnameVerifier.INSTANCE);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

How to convert Map keys to array?

OK, let's go a bit more comprehensive and start with what's Map for those who don't know this feature in JavaScript... MDN says:

The Map object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and primitive values) may be used as either a key or a value.

As you mentioned, you can easily create an instance of Map using new keyword... In your case:

let myMap = new Map().set('a', 1).set('b', 2);

So let's see...

The way you mentioned is an OK way to do it, but yes, there are more concise ways to do that...

Map has many methods which you can use, like set() which you already used to assign the key values...

One of them is keys() which returns all the keys...

In your case, it will return:

MapIterator {"a", "b"}

and you easily convert them to an Array using ES6 ways, like spread operator...

const b = [...myMap.keys()];

Git add all files modified, deleted, and untracked?

For newer version of Git.

I tried git add -A and this prompted,

warning: The behavior of 'git add --all (or -A)' with no path argument from a subdirectory of the tree will change in Git 2.0 and should not be used anymore. To add content for the whole tree, run:

git add --all :/ (or git add -A :/)

To restrict the command to the current directory, run:

git add --all . (or git add -A .)

With the current Git version, the command is restricted to the current directory.


Then I tried below which worked.

git add --all :/

Twitter Bootstrap button click to toggle expand/collapse text section above button

It's possible to do this without using extra JS code using the data-collapse and data-target attributes on the a link.

e.g.

<a class="btn" data-toggle="collapse" data-target="#viewdetails">View details &raquo;</a>

Here's a working example.

Global Events in Angular

We implemented a ngModelChange observable directive that sends all model changes through an event emitter that you instantiate in your own component. You simply have to bind your event emitter to the directive.

See: https://github.com/atomicbits/angular2-modelchangeobservable

In html, bind your event emitter (countryChanged in this example):

<input [(ngModel)]="country.name"
       [modelChangeObservable]="countryChanged" 
       placeholder="Country"
       name="country" id="country"></input>

In your typescript component, do some async operations on the EventEmitter:

import ...
import {ModelChangeObservable} from './model-change-observable.directive'


@Component({
    selector: 'my-component',
    directives: [ModelChangeObservable],
    providers: [],
    templateUrl: 'my-component.html'
})

export class MyComponent {

    @Input()
    country: Country

    selectedCountries:Country[]
    countries:Country[] = <Country[]>[]
    countryChanged:EventEmitter<string> = new EventEmitter<string>()


    constructor() {

        this.countryChanged
            .filter((text:string) => text.length > 2)
            .debounceTime(300)
            .subscribe((countryName:string) => {
                let query = new RegExp(countryName, 'ig')
                this.selectedCountries = this.countries.filter((country:Country) => {
                    return query.test(country.name)
                })
            })
    }
}

AttributeError: 'DataFrame' object has no attribute

value_counts work only for series. It won't work for entire DataFrame. Try selecting only one column and using this attribute. For example:

df['accepted'].value_counts()

It also won't work if you have duplicate columns. This is because when you select a particular column, it will also represent the duplicate column and will return dataframe instead of series. At that time remove duplicate column by using

df = df.loc[:,~df.columns.duplicated()]
df['accepted'].value_counts()

How do you stylize a font in Swift?

Add Custom Font in Swift

  1. Drag and drop your font in your project.
  2. Double check that it is added in Copy Bundle Resource. (Build Phase -> Copy Bundle Resource).
  3. In your plist file add "Font Provided by application" and add your fonts with full name.
  4. Now use your font like: myLabel.font = UIFont (name: "GILLSANSCE-ROMAN", size: 20)

Select row with most recent date per user

Possibly you can do group by user and then order by time desc. Something like as below

  SELECT * FROM lms_attendance group by user order by time desc;

Better way to cast object to int

int i = myObject.myField.CastTo<int>();

Kotlin: How to get and set a text to TextView in Android using Kotlin?

The top post has 'as TextView' appended on the end. You might get other compiler errors if you leave this on. The following should be fine.

val text: TextView = findViewById(R.id.android_text) as TextView

Where 'android_text' is the ID of your textView

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

The following answer is to merge data into same table

MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
    ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif') 
WHEN NOT MATCHED THEN
        INSERT ( d.USERS_ID, d.USER_NAME)
        VALUES ('123','itszaif');

This command checks if USER_ID and USER_NAME are matched, if not matched then it will insert.

How to display scroll bar onto a html table

Very easy, just wrap the table in a div that has overflow-y:scroll; and overflow-x:scroll properties, and make the div have a width and length smaller than the table. IT WILL WORK!!!

Text size of android design TabLayout tabs

Do as following.

1. Add the Style to the XML

    <style name="MyTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
    </style>

2. Apply Style

Find the Layout containing the TabLayout and add the style. The added line is bold.

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabTextAppearance="@style/MyTabLayoutTextAppearance" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

How to print values separated by spaces instead of new lines in Python 2.7

This does almost everything you want:

f = open('data.txt', 'rb')

while True:
    char = f.read(1)
    if not char: break
    print "{:02x}".format(ord(char)),

With data.txt created like this:

f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()

I get the following output:

61 62 0d 0a 63 64

tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.

===

1. Your variable names are horrendous.

That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:

fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()

xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0

while yxxxxx < xxyxxx:
    xyxxxx = hex(ord(xxxyxx[yxxxxx]))
    xyxxxx = xyxxxx[-2:]
    yxxxxx = yxxxxx + 1
    xxxxxy = chr(13) + chr(10)
    xxxxyx = str(xxxxxy)
    xyxxxxx = str(xyxxxx)
    xyxxxxx.replace(xxxxyx, ' ')
    print xyxxxxx

That program runs fine, but it is impossible to understand.

2. The hex() function produces strings of different lengths.

For instance,

print hex(61)
print hex(15)

--output:--
0x3d
0xf

And taking the slice [-2:] for each of those strings gives you:

3d
xf

See how you got the 'x' in the second one? The slice:

[-2:] 

says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:

[2:]  

3. Your code will never replace any newlines.

Suppose your file has these two consecutive characters:

"\r\n"

Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd", and you slice off the first two characters giving you:

"d"

Next, this line in your code:

bndtx.replace(entx, ' ')

tries to find every occurrence of the string "\r\n" in the string "d" and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d" is one character long.

The replacement won't work for "\r\n" and "0d" either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"? The ascii code for the character "0" is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:

 x = '0d' + '0a'
 x.replace("\r\n", " ")
 print x

 --output:--
 '0d0a'

Nor will this:

x = 'd' + 'a'
x.replace("\r\n", " ")
print x

--output:--
da

The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:

char = "a"
code = ord(char)
hex_str = hex(code)

print char.replace(hex_str, " ")

...you can't expect "a" to be replaced by a space. If you examine the output here:

char = "a"
print repr(char)

code = ord(char)
print repr(code)

hex_str = hex(code)
print repr(hex_str)

print repr(
    char.replace(hex_str, " ")
)

--output:--
'a'
97
'0x61'
'a'

You can see that 'a' is a string with one character in it, and '0x61' is a string with 4 characters in it: '0', 'x', '6', and '1', and you can never find a four character string inside a one character string.

4) Removing newlines can corrupt the data.

For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.

However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.

I hope all that's not too confusing.

select unique rows based on single distinct column

Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try

;WITH ue(id)
 AS
 (
   SELECT MAX(id)
   FROM table
   GROUP BY email
 )
 SELECT * FROM table t
 INNER JOIN ue ON ue.id = t.id

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

How to access property of anonymous type in C#?

You could iterate over the anonymous type's properties using Reflection; see if there is a "Checked" property and if there is then get its value.

See this blog post: http://blogs.msdn.com/wriju/archive/2007/10/26/c-3-0-anonymous-type-and-net-reflection-hand-in-hand.aspx

So something like:

foreach(object o in nodes)
{
    Type t = o.GetType();

    PropertyInfo[] pi = t.GetProperties(); 

    foreach (PropertyInfo p in pi)
    {
        if (p.Name=="Checked" && !(bool)p.GetValue(o))
            Console.WriteLine("awesome!");
    }
}

How can I solve equations in Python?

If you only want to solve the extremely limited set of equations mx + c = y for positive integer m, c, y, then this will do:

import re
def solve_linear_equation ( equ ):
    """
    Given an input string of the format "3x+2=6", solves for x.
    The format must be as shown - no whitespace, no decimal numbers,
    no negative numbers.
    """
    match = re.match(r"(\d+)x\+(\d+)=(\d+)", equ)
    m, c, y = match.groups()
    m, c, y = float(m), float(c), float(y) # Convert from strings to numbers
    x = (y-c)/m
    print ("x = %f" % x)

Some tests:

>>> solve_linear_equation("2x+4=12")
x = 4.000000
>>> solve_linear_equation("123x+456=789")
x = 2.707317
>>> 

If you want to recognise and solve arbitrary equations, like sin(x) + e^(i*pi*x) = 1, then you will need to implement some kind of symbolic maths engine, similar to maxima, Mathematica, MATLAB's solve() or Symbolic Toolbox, etc. As a novice, this is beyond your ken.

Alternative to iFrames with HTML5

You can use an XMLHttpRequest to load a page into a div (or any other element of your page really). An exemple function would be:

function loadPage(){
if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}else{
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("ID OF ELEMENT YOU WANT TO LOAD PAGE IN").innerHTML=xmlhttp.responseText;
    }
}

xmlhttp.open("POST","WEBPAGE YOU WANT TO LOAD",true);
xmlhttp.send();
}

If your sever is capable, you could also use PHP to do this, but since you're asking for an HTML5 method, this should be all you need.

Converting strings to floats in a DataFrame

You can try df.column_name = df.column_name.astype(float). As for the NaN values, you need to specify how they should be converted, but you can use the .fillna method to do it.

Example:

In [12]: df
Out[12]: 
     a    b
0  0.1  0.2
1  NaN  0.3
2  0.4  0.5

In [13]: df.a.values
Out[13]: array(['0.1', nan, '0.4'], dtype=object)

In [14]: df.a = df.a.astype(float).fillna(0.0)

In [15]: df
Out[15]: 
     a    b
0  0.1  0.2
1  0.0  0.3
2  0.4  0.5

In [16]: df.a.values
Out[16]: array([ 0.1,  0. ,  0.4])

Java - How to create new Entry (key, value)

If you are using Clojure, you have another option:

(defn map-entry
  [k v]
  (clojure.lang.MapEntry/create k v))

How do I use extern to share variables between source files?

extern keyword is used with the variable for its identification as a global variable.

It also represents that you can use the variable declared using extern keyword in any file though it is declared/defined in other file.

Make button width fit to the text

If you are developing to a modern browser. https://caniuse.com/#search=fit%20content

You can use:

width: fit-content;

How to force view controller orientation in iOS 8?

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [UIViewController attemptRotationToDeviceOrientation];
}

HTML.ActionLink vs Url.Action in ASP.NET Razor

<p>
    @Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("Index", "Company", FormMethod.Get))
{
    <p>
        Find by Name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />
        <input type="button" value="Clear" onclick="location.href='@Url.Action("Index","Company")'"/>
    </p>
}

In the above example you can see that If I specifically need a button to do some action, I have to do it with @Url.Action whereas if I just want a link I will use @Html.ActionLink. The point is when you have to use some element(HTML) with action url is used.

Android ImageView Animation

You can also simply use the Rotate animation feature. That runs a specific animation, for a pre-determined amount of time, on an ImageView.

Animation rotate = AnimationUtils.loadAnimation([context], R.anim.rotate_picture);
splash.startAnimation(rotate);

Then create an animation XML file in your res/anim called rotate_picture with the content:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shareInterpolator="false">

    <rotate 
    android:fromDegrees="0"
    android:toDegrees="360"
    android:duration="5000"
    android:pivotX="50%"
    android:pivotY="50%">
</rotate>
</set>

Now unfortunately, this will only run it once. You'll need a loop somewhere to make it repeat the animation while it's waiting. I experimented a little bit and got my program stuck in infinite loops, so I'm not sure of the best way to that. EDIT: Christopher's answer provides the info on how to make it loop properly, so removing my bad suggestion about separate threads!

Check variable equality against a list of values

Now you may have a better solution to resolve this scenario, but other way which i preferred.

const arr = [1,3,12]
if( arr.includes(foo)) { // it will return true if you `foo` is one of array values else false
  // code here    
}

I preferred above solution over the indexOf check where you need to check index as well.

includes docs

if ( arr.indexOf( foo ) !== -1 ) { }

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Working with huge files in VIM

This has been a recurring question for many years. (The numbers keep changing, but the concept is the same: how do I view or edit files that are larger than memory?)

Obviously more or less are good approaches to merely reading the files --- less even offers vi like keybindings for scrolling and searching.

A Freshmeat search on "large files" suggests that two editors would be particularly suited to your needs.

One would be: lfhex ... a large file hex editor (which depends on Qt). That one, obviously, entails using a GUI.

Another would seem to be suited to console use: hed ... and it claims to have a vim-like interface (including an ex mode?).

I'm sure I've seen other editors for Linux/UNIX that were able to page through files without loading their entirety into memory. However, I don't recall any of their names. I'm making this response a "wiki" entry to encourage others to add their links to such editors. (Yes, I am familiar with ways to work around the issue using split and cat; but I'm thinking of editors, especially console/curses editors which can dispense with that and save us the time/latencies and disk space overhead that such approaches entail).

MongoDB query multiple collections at once

One solution: add isAdmin: 0/1 flag to your post collection document.

Other solution: use DBrefs

Android: disabling highlight on listView click

you can just get the pos that you get from the onItemClick and do:

listView.setItemChecked(pos, false);

that's the best way i know of

How to merge many PDF files into a single one?

There are lots of free tools that can do this.

I use PDFTK (a open source cross-platform command-line tool) for things like that.

Making an svg image object clickable with onclick, avoiding absolute positioning

Perhaps what you're looking for is the SVG element's pointer-events property, which you can read about at the SVG w3C working group docs.

You can use CSS to set what happens to the SVG element when it is clicked, etc.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

Add a build task to concatenate and register your html partials in the Angular $templateCache. (This answer is a more detailed variant of karlgold's answer.)

For grunt, use grunt-angular-templates. For gulp, use gulp-angular-templatecache.

Below are config/code snippets to illustrate.

gruntfile.js Example:

ngtemplates: {
  app: {                
    src: ['app/partials/**.html', 'app/views/**.html'],
    dest: 'app/scripts/templates.js'
  },
  options: {
    module: 'myModule'
  }
}

gulpfile.js Example:

var templateCache = require('gulp-angular-templatecache');
var paths = ['app/partials/.html', 'app/views/.html'];

gulp.task('createTemplateCache', function () {
return gulp.src(paths)
    .pipe(templateCache('templates.js', { module: 'myModule', root:'app/views'}))
    .pipe(gulp.dest('app/scripts'));
    });

templates.js (this file is autogenerated by the build task)

$templateCache.put('app/views/main.html', "<div class=\"main\">\r"...

index.html

<script src="app/scripts/templates.js"></script>
<div ng-include ng-controller="main as vm" src="'app/views/main.html'"></div>

SQL: set existing column as Primary Key in MySQL

ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

if you have this problem and you don't have another option change the engine to any other engine like 'myisam', then try to create the table.

disclaimer: it is not the valid answer as you may have foreign key constraints which will not be supported by another storage engine. Every storage engine has their own specialty to store and access data, these points also to be taken in account.

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

how to console.log result of this ajax call?

In Chrome, right click in the console and check 'preserve log on navigation'.

Cannot install node modules that require compilation on Windows 7 x64/VS2012

on windows 8, it worked for me using :

npm install -g node-gyp -msvs_version=2012

then

npm install -g restify

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

Scanner only reads first word instead of line

The javadocs for Scanner answer your question

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

You might change the default whitespace pattern the Scanner is using by doing something like

Scanner s = new Scanner();
s.useDelimiter("\n");

C++ Calling a function from another class

in A you have used a definition of B which is not given until then , that's why the compiler is giving error .

How to loop through a dataset in powershell?

Here's a practical example (build a dataset from your current location):

$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])

dir | foreach {
    $dr = $ds.Tables["tblTest"].NewRow()
    $dr["Name"] = $_.name
    $dr["Path"] = $_.fullname
    $ds.Tables["tblTest"].Rows.Add($dr)
}


$ds.Tables["tblTest"]

$ds.Tables["tblTest"] is an object that you can manipulate just like any other Powershell object:

$ds.Tables["tblTest"] | foreach {
    write-host 'Name value is : $_.name
    write-host 'Path value is : $_.path
}

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

Define global constants

In Angular2, you have the following provide definition, which allows you to setup different kinds of dependencies:

provide(token: any, {useClass, useValue, useExisting, useFactory, deps, multi}

Comparing to Angular 1

app.service in Angular1 is equivalent to useClass in Angular2.

app.factory in Angular1 is equivalent to useFactory in Angular2.

app.constant and app.value has been simplified to useValue with less constraints. i.e. there is no config block anymore.

app.provider - There is no equivalent in Angular 2.

Examples

To setup with the root injector:

bootstrap(AppComponent,[provide(API_ENDPOINT, { useValue='http://127.0.0.1:6666/api/' })]);

Or setup with your component's injector:

providers: [provide(API_ENDPOINT, { useValue: 'http://127.0.0.1:6666/api/'})]

provide is short hand for:

var injectorValue = Injector.resolveAndCreate([
  new Provider(API_ENDPOINT, { useValue: 'http://127.0.0.1:6666/api/'})
]);

With the injector, getting the value is easy:

var endpoint = injectorValue.get(API_ENDPOINT);

Reading DataSet

If this is from a SQL Server datebase you could issue this kind of query...

Select Top 1 DepartureTime From TrainSchedule where DepartureTime > 
GetUTCDate()
Order By DepartureTime ASC

GetDate() could also be used, not sure how dates are being stored.

I am not sure how the data is being stored and/or read.

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

How to include multiple js files using jQuery $.getScript() method

Load the following up needed script in the callback of the previous one like:

$.getScript('scripta.js', function()
{
   $.getScript('scriptb.js', function()
   {
       // run script that depends on scripta.js and scriptb.js
   });
});

How to set fake GPS location on IOS real device

you can do it on real device by run device in Debug mode

Click Debug->Simulate Location -> add .gpx file for your location during run time

Should C# or C++ be chosen for learning Games Programming (consoles)?

C++ with win32/GDI is relatively easy to get going, but far more difficult than say Flash or Python (pygame) - however, by using C++ you'll learn a lot in the process and be well poised to continue advancing your career as a game developer. You can also look into XNA if you want to program to the xbox360.

I took some classes at Game Institute (GI) and learned a lot about C++, win32 API and DirectX.

How can I unstage my files again after making a local commit?

git reset --soft is just for that: it is like git reset --hard, but doesn't touch the files.

Set inputType for an EditText Programmatically?

Here are the various Input Types as shown on the standard keyboard.

input types demo

Setting the input type programmatically

editText.setInputType(InputType.TYPE_CLASS_TEXT);

Other options besides TYPE_CLASS_TEXT can be found in the documentation.

Setting the input type in XML

<EditText
    android:inputType="text"
/>

Other options besides text can be found in the documentation.

Supplemental code

Here is the code for the image above.

public class MainActivity extends AppCompatActivity {

    EditText editText;
    TextView textView;
    List<InputTypeItem> inputTypes;
    int counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        initArray();
    }

    public void onChangeInputTypeButtonClick(View view) {
        if (counter >= inputTypes.size()) {
            startOver();
            return;
        }
        textView.setText(inputTypes.get(counter).name);
        editText.setInputType(inputTypes.get(counter).value);
        editText.setSelection(editText.getText().length());
        counter++;
    }

    private void startOver() {
        counter = 0;
        textView.setText("");
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }


    private void initArray() {
        inputTypes = new ArrayList<>();
        inputTypes.add(new InputTypeItem("date",  InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE));
        inputTypes.add(new InputTypeItem("datetime", InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL));
        inputTypes.add(new InputTypeItem("none", InputType.TYPE_NULL));
        inputTypes.add(new InputTypeItem("number",  InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL));
        inputTypes.add(new InputTypeItem("numberDecimal",  InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL));
        inputTypes.add(new InputTypeItem("numberPassword",  InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
        inputTypes.add(new InputTypeItem("numberSigned", InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED));
        inputTypes.add(new InputTypeItem("phone",  InputType.TYPE_CLASS_PHONE));
        inputTypes.add(new InputTypeItem("text",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL));
        inputTypes.add(new InputTypeItem("textAutoComplete", InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE));
        inputTypes.add(new InputTypeItem("textAutoCorrect",  InputType.TYPE_TEXT_FLAG_AUTO_CORRECT));
        inputTypes.add(new InputTypeItem("textCapCharacters",  InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS));
        inputTypes.add(new InputTypeItem("textCapSentences",  InputType.TYPE_TEXT_FLAG_CAP_SENTENCES));
        inputTypes.add(new InputTypeItem("textCapWords",  InputType.TYPE_TEXT_FLAG_CAP_WORDS));
        inputTypes.add(new InputTypeItem("textEmailAddress",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS));
        inputTypes.add(new InputTypeItem("textEmailSubject", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT));
        inputTypes.add(new InputTypeItem("textFilter",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER));
        inputTypes.add(new InputTypeItem("textLongMessage",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE));
        inputTypes.add(new InputTypeItem("textMultiLine",  InputType.TYPE_TEXT_FLAG_MULTI_LINE));
        inputTypes.add(new InputTypeItem("textNoSuggestions", InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS));
        inputTypes.add(new InputTypeItem("textPassword",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
        inputTypes.add(new InputTypeItem("textPersonName", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME));
        inputTypes.add(new InputTypeItem("textPhonetic",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PHONETIC));
        inputTypes.add(new InputTypeItem("textPostalAddress", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS));
        inputTypes.add(new InputTypeItem("textShortMessage", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
        inputTypes.add(new InputTypeItem("textUri",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI));
        inputTypes.add(new InputTypeItem("textVisiblePassword",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD));
        inputTypes.add(new InputTypeItem("textWebEditText",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT));
        inputTypes.add(new InputTypeItem("textWebEmailAddress", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS));
        inputTypes.add(new InputTypeItem("textWebPassword", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD));
        inputTypes.add(new InputTypeItem("time", InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_TIME));
    }

    class InputTypeItem {
        private String name;
        private int value;
        InputTypeItem(String name, int value) {
            this.name = name;
            this.value = value;
        }
    }
}

See also

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

I've updated the Microsoft.Net.Compilers to version 2.0 or higher

see this

Multi-line strings in PHP

Well,

$xml = "l
vv";

Works.

You can also use the following:

$xml = "l\nvv";

or

$xml = <<<XML
l
vv
XML;

Edit based on comment:

You can concatenate strings using the .= operator.

$str = "Hello";
$str .= " World";
echo $str; //Will echo out "Hello World";

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Had this issue, but it wasn't related to the bitcode setting. I had somehow ended up with duplicate framework files in the Frameworks folder of my XCode project. I deleted all frameworks files that were red (and duplicates). This solved the "Apple Mach O, Linker Command failed with exit code 1" error.

How can I convert a comma-separated string to an array?

The split() method is used to split a string into an array of substrings, and returns the new array.

var array = string.split(',');

Android set bitmap to Imageview

Please try this:

byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream  = new ByteArrayInputStream(decodedString);
Bitmap bitmap  = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

There is no difference between the %i and %d format specifiers for printf. We can see this by going to the draft C99 standard section 7.19.6.1 The fprintf function which also covers printf with respect to format specifiers and it says in paragraph 8:

The conversion specifiers and their meanings are:

and includes the following bullet:

d,i     The int argument is converted to signed decimal in the style
        [-]dddd. The precision specifies the minimum number of digits to
        appear; if the value being converted can be represented in fewer
        digits, it is expanded with leading zeros. The default precision is
        1. The result of converting a zero value with a precision of zero is
        no characters.

On the other hand for scanf there is a difference, %d assume base 10 while %i auto detects the base. We can see this by going to section 7.19.6.2 The fscanf function which covers scanf with respect to format specifier, in paragraph 12 it says:

The conversion specifiers and their meanings are:

and includes the following:

d     Matches an optionally signed decimal integer, whose format is the
      same as expected for the subject sequence of the strtol function with
      the value 10 for the base argument. The corresponding argument shall
      be a pointer to signed integer.

i     Matches an optionally signed integer, whose format is the same as
      expected for the subject sequence of the strtol function with the
      value 0 for the base argument. The corresponding argument shall be a
      pointer to signed integer.

How to make sure that a certain Port is not occupied by any other process

You can use "netstat" to check whether a port is available or not.

Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

You have to put : before port number to get the actual output

Ex netstat -anp | find ":8080"

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

There is a library that provides a better ProcessBuilder, zt-exec. This library can do exactly what you are asking for and more.

Here's what your code would look like with zt-exec instead of ProcessBuilder :

add the dependency :

<dependency>
  <groupId>org.zeroturnaround</groupId>
  <artifactId>zt-exec</artifactId>
  <version>1.11</version>
</dependency>

The code :

new ProcessExecutor()
  .command("somecommand", "arg1", "arg2")
  .redirectOutput(System.out)
  .redirectError(System.err)
  .execute();

Documentation of the library is here : https://github.com/zeroturnaround/zt-exec/

Creating a directory in /sdcard fails

use mkdirs() instead of mkdir()..it worked for me :)

File folder = new File(Environment.getExternalStorageDirectory()+"/Saved CGPA");
if(!folder.exists()){
    if(folder.mkdirs())
    Toast.makeText(this, "New Folder Created", Toast.LENGTH_SHORT).show();
}

File sdCardFile = new File(Environment.getExternalStorageDirectory()+"/Saved CGPA/cgpa.html");

Which method performs better: .Any() vs .Count() > 0?

If you are using the Entity Framework and have a huge table with many records Any() will be much faster. I remember one time I wanted to check to see if a table was empty and it had millions of rows. It took 20-30 seconds for Count() > 0 to complete. It was instant with Any().

Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ....

Way to get all alphabetic chars in an array in PHP?

Another way:

$c = 'A';
$chars = array($c);
while ($c < 'Z') $chars[] = ++$c;

Focusable EditText inside ListView

I just found another solution. I believe it's more a hack than a solution but it works on android 2.3.7 and android 4.3 (I've even tested that good old D-pad)

init your webview as usual and add this: (thanks Michael Bierman)

listView.setItemsCanFocus(true);

During the getView call:

editText.setOnFocusChangeListener(
    new OnFocusChangeListener(View view,boolean hasFocus){
        view.post(new Runnable() {
            @Override
            public void run() {
                view.requestFocus();
                view.requestFocusFromTouch();
            }
     });

How can I get a resource "Folder" from inside my jar File?

This link tells you how.

The magic is the getResourceAsStream() method :

InputStream is = 
this.getClass().getClassLoader().getResourceAsStream("yourpackage/mypackage/myfile.xml")

Section vs Article HTML5

My interpretation is: I think of YouTube it has a comment-section, and inside the comment-section there are multiple articles (in this case comments).

So a section is like a div-container that holds articles.

Java - sending HTTP parameters via POST method easily

here i sent jsonobject as parameter //jsonobject={"name":"lucifer","pass":"abc"}//serverUrl = "http://192.168.100.12/testing" //host=192.168.100.12

  public static String getJson(String serverUrl,String host,String jsonobject){

    StringBuilder sb = new StringBuilder();

    String http = serverUrl;

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(http);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(50000);
        urlConnection.setReadTimeout(50000);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Host", host);
        urlConnection.connect();
        //You Can also Create JSONObject here 
        OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
        out.write(jsonobject);// here i sent the parameter
        out.close();
        int HttpResult = urlConnection.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream(), "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            Log.e("new Test", "" + sb.toString());
            return sb.toString();
        } else {
            Log.e(" ", "" + urlConnection.getResponseMessage());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }
    return null;
}

Re-assign host access permission to MySQL user

For reference, the solution is:

UPDATE mysql.user SET host = '10.0.0.%' WHERE host = 'internalfoo' AND user != 'root';
UPDATE mysql.db SET host = '10.0.0.%' WHERE host = 'internalfoo' AND user != 'root';
FLUSH PRIVILEGES;

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Specifically if you want to clear your text box in VB.NET or VB 6.0, write this code:

TextBox1.Items.Clear()

If you are using VBA, then the use this code :

TextBox1.Text = "" or TextBox1.Clear()

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

Why would $_FILES be empty when uploading files to PHP?

Do not trust the temp folder location provided by sys_get_temp_dir if you're in a shared hosting environment.

Here is one more thing to check that has not yet been mentioned...

I assumed, naturally, that the folder where my PHP script stored temporary file uploads was /tmp. This belief was reinforced by the fact that echo sys_get_temp_dir() . PHP_EOL; returns/tmp. Also, echo ini_get('upload_tmp_dir'); returns nothing.

To verify that the uploaded file does in fact briefly appear in my /tmp folder, I added a sleep(30); statement to my script (as suggested here) and navigated to my /tmp folder in cPanel File Manager to locate the file. However, no matter what, the uploaded file was nowhere to be found there.

I spent hours trying to determine the reason for this, and implemented every suggestion that's been offered here.

Finally, after searching my website files for the query tmp, I discovered that my site contained other folders named tmp in different directories. I realized that my PHP script was actually writing the uploaded files to .cagefs/tmp. (The "Show Hidden Files" setting must be enabled in cPanel in order to view this folder.)

So, why does the sys_get_temp_dir function return inaccurate info?

Here's an explanation from the PHP.net webpage for sys_get_temp_dir (i.e., the top comment):

If running on a Linux system where systemd has PrivateTmp=true (which is the default on CentOS 7 and perhaps other newer distros), this function will simply return "/tmp", not the true, much longer, somewhat dynamic path.

This SO post delves into the issue, as well:

Could not reserve enough space for object heap to start JVM

According to this post this error message means:

Heap size is larger than your computer's physical memory.

Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.

Why not downsize other memory settings to free up space for the heap?

process.start() arguments

Not really a direct answer, but I'd highly recommend using LINQPad for this kind of "exploratory" C# programming.

I have the following as a saved "query" in LINQPad:

var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c echo Foo && echo Bar";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardOutput.ReadToEnd().Dump();

Feel free to adapt as needed.

Add an image in a WPF button

Try ContentTemplate:

<Button Grid.Row="2" Grid.Column="0" Width="20" Height="20"
        Template="{StaticResource SomeTemplate}">
    <Button.ContentTemplate>
        <DataTemplate>
            <Image Source="../Folder1/Img1.png" Width="20" />
        </DataTemplate>
    </Button.ContentTemplate>
</Button>

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

If you are using Python 2, the following will be the solution:

import io
for line in io.open("u.item", encoding="ISO-8859-1"):
    # Do something

Because the encoding parameter doesn't work with open(), you will be getting the following error:

TypeError: 'encoding' is an invalid keyword argument for this function

How to print without newline or space?

How to print on the same line:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()

Hide console window from Process.Start C#

This should work, try;


Add a System Reference.

using System.Diagnostics;

Then use this code to run your command in a hiden CMD Window.

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";
cmd.Start();

Cast IList to List

How about this:

List<SubProduct> subProducts = Model.subproduct.ToList();

docker entrypoint running bash script gets "permission denied"

  1. "Permission denied" prevents your script from being invoked at all. Thus, the only syntax that could be possibly pertinent is that of the first line (the "shebang"), which should look like #!/usr/bin/env bash, or #!/bin/bash, or similar depending on your target's filesystem layout.

  2. Most likely the filesystem permissions not being set to allow execute. It's also possible that the shebang references something that isn't executable, but this is far less likely.

  3. Mooted by the ease of repairing the prior issues.


The simple reading of

docker: Error response from daemon: oci runtime error: exec: "/usr/src/app/docker-entrypoint.sh": permission denied.

...is that the script isn't marked executable.

RUN ["chmod", "+x", "/usr/src/app/docker-entrypoint.sh"]

will address this within the container. Alternately, you can ensure that the local copy referenced by the Dockerfile is executable, and then use COPY (which is explicitly documented to retain metadata).

Setting up an MS-Access DB for multi-user access

I have found the SMB2 protocol introduced in Vista to lock the access databases. It can be disabled by the following regedit:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\LanmanServer\Parameters] "Smb2"=dword:00000000

How do I check if an element is hidden in jQuery?

You can use the hidden selector:

// Matches all elements that are hidden
$('element:hidden')

And the visible selector:

// Matches all elements that are visible
$('element:visible')

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

How do I disable a Button in Flutter?

For a specific and limited number of widgets, wrapping them in a widget IgnorePointer does exactly this: when its ignoring property is set to true, the sub-widget (actually, the entire subtree) is not clickable.

IgnorePointer(
    ignoring: true, // or false
    child: RaisedButton(
        onPressed: _logInWithFacebook,
        child: Text("Facebook sign-in"),
        ),
),

Otherwise, if you intend to disable an entire subtree, look into AbsorbPointer().

Apply .gitignore on an existing repository already tracking large number of files

As specified here You can update the index:

git update-index --assume-unchanged /path/to/file

By doing this, the files will not show up in git status or git diff.

To begin tracking the files again you can run:

git update-index --no-assume-unchanged /path/to/file

Tomcat 7: How to set initial heap size correctly?

Just came across this and I've implemented Nathan's solution:

add the line (changing the values as required):

export JAVA_OPTS="-Xms512M -Xmx1024M"

to /usr/share/tomcat7/bin/setenv.sh

If that file doesn't exists then create it and

chown root:root it
chmod 755 it

And then restart tomcat and check it with

ps aux | grep logging

Which should just pick up the instance and show the java parms

How to load Spring Application Context

package com.dataload;

    public class insertCSV 
    {
        public static void main(String args[])
        {
            ApplicationContext context =
        new ClassPathXmlApplicationContext("applicationcontext.xml");


            // retrieve configured instance
            JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
            Job job = context.getBean("job", Job.class);
            JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
        }
    }

JavaScript: location.href to open in new window/tab?

You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.

How to bring an activity to foreground (top of stack)?

You can try this FLAG_ACTIVITY_REORDER_TO_FRONT (the document describes exactly what you want to)

Delete forked repo from GitHub

Deleting your forked repository will not affect the master(original) repository.

Like I have shown an example by deleting a forked repo

This is my forked repo (Image)

Deleting the forked repo

And no changes to the original repository.

The master repo is something like an original one.

Forking is same as creating a xerox copy of the original one. Even if you get your xeroxed paper damaged, will it be that the original document also gets damaged. Obviously No.

So its the same as that.

Hope this helps.

jQuery - how to check if an element exists?

if ($("#MyId").length) { ... write some code here ...}

This from will automatically check for the presence of the element and will return true if an element exists.

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

I had a similar issue and upgrading pip fixed it for me.

python -m pip install --upgrade pip 

This was on Windows and the path to python inside pip.exe was incorrect. See Archimedix answer for more information about the path.

const vs constexpr on variables

No difference here, but it matters when you have a type that has a constructor.

struct S {
    constexpr S(int);
};

const S s0(0);
constexpr S s1(1);

s0 is a constant, but it does not promise to be initialized at compile-time. s1 is marked constexpr, so it is a constant and, because S's constructor is also marked constexpr, it will be initialized at compile-time.

Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program

How to set a default value in react-select

  1. Create a state property for the default option text in the constructor
    • Don't worry about the default option value
  2. Add an option tag to the render function. Only show using state and ternary expression
  3. Create a function to handle when an option was selected
  4. Change the state of the default option value in this event handler function to null

    Class MySelect extends React.Component
    {
        constructor()
        {
            super()
            this.handleChange = this.handleChange.bind(this);
            this.state = {
                selectDefault: "Select An Option"
            }
        }
        handleChange(event)
        {
            const selectedValue = event.target.value;
            //do something with selectedValue
            this.setState({
                selectDefault: null
            });
        }
        render()
        {
            return (
            <select name="selectInput" id="selectInput" onChange={this.handleChange} value= 
                {this.selectedValue}>
             {this.state.selectDefault ? <option>{this.state.selectDefault}</option> : ''}
                {'map list or static list of options here'}
            </select>
            )
        }
    }
    

Change font size of UISegmentedControl

Here i have updated for iOS8

[[UISegmentedControl appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"STHeitiSC-Medium" size:13.0], NSFontAttributeName, nil] forState:UIControlStateNormal];

Node.js/Express.js App Only Works on Port 3000

In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www. I just changed the statement in bin/www.

How to run SQL script in MySQL?

Never is a good practice to pass the password argument directly from the command line, it is saved in the ~/.bash_history file and can be accessible from other applications.

Use this instead:

mysql -u user --host host --port 9999 database_name < /scripts/script.sql -p
Enter password:

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

if (index < 0 || index >= array.length) {
    // Don't use this index. This is out of bounds (borders, limits, whatever).
} else {
    // Yes, you can safely use this index. The index is present in the array.
    Object element = array[index];
}

See also:


Update: as per your code snippet,

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

The index is inclusive the array's length. This is out of bounds. You need to replace <= by <.

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

jQuery $.ajax(), pass success data into separate function

this is how I do it

function run_ajax(obj) {
    $.ajax({
        type:"POST",
        url: prefix,
        data: obj.pdata,
        dataType: 'json',
        error: function(data) {
            //do error stuff
        },
        success: function(data) {

            if(obj.func){
                obj.func(data); 
            }

        }
    });
}

alert_func(data){
    //do what you want with data
}

var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);

rails bundle clean

I assume you install gems into vendor/bundle? If so, why not just delete all the gems and do a clean bundle install?

Can we import XML file into another XML file?

Mads Hansen's solution is good but to succeed in reading the external file in .NET 4 took some time to figure out using hints in the comments about resolvers, ProhibitDTD and so on.

This is how it's done:

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.DtdProcessing = DtdProcessing.Parse;
        XmlUrlResolver resolver = new XmlUrlResolver();
        resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
        settings.XmlResolver = resolver;
        var reader = XmlReader.Create("logfile.xml", settings);
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        foreach (XmlElement element in doc.SelectNodes("//event"))
        {
            var ch = element.ChildNodes;
            var count = ch.Count;
        }

logfile.xml:

<?xml version="1.0"?>
<!DOCTYPE logfile [
<!ENTITY events    
 SYSTEM "events.txt">
]>
<logfile>
&events;
</logfile>

events.txt:

<event>
    <item1>item1</item1>
    <item2>item2</item2>
</event>

Open file in a relative location in Python

Try this:

from pathlib import Path

data_folder = Path("/relative/path")
file_to_open = data_folder / "file.pdf"

f = open(file_to_open)

print(f.read())

Python 3.4 introduced a new standard library for dealing with files and paths called pathlib. It works for me!

When to use extern in C++

It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.

For example:

in file1.cpp:

int global_int = 1;

in file2.cpp:

extern int global_int;
//in some function
cout << "global_int = " << global_int;

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I had a such problem too because i was using IMG tag and UL tag.

Try to apply the 'corners' plugin to elements such as $('#mydiv').corner(), $('#myspan').corner(), $('#myp').corner() but NOT for $('#img').corner()! This rule is related with adding child DIVs into specified element for emulation round-corner effect. As we know IMG element couldn't have any child elements.

I've solved this by wrapping a needed element within the div and changing IMG to DIV with background: CSS property.

Good luck!

Is there shorthand for returning a default value if None in Python?

You've got the ternary syntax x if x else '' - is that what you're after?

How to select the first row of each group?

Here you can do like this -

   val data = df.groupBy("Hour").agg(first("Hour").as("_1"),first("Category").as("Category"),first("TotalValue").as("TotalValue")).drop("Hour")

data.withColumnRenamed("_1","Hour").show

Get user location by IP address

I have tried using http://ipinfo.io and this JSON API works perfectly. First, you need to add the below mentioned namespaces:

using System.Linq;
using System.Web; 
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Xml;
using System.Collections.Specialized;

For localhost it will give dummy data as AU. You can try hardcoding your IP and get results:

namespace WebApplication4
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
         {

          string VisitorsIPAddr = string.Empty;
          //Users IP Address.                
          if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
          {
              //To get the IP address of the machine and not the proxy
              VisitorsIPAddr =   HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
          }
          else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
          {
              VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;`enter code here`
          }

          string res = "http://ipinfo.io/" + VisitorsIPAddr + "/city";
          string ipResponse = IPRequestHelper(res);

        }

        public string IPRequestHelper(string url)
        {

            string checkURL = url;
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
            string responseRead = responseStream.ReadToEnd();
            responseRead = responseRead.Replace("\n", String.Empty);
            responseStream.Close();
            responseStream.Dispose();
            return responseRead;
        }


    }
}

How to use relative/absolute paths in css URLs?

Personally, I would fix this in the .htaccess file. You should have access to that.

Define your CSS URL as such:

url(/image_dir/image.png);

In your .htacess file, put:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/$1

or

RewriteRule ^image_dir/(.*) images/$1

depending on the site.

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

What about this for a catch all...

if (string.IsNullOrEmpty(x.Trim())
{
}

This will trim all the spaces if they are there avoiding the performance penalty of IsWhiteSpace, which will enable the string to meet the "empty" condition if its not null.

I also think this is clearer and its generally good practise to trim strings anyway especially if you are putting them into a database or something.

PHP pass variable to include

I know this is an old question, but stumbled upon it now and saw nobody mentioned this. so writing it.

The Option one if tweaked like this, it should also work.

The Original

Option One

In the first file:

global $variable; 
$variable = "apple"; 
include('second.php'); 

In the second file:

echo $variable;

TWEAK

In the first file:

$variable = "apple"; 
include('second.php');

In the second file:

global $variable;
echo $variable;

Find where python is installed (if it isn't default dir)

On windows search python,then right click and click on "Open file location".That's how I did

Clicking HTML 5 Video element to play, pause video, breaks play button

How about this one

<video class="play-video" muted onclick="this.paused?this.play():this.pause();">
   <source src="" type="video/mp4">
</video>

Adding a new value to an existing ENUM Type

Can't add a comment to the appropriate place, but ALTER TABLE foo ALTER COLUMN bar TYPE new_enum_type USING bar::text::new_enum_type with a default on the column failed. I had to:

ALTER table ALTER COLUMN bar DROP DEFAULT;

and then it worked.