Programs & Examples On #Unify

How to pass boolean values to a PowerShell script from a command prompt

This is an older question, but there is actually an answer to this in the PowerShell documentation. I had the same problem, and for once RTFM actually solved it. Almost.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe

Documentation for the -File parameter states that "In rare cases, you might need to provide a Boolean value for a switch parameter. To provide a Boolean value for a switch parameter in the value of the File parameter, enclose the parameter name and value in curly braces, such as the following: -File .\Get-Script.ps1 {-All:$False}"

I had to write it like this:

PowerShell.Exe -File MyFile.ps1 {-SomeBoolParameter:False}

So no '$' before the true/false statement, and that worked for me, on PowerShell 4.0

Finding duplicate rows in SQL Server

Try

SELECT orgName, id, count(*) as dupes
FROM organizations
GROUP BY orgName, id
HAVING count(*) > 1;

Pass Array Parameter in SqlCommand

Use .AddWithValue(), So:

sqlComm.Parameters.AddWithValue("@Age", sb.ToString().TrimEnd(','));

Alternatively, you could use this:

sqlComm.Parameters.Add(
    new SqlParameter("@Age", sb.ToString().TrimEnd(',')) { SqlDbType = SqlDbType. NVarChar }
    );

Your total code sample will look at follows then:

string sqlCommand = "SELECT * from TableA WHERE Age IN (@Age)";
SqlConnection sqlCon = new SqlConnection(connectString);
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = sqlCon;
sqlComm.CommandType = System.Data.CommandType.Text;
sqlComm.CommandText = sqlCommand;
sqlComm.CommandTimeout = 300;

StringBuilder sb = new StringBuilder();
foreach (ListItem item in ddlAge.Items)
{
     if (item.Selected)
     {
         sb.Append(item.Text + ",");
     }
}

sqlComm.Parameters.AddWithValue("@Age", sb.ToString().TrimEnd(','));

// OR

// sqlComm.Parameters.Add(new SqlParameter("@Age", sb.ToString().TrimEnd(',')) { SqlDbType = SqlDbType. NVarChar });

Confirm Password with jQuery Validate

jQuery('.validatedForm').validate({
        rules : {
            password : {
                minlength : 5
            },
            password_confirm : {
                minlength : 5,
                equalTo : '[name="password"]'
            }
        }

In general, you will not use id="password" like this. So, you can use [name="password"] instead of "#password"

Finding the source code for built-in Python functions?

The iPython shell makes this easy: function? will give you the documentation. function?? shows also the code. BUT this only works for pure python functions.

Then you can always download the source code for the (c)Python.

If you're interested in pythonic implementations of core functionality have a look at PyPy source.

Reading images in python

import matplotlib.pyplot as plt
image = plt.imread('images/my_image4.jpg')
plt.imshow(image)

Using 'matplotlib.pyplot.imread' is recommended by warning messages in jupyter.

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.

How to remove Firefox's dotted outline on BUTTONS as well as links?

The below worked for me in case of LINKS, thought of sharing - in case someone is interested.

a, a:visited, a:focus, a:active, a:hover{
    outline:0 none !important;
}

Cheers!

Why is null an object and what's the difference between null and undefined?

null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object". But that is actually a bug (that might even be fixed in ECMAScript 6).

The difference between null and undefined is as follows:

  • undefined: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.

    > var noValueYet;
    > console.log(noValueYet);
    undefined
    
    > function foo(x) { console.log(x) }
    > foo()
    undefined
    
    > var obj = {};
    > console.log(obj.unknownProperty)
    undefined
    

    Accessing unknown variables, however, produces an exception:

    > unknownVariable
    ReferenceError: unknownVariable is not defined
    
  • null: used by programmers to indicate “no value”, e.g. as a parameter to a function.

Examining a variable:

console.log(typeof unknownVariable === "undefined"); // true

var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true

var bar = null;
console.log(bar === null); // true

As a general rule, you should always use === and never == in JavaScript (== performs all kinds of conversions that can produce unexpected results). The check x == null is an edge case, because it works for both null and undefined:

> null == null
true
> undefined == null
true

A common way of checking whether a variable has a value is to convert it to boolean and see whether it is true. That conversion is performed by the if statement and the boolean operator ! (“not”).

function foo(param) {
    if (param) {
        // ...
    }
}
function foo(param) {
    if (! param) param = "abc";
}
function foo(param) {
    // || returns first operand that can't be converted to false
    param = param || "abc";
}

Drawback of this approach: All of the following values evaluate to false, so you have to be careful (e.g., the above checks can’t distinguish between undefined and 0).

  • undefined, null
  • Booleans: false
  • Numbers: +0, -0, NaN
  • Strings: ""

You can test the conversion to boolean by using Boolean as a function (normally it is a constructor, to be used with new):

> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

What is the best way to ensure only one instance of a Bash script is running?

Ubuntu/Debian distros have the start-stop-daemon tool which is for the same purpose you describe. See also /etc/init.d/skeleton to see how it is used in writing start/stop scripts.

-- Noah

How to set a timer in android

For timing operation you should use Handler.

If you need to run a background service the AlarmManager is the way to go.

Matplotlib 2 Subplots, 1 Colorbar

Just place the colorbar in its own axis and use subplots_adjust to make room for it.

As a quick example:

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax)

plt.show()

enter image description here

Note that the color range will be set by the last image plotted (that gave rise to im) even if the range of values is set by vmin and vmax. If another plot has, for example, a higher max value, points with higher values than the max of im will show in uniform color.

Immutable vs Mutable types

What? Floats are immutable? But can't I do

x = 5.0
x += 7.0
print x # 12.0

Doesn't that "mut" x?

Well you agree strings are immutable right? But you can do the same thing.

s = 'foo'
s += 'bar'
print s # foobar

The value of the variable changes, but it changes by changing what the variable refers to. A mutable type can change that way, and it can also change "in place".

Here is the difference.

x = something # immutable type
print x
func(x)
print x # prints the same thing

x = something # mutable type
print x
func(x)
print x # might print something different

x = something # immutable type
y = x
print x
# some statement that operates on y
print x # prints the same thing

x = something # mutable type
y = x
print x
# some statement that operates on y
print x # might print something different

Concrete examples

x = 'foo'
y = x
print x # foo
y += 'bar'
print x # foo

x = [1, 2, 3]
y = x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]

def func(val):
    val += 'bar'

x = 'foo'
print x # foo
func(x)
print x # foo

def func(val):
    val += [3, 2, 1]

x = [1, 2, 3]
print x # [1, 2, 3]
func(x)
print x # [1, 2, 3, 3, 2, 1]

How can I set a custom date time format in Oracle SQL Developer?

When i copied the date format for timestamp and used that for date, it did not work. But changing the date format to this (DD-MON-YY HH12:MI:SS AM) worked for me.

The change has to be made in Tools->Preferences-> search for NLS

What is setBounds and how do I use it?

There is an answer by @hexafraction , He had specified the x and y to be top right corner which is wrong, those are top left corner .

I have also provided the source please check it.

public void setBounds(int x,
             int y,
             int width,
             int height)

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. This method changes layout-related information, and therefore, invalidates the component hierarchy.

Parameters:

x - the new x-coordinate of this component

y - the new y-coordinate of this component

width - the new width of this component

height - the new height of this component

source:- setBounds

How many significant digits do floats and doubles have in java?

Floating point numbers are encoded using an exponential form, that is something like m * b ^ e, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.

Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333) which do not have a finite presentation in decimal but do have one in binary and vice versa.

Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1 yields value, since value + 1 can not be encoded using m * b ^ e, where m, b and e are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.

Because of this there is no precision of exactly n digits like with fixed point numbers, since not every number with n decimal digits does have a IEEE encoding.

There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.

How do I check if a variable exists?

To check the existence of a local variable:

if 'myVar' in locals():
  # myVar exists.

To check the existence of a global variable:

if 'myVar' in globals():
  # myVar exists.

To check if an object has an attribute:

if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.

Only allow specific characters in textbox

For your validation event IMO the easiest method would be to use a character array to validate textbox characters against. True - iterating and validating isn't particularly efficient, but it is straightforward.

Alternately, use a regular expression of your whitelist characters against the input string. Your events are availalbe at MSDN here: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

You want to follow the same pattern as before:

for (Type curInstance: CollectionOf<Type>) {
  // use currInstance
}

In this case it would be:

for (Bullet bullet : gunList.get(2).getBullet()) {
   System.out.println(bullet);
}

ssh script returns 255 error

SSH Very critical issue on Production. SSH-debug1: Exit status 255

I was working with Live Server and lots stuff stuck. I try many things to fix but exact issue of 255 don't figure out.

Even I had resolved issue 100%

Replace my sshd_config file from similar other my debian server

[email protected]:~# cp sshd_config sshd_config.snippetbucket.com.bkp #keep my backup file

[email protected]:~# echo "" > sshd_config

[email protected]:~# nano sshd_config #replaced all content with other exact same server

[email protected]:~# sudo service ssh restart #normally restart server

That's 100% resolve my issue immediate.

#SnippetBucket-Tip: Always take backup of ssh related files, which help on quick restoration.

Note: After apply given changes you need to exit rescue mode and reboot your vps / dedicated server normally, than your ssh connection works.

During rescue mode ssh don't allow user to login as normally. only rescue ssh related login and password works.

NumPy first and last element from array

I ended here, because I googled for "python first and last element of array", and found everything else but this. So here's the answer to the title question:

a = [1,2,3]
a[0] # first element (returns 1)
a[-1] # last element (returns 3)

How do I conditionally add attributes to React components?

Here is an example of using Bootstrap's Button via React-Bootstrap (version 0.32.4):

var condition = true;

return (
  <Button {...(condition ? {bsStyle: 'success'} : {})} />
);

Depending on the condition, either {bsStyle: 'success'} or {} will be returned. The spread operator will then spread the properties of the returned object to Button component. In the falsy case, since no properties exist on the returned object, nothing will be passed to the component.


An alternative way based on Andy Polhill's comment:

var condition = true;

return (
  <Button bsStyle={condition ? 'success' : undefined} />
);

The only small difference is that in the second example the inner component <Button/>'s props object will have a key bsStyle with a value of undefined.

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

Using a Loop to add objects to a list(python)

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

Common Header / Footer with static HTML

The most practical way is to use Server Side Include. It's very easy to implement and saves tons of work when you have more than a couple pages.

Convert XML to JSON (and back) using Javascript

In 6 simple ES6 lines:

xml2json = xml => {                                                                                                                                                     
  var el = xml.nodeType === 9 ? xml.documentElement : xml                                                                                                               
  var h  = {name: el.nodeName}                                                                                                                                          
  h.content    = Array.from(el.childNodes || []).filter(e => e.nodeType === 3).map(e => e.textContent).join('').trim()                                                  
  h.attributes = Array.from(el.attributes || []).filter(a => a).reduce((h, a) => { h[a.name] = a.value; return h }, {})                                                 
  h.children   = Array.from(el.childNodes || []).filter(e => e.nodeType === 1).map(c => h[c.nodeName] = xml2json(c))                                                    
  return h                                                                                                                                                              
}  

Test with echo "xml2json_example()" | node -r xml2json.es6 with source at https://github.com/brauliobo/biochemical-db/blob/master/lib/xml2json.es6

Sending mail attachment using Java

To send html file I have used below code in my project.

final String userID = "[email protected]";
final String userPass = "userpass";
final String emailTo = "[email protected]"

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userID, userPass);
            }
        });
try {

    Message message = new MimeMessage(session);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
    message.setSubject("Hello, this is a test mail..");

    Multipart multipart = new MimeMultipart();
    String fileName = "fileName";

    addAttachment(multipart, fileName);

    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText("No need to reply.");
    multipart.addBodyPart(messageBodyPart1);

    message.setContent(multipart);

    Transport.send(message);
    System.out.println("Email successfully sent to: " + emailTo);

} catch (MessagingException e) {
    e.printStackTrace();
}



private static void addAttachment(Multipart multipart, String fileName){
    DataSource source = null;
    File f = new File("filepath" +"/"+ fileName);
    if(f.exists() && !f.isDirectory()) {
        source = new FileDataSource("filepath" +"/"+ fileName);
        BodyPart messageBodyPart = new MimeBodyPart();
        try {
            messageBodyPart.setHeader("Content-Type", "text/html");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Android Studio - Auto complete and other features not working

If nothing works (like happened with me ) go to your user profile in windows at %userprofile% . You will find folders there (hidden) named with the version of the android studio you are using and prefixed with a dot.

like .AndroidStudio3.1. Just delete that .

Gaussian fit for Python

You get a horizontal straight line because it did not converge.

Better convergence is attained if the first parameter of the fitting (p0) is put as max(y), 5 in the example, instead of 1.

How to add a Browse To File dialog to a VB.NET application

You're looking for the OpenFileDialog class.

For example:

Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
    Using dialog As New OpenFileDialog
        If dialog.ShowDialog() <> DialogResult.OK Then Return
        File.Copy(dialog.FileName, newPath)
    End Using
End Sub

How to listen for changes to a MongoDB collection?

MongoDB version 3.6 now includes change streams which is essentially an API on top of the OpLog allowing for trigger/notification-like use cases.

Here is a link to a Java example: http://mongodb.github.io/mongo-java-driver/3.6/driver/tutorials/change-streams/

A NodeJS example might look something like:

 var MongoClient = require('mongodb').MongoClient;
    MongoClient.connect("mongodb://localhost:22000/MyStore?readConcern=majority")
     .then(function(client){
       let db = client.db('MyStore')

       let change_streams = db.collection('products').watch()
          change_streams.on('change', function(change){
            console.log(JSON.stringify(change));
          });
      });

How can I concatenate a string within a loop in JSTL/JSP?

Perhaps this will work?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" />
</c:forEach>

Setting maxlength of textbox with JavaScript or jQuery

without jQuery you can use

document.getElementById('text_input').setAttribute('maxlength',200);

How to include external Python code to use in other files?

You will need to import the other file as a module like this:

import Math

If you don't want to prefix your Calculate function with the module name then do this:

from Math import Calculate

If you want to import all members of a module then do this:

from Math import *

Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

To the power of in C?

#include <math.h>


printf ("%d", (int) pow (3, 4));

Spring-boot default profile for integration tests

Another way to do this is to define a base (abstract) test class that your actual test classes will extend :

@RunWith(SpringRunner.class)
@SpringBootTest()
@ActiveProfiles("staging")
public abstract class BaseIntegrationTest {
}

Concrete test :

public class SampleSearchServiceTest extends BaseIntegrationTest{

    @Inject
    private SampleSearchService service;

    @Test
    public void shouldInjectService(){
        assertThat(this.service).isNotNull();
    }
} 

This allows you to extract more than just the @ActiveProfiles annotation. You could also imagine more specialised base classes for different kinds of integration tests, e.g. data access layer vs service layer, or for functional specialties (common @Before or @After methods etc).

Best way in asp.net to force https for an entire site?

If you are unable to set this up in IIS for whatever reason, I'd make an HTTP module that does the redirect for you:

using System;
using System.Web;

namespace HttpsOnly
{
    /// <summary>
    /// Redirects the Request to HTTPS if it comes in on an insecure channel.
    /// </summary>
    public class HttpsOnlyModule : IHttpModule
    {
        public void Init(HttpApplication app)
        {
            // Note we cannot trust IsSecureConnection when 
            // in a webfarm, because usually only the load balancer 
            // will come in on a secure port the request will be then 
            // internally redirected to local machine on a specified port.

            // Move this to a config file, if your behind a farm, 
            // set this to the local port used internally.
            int specialPort = 443;

            if (!app.Context.Request.IsSecureConnection 
               || app.Context.Request.Url.Port != specialPort)
            {
               app.Context.Response.Redirect("https://" 
                  + app.Context.Request.ServerVariables["HTTP_HOST"] 
                  + app.Context.Request.RawUrl);    
            }
        }

        public void Dispose()
        {
            // Needed for IHttpModule
        }
    }
}

Then just compile it to a DLL, add it as a reference to your project and place this in web.config:

 <httpModules>
      <add name="HttpsOnlyModule" type="HttpsOnly.HttpsOnlyModule, HttpsOnly" />
 </httpModules>

Format an Excel column (or cell) as Text in C#?

Before your write to Excel need to change the format:

xlApp = New Excel.Application
xlWorkSheet = xlWorkBook.Sheets("Sheet1")

Dim cells As Excel.Range = xlWorkSheet.Cells

'set each cell's format to Text
cells.NumberFormat = "@"

'reset horizontal alignment to the right
cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight

Strange PostgreSQL "value too long for type character varying(500)"

By specifying the column as VARCHAR(500) you've set an explicit 500 character limit. You might not have done this yourself explicitly, but Django has done it for you somewhere. Telling you where is hard when you haven't shown your model, the full error text, or the query that produced the error.

If you don't want one, use an unqualified VARCHAR, or use the TEXT type.

varchar and text are limited in length only by the system limits on column size - about 1GB - and by your memory. However, adding a length-qualifier to varchar sets a smaller limit manually. All of the following are largely equivalent:

column_name VARCHAR(500)

column_name VARCHAR CHECK (length(column_name) <= 500) 

column_name TEXT CHECK (length(column_name) <= 500) 

The only differences are in how database metadata is reported and which SQLSTATE is raised when the constraint is violated.

The length constraint is not generally obeyed in prepared statement parameters, function calls, etc, as shown:

regress=> \x
Expanded display is on.
regress=> PREPARE t2(varchar(500)) AS SELECT $1;
PREPARE
regress=> EXECUTE t2( repeat('x',601) );
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
?column? | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

and in explicit casts it result in truncation:

regress=> SELECT repeat('x',501)::varchar(1);
-[ RECORD 1 ]
repeat | x

so I think you are using a VARCHAR(500) column, and you're looking at the wrong table or wrong instance of the database.

Calling a function from a string in C#

A slight tangent -- if you want to parse and evaluate an entire expression string which contains (nested!) functions, consider NCalc (http://ncalc.codeplex.com/ and nuget)

Ex. slightly modified from the project documentation:

// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);

// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
        if (name == "MyFunction")
            args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
    };

// confirm it worked
Debug.Assert(19 == e.Evaluate());

And within the EvaluateFunction delegate you would call your existing function.

How can I create an object based on an interface file definition in TypeScript?

Here is another approach:

You can simply create an ESLint friendly object like this

const modal: IModal = {} as IModal;

Or a default instance based on the interface and with sensible defaults, if any

const defaultModal: IModal = {
    content: "",
    form: "",
    href: "",
    $form: {} as JQuery,
    $message: {} as JQuery,
    $modal: {} as JQuery,
    $submits: {} as JQuery
};

Then variations of the default instance simply by overriding some properties

const confirmationModal: IModal = {
    ...defaultModal,     // all properties/values from defaultModal
    form: "confirmForm"  // override form only
}

jQuery - multiple $(document).ready ...?

It is important to note that each jQuery() call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.

This applies regardless of syntax. You can use jQuery(), jQuery(function() {}), $(document).ready(), whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.

This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.

Show spinner GIF during an $http request in AngularJS?

https://github.com/wongatech/angular-http-loader is a good project for this.

Example here http://wongatech.github.io/angular-http-loader/

The code below shows a template example/loader.tpl.html when a request is happening.

<div ng-http-loader template="example/loader.tpl.html"></div>

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

iterating through json object javascript

My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.

{
"dialog":
{
    "trunks":[
    {
        "trunk_id" : "1",
        "message": "This is just a JSON Test"
    },
    {
        "trunk_id" : "2",
        "message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
    }
    ]
}
}

At that point, I was able to do a fairly simple for loop based on the total number of objects.

var totalMessages = Object.keys(messages.dialog.trunks).length;

    for ( var i = 0; i < totalMessages; i++)
    {
        console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
    }

My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.

How to set viewport meta for iPhone that handles rotation properly?

<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">

suport all iphones, all ipads, all androids.

How do I get the position selected in a RecyclerView?

Get focused child, and use it to get position in adapter.

mRecyclerView.getChildAdapterPosition(mRecyclerView.getFocusedChild())

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');

Result:

1 second(s)

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Populate nested array in mongoose

It's is the best solution:

Car
 .find()
 .populate({
   path: 'pages.page.components'
})

How to detect idle time in JavaScript elegantly?

Similar to Iconic's solution above (with jQuery custom event)...

// use jquery-idle-detect.js script below
$(window).on('idle:start', function(){
  //start your prefetch etc here...
});

$(window).on('idle:stop', function(){
  //stop your prefetch etc here...
});

//jquery-idle-detect.js
(function($,$w){
  // expose configuration option
  // idle is triggered when no events for 2 seconds
  $.idleTimeout = 2000;

  // currently in idle state
  var idle = false;

  // handle to idle timer for detection
  var idleTimer = null;

  //start idle timer and bind events on load (not dom-ready)
  $w.on('load', function(){
    startIdleTimer();
    $w.on('focus resize mousemove keyup', startIdleTimer)
      .on('blur',idleStart) //force idle when in a different tab/window
      ;
  ]);

  function startIdleTimer() {
    clearTimeout(idleTimer); //clear prior timer

    if (idle) $w.trigger('idle:stop'); //if idle, send stop event
    idle = false; //not idle

    var timeout = ~~$.idleTimeout; // option to integer
    if (timeout <= 100) timeout = 100; // min 100ms
    if (timeout > 300000) timeout = 300000; // max 5 minutes

    idleTimer = setTimeout(idleStart, timeout); //new timer
  }

  function idleStart() {
    if (!idle) $w.trigger('idle:start');
    idle = true;
  }

}(window.jQuery, window.jQuery(window)))

Django DoesNotExist

Nice way to handle not found error in Django.

https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#get-object-or-404

from django.shortcuts import get_object_or_404

def get_data(request):
    obj = get_object_or_404(Model, pk=1)

Set the location in iPhone Simulator

  1. Run project in iPhone Simulator
  2. Create in TextEdit file following file, call it MyOffice for example. Make extension as .gpx enter image description here

    <?xml version="1.0"?> <gpx version="1.0" creator="MyName"> <wpt lat="53.936166" lon="27.565370"> <name>MyOffice</name> </wpt> </gpx>

  3. Select in Xcode at the Simulate area Add GPX File to Project...enter image description here

  4. Add created file from menu to project.
  5. Now you can see your location in Simulate area:enter image description here

Multiple aggregations of the same column using pandas GroupBy.agg()

TLDR; Pandas groupby.agg has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use

df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))

           Mean       Sum
dummy                    
1      0.036901  0.369012

OR

df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')

           Mean       Sum
dummy                    
1      0.036901  0.369012

Pandas >= 0.25: Named Aggregation

Pandas has changed the behavior of GroupBy.agg in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.

From the documentation,

To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in GroupBy.agg(), known as “named aggregation”, where

  • The keywords are the output column names
  • The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.

You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>).

import pandas as pd

pd.__version__                                                                                                                            
# '0.25.0.dev0+840.g989f912ee'

# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                   'height': [9.1, 6.0, 9.5, 34.0],
                   'weight': [7.9, 7.5, 9.9, 198.0]
})

df.groupby('kind').agg(
    max_height=('height', 'max'), min_weight=('weight', 'min'),)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

Alternatively, you can use pd.NamedAgg (essentially a namedtuple) which makes things more explicit.

df.groupby('kind').agg(
    max_height=pd.NamedAgg(column='height', aggfunc='max'), 
    min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

It is even simpler for Series, just pass the aggfunc to a keyword argument.

df.groupby('kind')['height'].agg(max_height='max', min_height='min')    

      max_height  min_height
kind                        
cat          9.5         9.1
dog         34.0         6.0       

Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:

df.groupby('kind')['height'].agg(**{'max height': 'max', ...})

Pandas < 0.25

In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning:

df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed 
# in a future version

Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.

df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})

        returns          
            op1       op2
dummy                    
1      0.328953  0.032895

Or,

df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])

            op1       op2
dummy                    
1      0.328953  0.032895

Responsive font size in CSS

I've been playing around with ways to overcome this issue, and believe I have found a solution:

If you can write your application for Internet Explorer 9 (and later) and all other modern browsers that support CSS calc(), rem units, and vmin units. You can use this to achieve scalable text without media queries:

body {
  font-size: calc(0.75em + 1vmin);
}

Here it is in action: http://codepen.io/csuwldcat/pen/qOqVNO

Android button background color

This is my way to do custom Button with different color.`

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke android:width="3dp"
        android:color="#80FFFFFF" />

  <corners android:radius="25dp" />

  <gradient android:angle="270"
            android:centerColor="#90150517"
            android:endColor="#90150517"
            android:startColor="#90150517" />
</shape>

This way you set as background.

<Button android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_marginBottom="25dp"
        android:layout_centerInParent="true"
        android:background="@drawable/button"/>

How do I draw a shadow under a UIView?

I use this as part of my utils. With this we can not only set shadow but also can get a rounded corner for any UIView. Also you could set what color shadow you prefer. Normally black is preferred but sometimes, when the background is non-white you might want something else. Here's what I use -

in utils.m
+ (void)roundedLayer:(CALayer *)viewLayer 
              radius:(float)r 
              shadow:(BOOL)s
{
    [viewLayer setMasksToBounds:YES];
    [viewLayer setCornerRadius:r];        
    [viewLayer setBorderColor:[RGB(180, 180, 180) CGColor]];
    [viewLayer setBorderWidth:1.0f];
    if(s)
    {
        [viewLayer setShadowColor:[RGB(0, 0, 0) CGColor]];
        [viewLayer setShadowOffset:CGSizeMake(0, 0)];
        [viewLayer setShadowOpacity:1];
        [viewLayer setShadowRadius:2.0];
    }
    return;
}

To use this we need to call this - [utils roundedLayer:yourview.layer radius:5.0f shadow:YES];

How can I get the image url in a Wordpress theme?

I had to use Stylesheet directory to work for me.

<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/image.png">

Split comma-separated values

A way to do this without Linq & Lambdas

string source = "a,b, b, c";
string[] items = source.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

"Rate This App"-link in Google Play store app on the phone

Play Store Rating

 btn_rate_us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
                Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                // To count with Play market backstack, After pressing back button,
                // to taken back to our application, we need to add following flags to intent.
                goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                        Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
                        Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                try {
                    startActivity(goToMarket);
                } catch (ActivityNotFoundException e) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
                }
            }
        });

How does Python's super() work with multiple inheritance?

Maybe there's still something that can be added, a small example with Django rest_framework, and decorators. This provides an answer to the implicit question: "why would I want this anyway?"

As said: we're with Django rest_framework, and we're using generic views, and for each type of objects in our database we find ourselves with one view class providing GET and POST for lists of objects, and an other view class providing GET, PUT, and DELETE for individual objects.

Now the POST, PUT, and DELETE we want to decorate with Django's login_required. Notice how this touches both classes, but not all methods in either class.

A solution could go through multiple inheritance.

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

class LoginToPost:
    @method_decorator(login_required)
    def post(self, arg, *args, **kwargs):
        super().post(arg, *args, **kwargs)

Likewise for the other methods.

In the inheritance list of my concrete classes, I would add my LoginToPost before ListCreateAPIView and LoginToPutOrDelete before RetrieveUpdateDestroyAPIView. My concrete classes' get would stay undecorated.

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

TensorFlow: "Attempting to use uninitialized value" in variable initialization

There is another the error happening which related to the order when calling initializing global variables. I've had the sample of code has similar error FailedPreconditionError (see above for traceback): Attempting to use uninitialized value W

def linear(X, n_input, n_output, activation = None):
    W = tf.Variable(tf.random_normal([n_input, n_output], stddev=0.1), name='W')
    b = tf.Variable(tf.constant(0, dtype=tf.float32, shape=[n_output]), name='b')
    if activation != None:
        h = tf.nn.tanh(tf.add(tf.matmul(X, W),b), name='h')
    else:
        h = tf.add(tf.matmul(X, W),b, name='h')
    return h

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as sess:
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    # But W hasn't in the graph yet so not know to initialize 
    # EVAL then error
    print(linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3).eval())

You should change to following

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as 
    # NOT RUNNING BUT ASSIGN
    l = linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3)
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    print([op.name for op in g.get_operations()])
    # ONLY EVAL AFTER INIT
    print(l.eval(session=sess))

accepting HTTPS connections with self-signed certificates

Google recommends the usage of Android Volley for HTTP/HTTPS connections, since that HttpClient is deprecated. So, you know the right choice :).

And also, NEVER NUKE SSL Certificates (NEVER!!!).

To nuke SSL Certificates, is totally against the purpose of SSL, which is promoting security. There's no sense of using SSL, if you're planning to bomb all SSL certificates that comes. A better solution would be creating a custom TrustManager on your App + using Android Volley for HTTP/HTTPS connections.

Here's a Gist which I created, with a basic LoginApp, performing HTTPS connections, using a Self-Signed Certificate on the server-side, accepted on the App.

Here's also another Gist that may help, for creating Self-Signed SSL Certificates for setting up on your Server and also using the certificate on your App. Very important: you must copy the .crt file which was generated by the script above, to the "raw" directory from your Android project.

How to directly move camera to current location in Google Maps Android API v2?

The above answer is not according to what Google Doc Referred for Location Tracking in Google api v2.

I just followed the official tutorial and ended up with this class that is fetching the current location and centring the map on it as soon as i get that.

you can extend this class to have LocationReciever to have periodic Location Update. I just executed this code on api level 7

http://developer.android.com/training/location/retrieve-current.html

Here it goes.

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;


public class MainActivity extends FragmentActivity implements 
    GooglePlayServicesClient.ConnectionCallbacks, 
    GooglePlayServicesClient.OnConnectionFailedListener{

private SupportMapFragment mapFragment;
private GoogleMap map;
private LocationClient mLocationClient;
/*
 * Define a request code to send to Google Play services
 * This code is returned in Activity.onActivityResult
 */
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {

    // Global field to contain the error dialog
    private Dialog mDialog;

    // Default constructor. Sets the dialog field to null
    public ErrorDialogFragment() {
        super();
        mDialog = null;
    }

    // Set the dialog to display
    public void setDialog(Dialog dialog) {
        mDialog = dialog;
    }

    // Return a Dialog to the DialogFragment.
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return mDialog;
    }
}

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

    mLocationClient = new LocationClient(this, this, this);

    mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
    map = mapFragment.getMap();

    map.setMyLocationEnabled(true);

}

/*
 * Called when the Activity becomes visible.
 */
@Override
protected void onStart() {
    super.onStart();
    // Connect the client.
    if(isGooglePlayServicesAvailable()){
        mLocationClient.connect();
    }

}

/*
 * Called when the Activity is no longer visible.
 */
@Override
protected void onStop() {
    // Disconnecting the client invalidates it.
    mLocationClient.disconnect();
    super.onStop();
}

/*
 * Handle results returned to the FragmentActivity
 * by Google Play services
 */
@Override
protected void onActivityResult(
                int requestCode, int resultCode, Intent data) {
    // Decide what to do based on the original request code
    switch (requestCode) {

        case CONNECTION_FAILURE_RESOLUTION_REQUEST:
            /*
             * If the result code is Activity.RESULT_OK, try
             * to connect again
             */
            switch (resultCode) {
                case Activity.RESULT_OK:
                    mLocationClient.connect();
                    break;
            }

    }
}

private boolean isGooglePlayServicesAvailable() {
    // Check that Google Play services is available
    int resultCode =  GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {
        // In debug mode, log the status
        Log.d("Location Updates", "Google Play services is available.");
        return true;
    } else {
        // Get the error dialog from Google Play services
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( resultCode,
                                                                                                              this,
                                                                                                              CONNECTION_FAILURE_RESOLUTION_REQUEST);

        // If Google Play services can provide an error dialog
        if (errorDialog != null) {
            // Create a new DialogFragment for the error dialog
            ErrorDialogFragment errorFragment = new ErrorDialogFragment();
            errorFragment.setDialog(errorDialog);
            errorFragment.show(getSupportFragmentManager(), "Location Updates");
        }

        return false;
    }
}

/*
 * Called by Location Services when the request to connect the
 * client finishes successfully. At this point, you can
 * request the current location or start periodic updates
 */
@Override
public void onConnected(Bundle dataBundle) {
    // Display the connection status
    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    Location location = mLocationClient.getLastLocation();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
    map.animateCamera(cameraUpdate);
}

/*
 * Called by Location Services if the connection to the
 * location client drops because of an error.
 */
@Override
public void onDisconnected() {
    // Display the connection status
    Toast.makeText(this, "Disconnected. Please re-connect.",
            Toast.LENGTH_SHORT).show();
}

/*
 * Called by Location Services if the attempt to
 * Location Services fails.
 */
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(
                    this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
            /*
            * Thrown if Google Play services canceled the original
            * PendingIntent
            */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
       Toast.makeText(getApplicationContext(), "Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
    }
}

}

MySQL: How to reset or change the MySQL root password?

Change the MySQL root password.

This method exposes the password to the command-line history, these commands should be run as root.

  1. Login through mysql command line tool:

    mysql -uroot -poldpassword
    
  2. Run this command:

    SET PASSWORD FOR root@'localhost' = PASSWORD('newpassword');
    

or

  1. Run this command, which sets a password for the current user ('root' for this case) :

    SET PASSWORD = PASSWORD('newpassword');

JSON.net: how to deserialize without using the default constructor?

The default behaviour of Newtonsoft.Json is going to find the public constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected or internal so that Newtonsoft.Json will pick your desired public constructor.

Admittedly, this solution is rather very limited to specific cases.

internal Result() { }

public Result(int? code, string format, Dictionary<string, string> details = null)
{
    Code = code ?? ERROR_CODE;
    Format = format;

    if (details == null)
        Details = new Dictionary<string, string>();
    else
        Details = details;
}

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

The Chrome Webstore has an extension that adds the 'Access-Control-Allow-Origin' header for you when there is an asynchronous call in the page that tries to access a different host than yours.

The name of the extension is: "Allow-Control-Allow-Origin: *" and this is the link: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Adding days to a date in Java

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 5); // Adding 5 days
String output = sdf.format(c.getTime());
System.out.println(output);

How to have a default option in Angular.js select box

You can simply use ng-init like this

<select ng-init="somethingHere = options[0]" 
        ng-model="somethingHere" 
        ng-options="option.name for option in options">
</select>

Why is an OPTIONS request sent and can I disable it?

Yes it's possible to avoid options request. Options request is a preflight request when you send (post) any data to another domain. It's a browser security issue. But we can use another technology: iframe transport layer. I strongly recommend you forget about any CORS configuration and use readymade solution and it will work anywhere.

Take a look here: https://github.com/jpillora/xdomain

And working example: http://jpillora.com/xdomain/

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

If somehow, the problem has to do with multiple insertions to your database "on refresh". Check my answer here Unset post variables after form submission. It should help.

Getting the array length of a 2D array in Java

Try this following program for 2d array in java:

public class ArrayTwo2 {
    public static void main(String[] args) throws  IOException,NumberFormatException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int[][] a;
        int sum=0;
        a=new int[3][2];
        System.out.println("Enter array with 5 elements");
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            a[i][j]=Integer.parseInt(br.readLine());
            }
        }
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            System.out.print(a[i][j]+"  ");
            sum=sum+a[i][j];
            }
        System.out.println();   
        //System.out.println("Array Sum: "+sum);
        sum=0;
        }
    }
}

How to send PUT, DELETE HTTP request in HttpURLConnection?

To perform an HTTP PUT:

URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
    httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();

To perform an HTTP DELETE:

URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
    "Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();

What are Transient and Volatile Modifiers?

Transient :

First need to know where it needed how it bridge the gap.

1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

2) Transient keyword cannot be used along with static keyword.

3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

How do I get the day of week given a date?

If you're not solely reliant on the datetime module, calendar might be a better alternative. This, for example, will provide you with the day codes:

calendar.weekday(2017,12,22);

And this will give you the day itself:

days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
days[calendar.weekday(2017,12,22)]

Or in the style of python, as a one liner:

["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][calendar.weekday(2017,12,22)]

Programmatically switching between tabs within Swift

Swift 3

You can add this code to the default view controller (index 0) in your tabBarController:

    override func viewWillAppear(_ animated: Bool) {
        _ = self.tabBarController?.selectedIndex = 1
    }

Upon load, this would automatically move the tab to the second item in the list, but also allow the user to manually go back to that view at any time.

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

Using extern is only of relevance when the program you're building consists of multiple source files linked together, where some of the variables defined, for example, in source file file1.c need to be referenced in other source files, such as file2.c.

It is important to understand the difference between defining a variable and declaring a variable:

  • A variable is declared when the compiler is informed that a variable exists (and this is its type); it does not allocate the storage for the variable at that point.

  • A variable is defined when the compiler allocates the storage for the variable.

You may declare a variable multiple times (though once is sufficient); you may only define it once within a given scope. A variable definition is also a declaration, but not all variable declarations are definitions.

Best way to declare and define global variables

The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable.

The header is included by the one source file that defines the variable and by all the source files that reference the variable. For each program, one source file (and only one source file) defines the variable. Similarly, one header file (and only one header file) should declare the variable. The header file is crucial; it enables cross-checking between independent TUs (translation units — think source files) and ensures consistency.

Although there are other ways of doing it, this method is simple and reliable. It is demonstrated by file3.h, file1.c and file2.c:

file3.h

extern int global_variable;  /* Declaration of the variable */

file1.c

#include "file3.h"  /* Declaration made available here */
#include "prog1.h"  /* Function declarations */

/* Variable defined here */
int global_variable = 37;    /* Definition checked against declaration */

int increment(void) { return global_variable++; }

file2.c

#include "file3.h"
#include "prog1.h"
#include <stdio.h>

void use_it(void)
{
    printf("Global variable: %d\n", global_variable++);
}

That's the best way to declare and define global variables.


The next two files complete the source for prog1:

The complete programs shown use functions, so function declarations have crept in. Both C99 and C11 require functions to be declared or defined before they are used (whereas C90 did not, for good reasons). I use the keyword extern in front of function declarations in headers for consistency — to match the extern in front of variable declarations in headers. Many people prefer not to use extern in front of function declarations; the compiler doesn't care — and ultimately, neither do I as long as you're consistent, at least within a source file.

prog1.h

extern void use_it(void);
extern int increment(void);

prog1.c

#include "file3.h"
#include "prog1.h"
#include <stdio.h>

int main(void)
{
    use_it();
    global_variable += 19;
    use_it();
    printf("Increment: %d\n", increment());
    return 0;
}
  • prog1 uses prog1.c, file1.c, file2.c, file3.h and prog1.h.

The file prog1.mk is a makefile for prog1 only. It will work with most versions of make produced since about the turn of the millennium. It is not tied specifically to GNU Make.

prog1.mk

# Minimal makefile for prog1

PROGRAM = prog1
FILES.c = prog1.c file1.c file2.c
FILES.h = prog1.h file3.h
FILES.o = ${FILES.c:.c=.o}

CC      = gcc
SFLAGS  = -std=c11
GFLAGS  = -g
OFLAGS  = -O3
WFLAG1  = -Wall
WFLAG2  = -Wextra
WFLAG3  = -Werror
WFLAG4  = -Wstrict-prototypes
WFLAG5  = -Wmissing-prototypes
WFLAGS  = ${WFLAG1} ${WFLAG2} ${WFLAG3} ${WFLAG4} ${WFLAG5}
UFLAGS  = # Set on command line only

CFLAGS  = ${SFLAGS} ${GFLAGS} ${OFLAGS} ${WFLAGS} ${UFLAGS}
LDFLAGS =
LDLIBS  =

all:    ${PROGRAM}

${PROGRAM}: ${FILES.o}
    ${CC} -o $@ ${CFLAGS} ${FILES.o} ${LDFLAGS} ${LDLIBS}

prog1.o: ${FILES.h}
file1.o: ${FILES.h}
file2.o: ${FILES.h}

# If it exists, prog1.dSYM is a directory on macOS
DEBRIS = a.out core *~ *.dSYM
RM_FR  = rm -fr

clean:
    ${RM_FR} ${FILES.o} ${PROGRAM} ${DEBRIS}


Guidelines

Rules to be broken by experts only, and only with good reason:

  • A header file only contains extern declarations of variables — never static or unqualified variable definitions.

  • For any given variable, only one header file declares it (SPOT — Single Point of Truth).

  • A source file never contains extern declarations of variables — source files always include the (sole) header that declares them.

  • For any given variable, exactly one source file defines the variable, preferably initializing it too. (Although there is no need to initialize explicitly to zero, it does no harm and can do some good, because there can be only one initialized definition of a particular global variable in a program).

  • The source file that defines the variable also includes the header to ensure that the definition and the declaration are consistent.

  • A function should never need to declare a variable using extern.

  • Avoid global variables whenever possible — use functions instead.

The source code and text of this answer are available in my SOQ (Stack Overflow Questions) repository on GitHub in the src/so-0143-3204 sub-directory.

If you're not an experienced C programmer, you could (and perhaps should) stop reading here.

Not so good way to define global variables

With some (indeed, many) C compilers, you can get away with what's called a 'common' definition of a variable too. 'Common', here, refers to a technique used in Fortran for sharing variables between source files, using a (possibly named) COMMON block. What happens here is that each of a number of files provides a tentative definition of the variable. As long as no more than one file provides an initialized definition, then the various files end up sharing a common single definition of the variable:

file10.c

#include "prog2.h"

long l;   /* Do not do this in portable code */

void inc(void) { l++; }

file11.c

#include "prog2.h"

long l;   /* Do not do this in portable code */

void dec(void) { l--; }

file12.c

#include "prog2.h"
#include <stdio.h>

long l = 9;   /* Do not do this in portable code */

void put(void) { printf("l = %ld\n", l); }

This technique does not conform to the letter of the C standard and the 'one definition rule' — it is officially undefined behaviour:

J.2 Undefined behavior

An identifier with external linkage is used, but in the program there does not exist exactly one external definition for the identifier, or the identifier is not used and there exist multiple external definitions for the identifier (6.9).

§6.9 External definitions ¶5

An external definition is an external declaration that is also a definition of a function (other than an inline definition) or an object. If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof or _Alignof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier; otherwise, there shall be no more than one.161)

161) Thus, if an identifier declared with external linkage is not used in an expression, there need be no external definition for it.

However, the C standard also lists it in informative Annex J as one of the Common extensions.

J.5.11 Multiple external definitions

There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).

Because this technique is not always supported, it is best to avoid using it, especially if your code needs to be portable. Using this technique, you can also end up with unintentional type punning.

If one of the files above declared l as a double instead of as a long, C's type-unsafe linkers probably would not spot the mismatch. If you're on a machine with 64-bit long and double, you'd not even get a warning; on a machine with 32-bit long and 64-bit double, you'd probably get a warning about the different sizes — the linker would use the largest size, exactly as a Fortran program would take the largest size of any common blocks.

Note that GCC 10.1.0, which was released on 2020-05-07, changes the default compilation options to use -fno-common, which means that by default, the code above no longer links unless you override the default with -fcommon (or use attributes, etc — see the link).


The next two files complete the source for prog2:

prog2.h

extern void dec(void);
extern void put(void);
extern void inc(void);

prog2.c

#include "prog2.h"
#include <stdio.h>

int main(void)
{
    inc();
    put();
    dec();
    put();
    dec();
    put();
}
  • prog2 uses prog2.c, file10.c, file11.c, file12.c, prog2.h.

Warning

As noted in comments here, and as stated in my answer to a similar question, using multiple definitions for a global variable leads to undefined behaviour (J.2; §6.9), which is the standard's way of saying "anything could happen". One of the things that can happen is that the program behaves as you expect; and J.5.11 says, approximately, "you might be lucky more often than you deserve". But a program that relies on multiple definitions of an extern variable — with or without the explicit 'extern' keyword — is not a strictly conforming program and not guaranteed to work everywhere. Equivalently: it contains a bug which may or may not show itself.

Violating the guidelines

There are, of course, many ways in which these guidelines can be broken. Occasionally, there may be a good reason to break the guidelines, but such occasions are extremely unusual.

faulty_header.h

int some_var;    /* Do not do this in a header!!! */

Note 1: if the header defines the variable without the extern keyword, then each file that includes the header creates a tentative definition of the variable. As noted previously, this will often work, but the C standard does not guarantee that it will work.

broken_header.h

int some_var = 13;    /* Only one source file in a program can use this */

Note 2: if the header defines and initializes the variable, then only one source file in a given program can use the header. Since headers are primarily for sharing information, it is a bit silly to create one that can only be used once.

seldom_correct.h

static int hidden_global = 3;   /* Each source file gets its own copy  */

Note 3: if the header defines a static variable (with or without initialization), then each source file ends up with its own private version of the 'global' variable.

If the variable is actually a complex array, for example, this can lead to extreme duplication of code. It can, very occasionally, be a sensible way to achieve some effect, but that is very unusual.


Summary

Use the header technique I showed first. It works reliably and everywhere. Note, in particular, that the header declaring the global_variable is included in every file that uses it — including the one that defines it. This ensures that everything is self-consistent.

Similar concerns arise with declaring and defining functions — analogous rules apply. But the question was about variables specifically, so I've kept the answer to variables only.

End of Original Answer

If you're not an experienced C programmer, you probably should stop reading here.


Late Major Addition

Avoiding Code Duplication

One concern that is sometimes (and legitimately) raised about the 'declarations in headers, definitions in source' mechanism described here is that there are two files to be kept synchronized — the header and the source. This is usually followed up with an observation that a macro can be used so that the header serves double duty — normally declaring the variables, but when a specific macro is set before the header is included, it defines the variables instead.

Another concern can be that the variables need to be defined in each of a number of 'main programs'. This is normally a spurious concern; you can simply introduce a C source file to define the variables and link the object file produced with each of the programs.

A typical scheme works like this, using the original global variable illustrated in file3.h:

file3a.h

#ifdef DEFINE_VARIABLES
#define EXTERN /* nothing */
#else
#define EXTERN extern
#endif /* DEFINE_VARIABLES */

EXTERN int global_variable;

file1a.c

#define DEFINE_VARIABLES
#include "file3a.h"  /* Variable defined - but not initialized */
#include "prog3.h"

int increment(void) { return global_variable++; }

file2a.c

#include "file3a.h"
#include "prog3.h"
#include <stdio.h>

void use_it(void)
{
    printf("Global variable: %d\n", global_variable++);
}

The next two files complete the source for prog3:

prog3.h

extern void use_it(void);
extern int increment(void);

prog3.c

#include "file3a.h"
#include "prog3.h"
#include <stdio.h>

int main(void)
{
    use_it();
    global_variable += 19;
    use_it();
    printf("Increment: %d\n", increment());
    return 0;
}
  • prog3 uses prog3.c, file1a.c, file2a.c, file3a.h, prog3.h.

Variable initialization

The problem with this scheme as shown is that it does not provide for initialization of the global variable. With C99 or C11 and variable argument lists for macros, you could define a macro to support initialization too. (With C89 and no support for variable argument lists in macros, there is no easy way to handle arbitrarily long initializers.)

file3b.h

#ifdef DEFINE_VARIABLES
#define EXTERN                  /* nothing */
#define INITIALIZER(...)        = __VA_ARGS__
#else
#define EXTERN                  extern
#define INITIALIZER(...)        /* nothing */
#endif /* DEFINE_VARIABLES */

EXTERN int global_variable INITIALIZER(37);
EXTERN struct { int a; int b; } oddball_struct INITIALIZER({ 41, 43 });

Reverse contents of #if and #else blocks, fixing bug identified by Denis Kniazhev

file1b.c

#define DEFINE_VARIABLES
#include "file3b.h"  /* Variables now defined and initialized */
#include "prog4.h"

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }

file2b.c

#include "file3b.h"
#include "prog4.h"
#include <stdio.h>

void use_them(void)
{
    printf("Global variable: %d\n", global_variable++);
    oddball_struct.a += global_variable;
    oddball_struct.b -= global_variable / 2;
}

Clearly, the code for the oddball structure is not what you'd normally write, but it illustrates the point. The first argument to the second invocation of INITIALIZER is { 41 and the remaining argument (singular in this example) is 43 }. Without C99 or similar support for variable argument lists for macros, initializers that need to contain commas are very problematic.

Correct header file3b.h included (instead of fileba.h) per Denis Kniazhev


The next two files complete the source for prog4:

prog4.h

extern int increment(void);
extern int oddball_value(void);
extern void use_them(void);

prog4.c

#include "file3b.h"
#include "prog4.h"
#include <stdio.h>

int main(void)
{
    use_them();
    global_variable += 19;
    use_them();
    printf("Increment: %d\n", increment());
    printf("Oddball:   %d\n", oddball_value());
    return 0;
}
  • prog4 uses prog4.c, file1b.c, file2b.c, prog4.h, file3b.h.

Header Guards

Any header should be protected against reinclusion, so that type definitions (enum, struct or union types, or typedefs generally) do not cause problems. The standard technique is to wrap the body of the header in a header guard such as:

#ifndef FILE3B_H_INCLUDED
#define FILE3B_H_INCLUDED

...contents of header...

#endif /* FILE3B_H_INCLUDED */

The header might be included twice indirectly. For example, if file4b.h includes file3b.h for a type definition that isn't shown, and file1b.c needs to use both header file4b.h and file3b.h, then you have some more tricky issues to resolve. Clearly, you might revise the header list to include just file4b.h. However, you might not be aware of the internal dependencies — and the code should, ideally, continue to work.

Further, it starts to get tricky because you might include file4b.h before including file3b.h to generate the definitions, but the normal header guards on file3b.h would prevent the header being reincluded.

So, you need to include the body of file3b.h at most once for declarations, and at most once for definitions, but you might need both in a single translation unit (TU — a combination of a source file and the headers it uses).

Multiple inclusion with variable definitions

However, it can be done subject to a not too unreasonable constraint. Let's introduce a new set of file names:

  • external.h for the EXTERN macro definitions, etc.

  • file1c.h to define types (notably, struct oddball, the type of oddball_struct).

  • file2c.h to define or declare the global variables.

  • file3c.c which defines the global variables.

  • file4c.c which simply uses the global variables.

  • file5c.c which shows that you can declare and then define the global variables.

  • file6c.c which shows that you can define and then (attempt to) declare the global variables.

In these examples, file5c.c and file6c.c directly include the header file2c.h several times, but that is the simplest way to show that the mechanism works. It means that if the header was indirectly included twice, it would also be safe.

The restrictions for this to work are:

  1. The header defining or declaring the global variables may not itself define any types.

  2. Immediately before you include a header that should define variables, you define the macro DEFINE_VARIABLES.

  3. The header defining or declaring the variables has stylized contents.

external.h

/*
** This header must not contain header guards (like <assert.h> must not).
** Each time it is invoked, it redefines the macros EXTERN, INITIALIZE
** based on whether macro DEFINE_VARIABLES is currently defined.
*/
#undef EXTERN
#undef INITIALIZE

#ifdef DEFINE_VARIABLES
#define EXTERN              /* nothing */
#define INITIALIZE(...)     = __VA_ARGS__
#else
#define EXTERN              extern
#define INITIALIZE(...)     /* nothing */
#endif /* DEFINE_VARIABLES */

file1c.h

#ifndef FILE1C_H_INCLUDED
#define FILE1C_H_INCLUDED

struct oddball
{
    int a;
    int b;
};

extern void use_them(void);
extern int increment(void);
extern int oddball_value(void);

#endif /* FILE1C_H_INCLUDED */

file2c.h


/* Standard prologue */
#if defined(DEFINE_VARIABLES) && !defined(FILE2C_H_DEFINITIONS)
#undef FILE2C_H_INCLUDED
#endif

#ifndef FILE2C_H_INCLUDED
#define FILE2C_H_INCLUDED

#include "external.h"   /* Support macros EXTERN, INITIALIZE */
#include "file1c.h"     /* Type definition for struct oddball */

#if !defined(DEFINE_VARIABLES) || !defined(FILE2C_H_DEFINITIONS)

/* Global variable declarations / definitions */
EXTERN int global_variable INITIALIZE(37);
EXTERN struct oddball oddball_struct INITIALIZE({ 41, 43 });

#endif /* !DEFINE_VARIABLES || !FILE2C_H_DEFINITIONS */

/* Standard epilogue */
#ifdef DEFINE_VARIABLES
#define FILE2C_H_DEFINITIONS
#endif /* DEFINE_VARIABLES */

#endif /* FILE2C_H_INCLUDED */

file3c.c

#define DEFINE_VARIABLES
#include "file2c.h"  /* Variables now defined and initialized */

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }

file4c.c

#include "file2c.h"
#include <stdio.h>

void use_them(void)
{
    printf("Global variable: %d\n", global_variable++);
    oddball_struct.a += global_variable;
    oddball_struct.b -= global_variable / 2;
}

file5c.c


#include "file2c.h"     /* Declare variables */

#define DEFINE_VARIABLES
#include "file2c.h"  /* Variables now defined and initialized */

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }

file6c.c


#define DEFINE_VARIABLES
#include "file2c.h"     /* Variables now defined and initialized */

#include "file2c.h"     /* Declare variables */

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }


The next source file completes the source (provides a main program) for prog5, prog6 and prog7:

prog5.c

#include "file2c.h"
#include <stdio.h>

int main(void)
{
    use_them();
    global_variable += 19;
    use_them();
    printf("Increment: %d\n", increment());
    printf("Oddball:   %d\n", oddball_value());
    return 0;
}
  • prog5 uses prog5.c, file3c.c, file4c.c, file1c.h, file2c.h, external.h.

  • prog6 uses prog5.c, file5c.c, file4c.c, file1c.h, file2c.h, external.h.

  • prog7 uses prog5.c, file6c.c, file4c.c, file1c.h, file2c.h, external.h.


This scheme avoids most problems. You only run into a problem if a header that defines variables (such as file2c.h) is included by another header (say file7c.h) that defines variables. There isn't an easy way around that other than "don't do it".

You can partially work around the problem by revising file2c.h into file2d.h:

file2d.h

/* Standard prologue */
#if defined(DEFINE_VARIABLES) && !defined(FILE2D_H_DEFINITIONS)
#undef FILE2D_H_INCLUDED
#endif

#ifndef FILE2D_H_INCLUDED
#define FILE2D_H_INCLUDED

#include "external.h"   /* Support macros EXTERN, INITIALIZE */
#include "file1c.h"     /* Type definition for struct oddball */

#if !defined(DEFINE_VARIABLES) || !defined(FILE2D_H_DEFINITIONS)

/* Global variable declarations / definitions */
EXTERN int global_variable INITIALIZE(37);
EXTERN struct oddball oddball_struct INITIALIZE({ 41, 43 });

#endif /* !DEFINE_VARIABLES || !FILE2D_H_DEFINITIONS */

/* Standard epilogue */
#ifdef DEFINE_VARIABLES
#define FILE2D_H_DEFINITIONS
#undef DEFINE_VARIABLES
#endif /* DEFINE_VARIABLES */

#endif /* FILE2D_H_INCLUDED */

The issue becomes 'should the header include #undef DEFINE_VARIABLES?' If you omit that from the header and wrap any defining invocation with #define and #undef:

#define DEFINE_VARIABLES
#include "file2c.h"
#undef DEFINE_VARIABLES

in the source code (so the headers never alter the value of DEFINE_VARIABLES), then you should be clean. It is just a nuisance to have to remember to write the the extra line. An alternative might be:

#define HEADER_DEFINING_VARIABLES "file2c.h"
#include "externdef.h"

externdef.h

/*
** This header must not contain header guards (like <assert.h> must not).
** Each time it is included, the macro HEADER_DEFINING_VARIABLES should
** be defined with the name (in quotes - or possibly angle brackets) of
** the header to be included that defines variables when the macro
** DEFINE_VARIABLES is defined.  See also: external.h (which uses
** DEFINE_VARIABLES and defines macros EXTERN and INITIALIZE
** appropriately).
**
** #define HEADER_DEFINING_VARIABLES "file2c.h"
** #include "externdef.h"
*/

#if defined(HEADER_DEFINING_VARIABLES)
#define DEFINE_VARIABLES
#include HEADER_DEFINING_VARIABLES
#undef DEFINE_VARIABLES
#undef HEADER_DEFINING_VARIABLES
#endif /* HEADER_DEFINING_VARIABLES */

This is getting a tad convoluted, but seems to be secure (using the file2d.h, with no #undef DEFINE_VARIABLES in the file2d.h).

file7c.c

/* Declare variables */
#include "file2d.h"

/* Define variables */
#define HEADER_DEFINING_VARIABLES "file2d.h"
#include "externdef.h"

/* Declare variables - again */
#include "file2d.h"

/* Define variables - again */
#define HEADER_DEFINING_VARIABLES "file2d.h"
#include "externdef.h"

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }

file8c.h

/* Standard prologue */
#if defined(DEFINE_VARIABLES) && !defined(FILE8C_H_DEFINITIONS)
#undef FILE8C_H_INCLUDED
#endif

#ifndef FILE8C_H_INCLUDED
#define FILE8C_H_INCLUDED

#include "external.h"   /* Support macros EXTERN, INITIALIZE */
#include "file2d.h"     /* struct oddball */

#if !defined(DEFINE_VARIABLES) || !defined(FILE8C_H_DEFINITIONS)

/* Global variable declarations / definitions */
EXTERN struct oddball another INITIALIZE({ 14, 34 });

#endif /* !DEFINE_VARIABLES || !FILE8C_H_DEFINITIONS */

/* Standard epilogue */
#ifdef DEFINE_VARIABLES
#define FILE8C_H_DEFINITIONS
#endif /* DEFINE_VARIABLES */

#endif /* FILE8C_H_INCLUDED */

file8c.c

/* Define variables */
#define HEADER_DEFINING_VARIABLES "file2d.h"
#include "externdef.h"

/* Define variables */
#define HEADER_DEFINING_VARIABLES "file8c.h"
#include "externdef.h"

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }


The next two files complete the source for prog8 and prog9:

prog8.c

#include "file2d.h"
#include <stdio.h>

int main(void)
{
    use_them();
    global_variable += 19;
    use_them();
    printf("Increment: %d\n", increment());
    printf("Oddball:   %d\n", oddball_value());
    return 0;
}

file9c.c

#include "file2d.h"
#include <stdio.h>

void use_them(void)
{
    printf("Global variable: %d\n", global_variable++);
    oddball_struct.a += global_variable;
    oddball_struct.b -= global_variable / 2;
}

  • prog8 uses prog8.c, file7c.c, file9c.c.

  • prog9 uses prog8.c, file8c.c, file9c.c.


However, the problems are relatively unlikely to occur in practice, especially if you take the standard advice to

A

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had same issue and I solved it by "pod setup" after installing cocoapods.

How can I count the number of characters in a Bash variable

you can use wc to count the number of characters in the file wc -m filename.txt. Hope that help.

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

Twitter - share button, but with image

I used this code to solve this problem.

<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>

You can check the tweet-button documentation here tweet-button

How does String.Index work in Swift

enter image description here

All of the following examples use

var str = "Hello, playground"

startIndex and endIndex

  • startIndex is the index of the first character
  • endIndex is the index after the last character.

Example

// character
str[str.startIndex] // H
str[str.endIndex]   // error: after last character

// range
let range = str.startIndex..<str.endIndex
str[range]  // "Hello, playground"

With Swift 4's one-sided ranges, the range can be simplified to one of the following forms.

let range = str.startIndex...
let range = ..<str.endIndex

I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code.

after

As in: index(after: String.Index)

  • after refers to the index of the character directly after the given index.

Examples

// character
let index = str.index(after: str.startIndex)
str[index]  // "e"

// range
let range = str.index(after: str.startIndex)..<str.endIndex
str[range]  // "ello, playground"

before

As in: index(before: String.Index)

  • before refers to the index of the character directly before the given index.

Examples

// character
let index = str.index(before: str.endIndex)
str[index]  // d

// range
let range = str.startIndex..<str.index(before: str.endIndex)
str[range]  // Hello, playgroun

offsetBy

As in: index(String.Index, offsetBy: String.IndexDistance)

  • The offsetBy value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance, you can give it an Int.

Examples

// character
let index = str.index(str.startIndex, offsetBy: 7)
str[index]  // p

// range
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
str[range]  // play

limitedBy

As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

  • The limitedBy is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil if the index is out of bounds.

Example

// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
    str[index]  // p
}

If the offset had been 77 instead of 7, then the if statement would have been skipped.

Why is String.Index needed?

It would be much easier to use an Int index for Strings. The reason that you have to create a new String.Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.

It is possibly to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.

head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt

If you don't want to rest of the lines from the file, just skip the tail part.

XML Error: Extra content at the end of the document

I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

Postgres manually alter sequence

setval('sequence_name', sequence_value)

Int division: Why is the result of 1/3 == 0?

I did this.

double g = 1.0/3.0;
System.out.printf("%gf", g);

Use .0 while doing double calculations or else Java will assume you are using Integers. If a Calculation uses any amount of double values, then the output will be a double value. If the are all Integers, then the output will be an Integer.

Bash write to file without echo?

The way to do this in bash is

zsh <<< '> test <<< "Hello World!"'

This is one of the interesting differences between zsh and bash: given an unchained > or >>, zsh has the good sense to hook it up to stdin, while bash does not. It would be downright useful - if it were only standard. I tried to use this to send & append my ssh key over ssh to a remote authorized_keys file, but the remote host was bash, of course, and quietly did nothing.

And that's why you should just use cat.

Adding a regression line on a ggplot

The simple solution using geom_abline:

geom_abline(slope = coef(data.lm)[[2]], intercept = coef(data.lm)[[1]])

Where data.lm is an lm object, and coef(data.lm) looks something like this:

> coef(data.lm)
(Intercept)    DepDelay 
  -2.006045    1.025109 

The numeric indexing assumes that (Intercept) is listed first, which is the case if the model includes an intercept. If you have some other linear model object, just plug in the slope and intercept values similarly.

How to merge a list of lists with same type of items to a single list of items?

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();

How to regex in a MySQL query

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$' for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

Android 8: Cleartext HTTP traffic not permitted

You might only want to allow cleartext while debugging, but keep the security benefits of rejecting cleartext in production. This is useful for me because I test my app against a development server that does not support https. Here is how to enforce https in production, but allow cleartext in debug mode:

In build.gradle:

// Put this in your buildtypes debug section:
manifestPlaceholders = [usesCleartextTraffic:"true"]

// Put this in your buildtypes release section
manifestPlaceholders = [usesCleartextTraffic:"false"]

In the application tag in AndroidManifest.xml

android:usesCleartextTraffic="${usesCleartextTraffic}"

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

If the problem is that you don't have access to SQL Server and now you are using mixed mode to enable sa or grant an account admin privileges, then it is far easier just to uninstall SQL Server and reinstall.

Working with TIFFs (import, export) in Python using numpy

I recommend using the python bindings to OpenImageIO, it's the standard for dealing with various image formats in the vfx world. I've ovten found it more reliable in reading various compression types compared to PIL.

import OpenImageIO as oiio
input = oiio.ImageInput.open ("/path/to/image.tif")

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Change your code to.

<?php
$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".$rows['user'];
?>

There was syntax error in your query.

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

How to set data attributes in HTML elements

To keep jQuery and the DOM in sync, a simple option may be

$('#mydiv').data('myval',20).attr('data-myval',20);        

counting the number of lines in a text file

I think your question is, "why am I getting one more line than there is in the file?"

Imagine a file:

line 1
line 2
line 3

The file may be represented in ASCII like this:

line 1\nline 2\nline 3\n

(Where \n is byte 0x10.)

Now let's see what happens before and after each getline call:

Before 1: line 1\nline 2\nline 3\n
  Stream: ^
After 1:  line 1\nline 2\nline 3\n
  Stream:         ^

Before 2: line 1\nline 2\nline 3\n
  Stream:         ^
After 2:  line 1\nline 2\nline 3\n
  Stream:                 ^

Before 2: line 1\nline 2\nline 3\n
  Stream:                 ^
After 2:  line 1\nline 2\nline 3\n
  Stream:                         ^

Now, you'd think the stream would mark eof to indicate the end of the file, right? Nope! This is because getline sets eof if the end-of-file marker is reached "during it's operation". Because getline terminates when it reaches \n, the end-of-file marker isn't read, and eof isn't flagged. Thus, myfile.eof() returns false, and the loop goes through another iteration:

Before 3: line 1\nline 2\nline 3\n
  Stream:                         ^
After 3:  line 1\nline 2\nline 3\n
  Stream:                         ^ EOF

How do you fix this? Instead of checking for eof(), see if .peek() returns EOF:

while(myfile.peek() != EOF){
    getline ...

You can also check the return value of getline (implicitly casting to bool):

while(getline(myfile,line)){
    cout<< ...

c# datatable insert column at position 0

Just to improve Wael's answer and put it on a single line:

dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);

UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.

Run/install/debug Android applications over Wi-Fi?

Following steps are standard ones to follow( mostly same as previous answers):-

  • adb tcpip 5555.
  • adb connect your_device_ip_address.
  • adb devices (to see if devices got connected).

But in some cases above steps gives error like "unable to connect to device. Make sure that your computer and your device are connected to the same WiFi network." And you notice the devices are already on the same network.

In this case, install this plugin "Wifi ADB Ultimate" and follow below steps.

  1. Connect the device once through USB.
  2. Refresh the list to check whether its connected.
  3. Go to About Phone > Status > IP Address and note your IP address(e.g. 198.162.0.105).
  4. Come back to Android Studio and fill in this IP as done in below photo and hit the run button.

enter image description here


Now, you are good to go!

json call with C#

If your function resides in an mvc controller u can use the below code with a dictionary object of what you want to convert to json

Json(someDictionaryObj, JsonRequestBehavior.AllowGet);

Also try and look at system.web.script.serialization.javascriptserializer if you are using .net 3.5

as for your web request...it seems ok at first glance..

I would use something like this..

public void WebRequestinJson(string url, string postData)
    {
    StreamWriter requestWriter;

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.Timeout = 20000;

        webRequest.ContentType = "application/json";
        //POST the data.
        using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
        {
            requestWriter.Write(postData);
        }
    }
}

May be you can make the post and json string a parameter and use this as a generic webrequest method for all calls.

push object into array

I'm not really sure, but you can try some like this:

var pack = function( arr ) {
    var length = arr.length,
        result = {},
        i;

    for ( i = 0; i < length; i++ ) {
        result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
    }

    return result;
};

pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}

Find the files existing in one directory but not in the other

This is a bit late but may help someone. Not sure if diff or rsync spit out just filenames in a bare format like this. Thanks to plhn for giving that nice solution which I expanded upon below.

If you want just the filenames so it's easy to just copy the files you need in a clean format, you can use the find command.

comm -23 <(find dir1 | sed 's/dir1/\//'| sort) <(find dir2 | sed 's/dir2/\//'| sort) | sed 's/^\//dir1/'

This assumes that both dir1 and dir2 are in the same parent folder. sed just removes the parent folder so you can compare apples with apples. The last sed just puts the dir1 name back.

If you just want files:

comm -23 <(find dir1 -type f | sed 's/dir1/\//'| sort) <(find dir2 -type f | sed 's/dir2/\//'| sort) | sed 's/^\//dir1/'

Similarly for directories:

comm -23 <(find dir1 -type d | sed 's/dir1/\//'| sort) <(find dir2 -type d | sed 's/dir2/\//'| sort) | sed 's/^\//dir1/'

How to get the indexpath.row when an element is activated?

Extend UITableView to create function that get indexpath for a view:

extension UITableView {
    func indexPath(for view: UIView) -> IndexPath? {
        self.indexPathForRow(at: view.convert(.zero, to: self))
    }
}

How to use:

let row = tableView.indexPath(for: sender)?.row

Detect touch press vs long press vs movement?

This code can distinguish between click and movement (drag, scroll). In onTouchEvent set a flag isOnClick, and initial X, Y coordinates on ACTION_DOWN. Clear the flag on ACTION_MOVE (minding that unintentional movement is often detected which can be solved with a THRESHOLD const).

private float mDownX;
private float mDownY;
private final float SCROLL_THRESHOLD = 10;
private boolean isOnClick;

@Override
public boolean onTouchEvent(MotionEvent ev) {
    switch (ev.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            mDownX = ev.getX();
            mDownY = ev.getY();
            isOnClick = true;
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            if (isOnClick) {
                Log.i(LOG_TAG, "onClick ");
                //TODO onClick code
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (isOnClick && (Math.abs(mDownX - ev.getX()) > SCROLL_THRESHOLD || Math.abs(mDownY - ev.getY()) > SCROLL_THRESHOLD)) {
                Log.i(LOG_TAG, "movement detected");
                isOnClick = false;
            }
            break;
        default:
            break;
    }
    return true;
}

For LongPress as suggested above, GestureDetector is the way to go. Check this Q&A:

Detecting a long press with Android

How to use ternary operator in razor (specifically on HTML attributes)?

in my problem I want the text of anchor <a>text</a> inside my view to be based on some value and that text is retrieved form App string Resources

so, this @() is the solution

<a href='#'>
      @(Model.ID == 0 ? Resource_en.Back : Resource_en.Department_View_DescartChanges)
</a>

if the text is not from App string Resources use this

@(Model.ID == 0 ? "Back" :"Descart Changes")

Prevent RequireJS from Caching Required Scripts

This is in addition to @phil mccull's accepted answer.

I use his method but I also automate the process by creating a T4 template to be run pre-build.

Pre-Build Commands:

set textTemplatingPath="%CommonProgramFiles(x86)%\Microsoft Shared\TextTemplating\$(VisualStudioVersion)\texttransform.exe"
if %textTemplatingPath%=="\Microsoft Shared\TextTemplating\$(VisualStudioVersion)\texttransform.exe" set textTemplatingPath="%CommonProgramFiles%\Microsoft Shared\TextTemplating\$(VisualStudioVersion)\texttransform.exe"
%textTemplatingPath% "$(ProjectDir)CacheBuster.tt"

enter image description here

T4 template:

enter image description here

Generated File: enter image description here

Store in variable before require.config.js is loaded: enter image description here

Reference in require.config.js:

enter image description here

Recursively list all files in a directory including files in symlink directories

ls -R -L

-L dereferences symbolic links. This will also make it impossible to see any symlinks to files, though - they'll look like the pointed-to file.

How can I find the latitude and longitude from address?

public void goToLocationFromAddress(String strAddress) {
    //Create coder with Activity context - this
    Geocoder coder = new Geocoder(this);
    List<Address> address;

    try {
        //Get latLng from String
        address = coder.getFromLocationName(strAddress, 5);

        //check for null
        if (address != null) {

            //Lets take first possibility from the all possibilities.
            try {
                Address location = address.get(0);
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                //Animate and Zoon on that map location
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
            } catch (IndexOutOfBoundsException er) {
                Toast.makeText(this, "Location isn't available", Toast.LENGTH_SHORT).show();
            }

        }


    } catch (IOException e) {
        e.printStackTrace();
    }
}

How to use JavaScript variables in jQuery selectors?

$("input").click(function(){
        var name = $(this).attr("name");
        $('input[name="' + name + '"]').hide();    
    });   

Also works with ID:

var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();

when, (sometimes)

$('input#' + id).hide();

does not work, as it should.

You can even do both:

$('input[name="' + name + '"][id="' + id + '"]').hide();

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

How can I view array structure in JavaScript with alert()?

If what you want is to show with an alert() the content of an array of objects, i recomend you to define in the object the method toString() so with a simple alert(MyArray); the full content of the array will be shown in the alert.

Here is an example:

//-------------------------------------------------------------------
// Defininf the Point object
function Point(CoordenadaX, CoordenadaY) {
    // Sets the point coordinates depending on the parameters defined
    switch (arguments.length) {
        case 0:
            this.x = null;
            this.y = null;
            break;
        case 1:
            this.x = CoordenadaX;
            this.y = null;
            break;
        case 2:
            this.x = CoordenadaX;
            this.y = CoordenadaY;
            break;
    }
    // This adds the toString Method to the point object so the 
    // point can be printed using alert();
    this.toString = function() {
        return " (" + this.x + "," + this.y + ") ";
    };
 }

Then if you have an array of points:

var MyArray = [];
MyArray.push ( new Point(5,6) );
MyArray.push ( new Point(7,9) );

You can print simply calling:

alert(MyArray);

Hope this helps!

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

Try adding root path.

app.get('/', function(req, res) {
    res.sendFile('index.html', { root: __dirname });
});

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

  1. Follow the below procedure to solve the error.

  2. Go to File -> Project structure.

enter image description here

  1. From the drop down box, you will know all the version of build tools that are installed in your android studio.
  2. Look for a higher version. If Gradle cannot find 24.0.0, check if 24.0.1 is present in drop down.
  3. Do a complete code search. Find all the places where "24.0.0" is found. Replace it with "24.0.1"
  4. Do a gradle sync.

Creating a singleton in Python

class Foo(object):
     pass

some_global_variable = Foo()

Modules are imported only once, everything else is overthinking. Don't use singletons and try not to use globals.

Efficient evaluation of a function at every cell of a NumPy array

I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.

One can write his own customised ufunc in C, which surely is more efficient, or by invoking np.frompyfunc, which is built-in factory method. After testing, this is more efficient than np.vectorize:

f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)

%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms

I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post

Generating random numbers in Objective-C

I wrote my own random number utility class just so that I would have something that functioned a bit more like Math.random() in Java. It has just two functions, and it's all made in C.

Header file:

//Random.h
void initRandomSeed(long firstSeed);
float nextRandomFloat();

Implementation file:

//Random.m
static unsigned long seed;

void initRandomSeed(long firstSeed)
{ 
    seed = firstSeed;
}

float nextRandomFloat()
{
    return (((seed= 1664525*seed + 1013904223)>>16) / (float)0x10000);
}

It's a pretty classic way of generating pseudo-randoms. In my app delegate I call:

#import "Random.h"

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    initRandomSeed( (long) [[NSDate date] timeIntervalSince1970] );
    //Do other initialization junk.
}

Then later I just say:

float myRandomNumber = nextRandomFloat() * 74;

Note that this method returns a random number between 0.0f (inclusive) and 1.0f (exclusive).

Distribution certificate / private key not installed

Just for anyone else who goes through this, the answers above are correct but it can still be a bit confusing especially if you have multiple certificates. These were the steps that I took:

  1. First take note of the date in the actual distribution certificate that is missing its private key. Then go to the keychain application on the other computer and type iOS in the search bar. It will show all of your iOS Developer and Distribution keys so you have to find the right one.

  2. Click the right arrow of each iOS Distribution entry to reveal the certificate and find the one with the correct date and export that one by right clicking and selection export.

  3. Then just import it in the keychain of the new computer and at least with Xcode 9.3 it immediately recognizes it and corrects the error so you can now upload your achieve.

HTML: Select multiple as dropdown

    <select name="select_box"  multiple>
        <option>123</option>
        <option>456</option>
        <option>789</option>
     </select>

python 2 instead of python 3 as the (temporary) default python?

Use python command to launch scripts, not shell directly. E.g.

  python2 /usr/bin/command

AFAIK this is the recommended method to workaround scripts with bad env interpreter line.

Android Support Design TabLayout: Gravity Center and Mode Scrollable

 <android.support.design.widget.TabLayout
                    android:id="@+id/tabList"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    app:tabMode="scrollable"/>

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

Actually you can use an interface to achieve what you want.

public interface Animal {
    String getName();
    String getVoice();
}
public class Dog implements Animal{
    @Override 
    String getName(){return "Dog";}
    @Override
    String getVoice(){return "woof!";}

}

you can then use the collections using

List <Animal> animalGroup = new ArrayList<Animal>();
animalGroup.add(new Dog());

How can I brew link a specific version?

I asked in #machomebrew and learned that you can switch between versions using brew switch.

$ brew switch libfoo mycopy 

to get version mycopy of libfoo.

Hover and Active only when not disabled

A lower-specificity approach that works in most modern browsers (IE11+, and excluding some mobile Opera & IE browsers -- http://caniuse.com/#feat=pointer-events):

.btn {
  /* base styles */
}

.btn[disabled]
  opacity: 0.4;
  cursor: default;
  pointer-events: none;
}

.btn:hover {
  color: red;
}

The pointer-events: none rule will disable hover; you won't need to raise specificity with a .btn[disabled]:hover selector to nullify the hover style.

(FYI, this is the simple HTML pointer-events, not the contentious abstracting-input-devices pointer-events)

Python list / sublist selection -1 weirdness

In list[first:last], last is not included.

The 10th element is ls[9], in ls[0:10] there isn't ls[10].

Should I declare Jackson's ObjectMapper as a static field?

com.fasterxml.jackson.databind.type.TypeFactory._hashMapSuperInterfaceChain(HierarchicType)

com.fasterxml.jackson.databind.type.TypeFactory._findSuperInterfaceChain(Type, Class)
  com.fasterxml.jackson.databind.type.TypeFactory._findSuperTypeChain(Class, Class)
     com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(Class, Class, TypeBindings)
        com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(JavaType, Class)
           com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(ParameterizedType, TypeBindings)
              com.fasterxml.jackson.databind.type.TypeFactory._constructType(Type, TypeBindings)
                 com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeReference)
                    com.fasterxml.jackson.databind.ObjectMapper.convertValue(Object, TypeReference)

The method _hashMapSuperInterfaceChain in class com.fasterxml.jackson.databind.type.TypeFactory is synchronized. Am seeing contention on the same at high loads.

May be another reason to avoid a static ObjectMapper

The connection to adb is down, and a severe error has occurred

Reinstall everything??? no way! just add the path to SDK tools and platform tools in your classpath from Environment Variables. Then restart Eclipse.

other way go to Devices -> Reset adb, or simply open the task manager and kill the adb.exe process.

how to remove multiple columns in r dataframe?

If you only want to remove columns 5 and 7 but not 6 try:

album2 <- album2[,-c(5,7)] #deletes columns 5 and 7

Visual Studio Community 2015 expiration date

I am running VSCommunity 2015 in Win8.1 virtual machine installed inside a Parallels 11 virtual machine installed on my Mac OSX El Capitan. To my surprise and delight it installed and ran fine. I used it for 2 weeks without signing into my Microsoft account. I tried to login 6 weeks later and got the 30 day trial screen shown above.

However for me I was able to simply click on the link above shown as "Check for an updated license" and was prompted in to log in to my Microsoft account. I did so and it granted me a license successfully and was seamless. Now under License Status it displays as "This product is licensed to: ".

I guess I got lucky as I'm guessing this is how it is supposed to work.

[sidebar]: Over the decades I've disliked most MS products but have been out of the VS IDE development tools game for awhile, and I have to say using VSComm15 has been flawless. Using it to learn C# and the IDE itself for a new contract job and it worked perfectly and has great features.

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

I had this problem on debian. The issue was, I was using the dotdeb repository for more recent PHP packages. For some reason, it updated the php cli to 7.0, while the web php binary remained php 5.6. I used this answer to link the php command line binary to the 5.6 version, like so:

$ sudo ln -sfn /usr/bin/php5 /etc/alternatives/php

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

The (m) indicates the column display width; applications such as the MySQL client make use of this when showing the query results.

For example:

| v   | a   |  b  |   c |
+-----+-----+-----+-----+
| 1   | 1   |  1  |   1 |
| 10  | 10  | 10  |  10 |
| 100 | 100 | 100 | 100 |

Here a, b and c are using TINYINT(1), TINYINT(2) and TINYINT(3) respectively. As you can see, it pads the values on the left side using the display width.

It's important to note that it does not affect the accepted range of values for that particular type, i.e. TINYINT(1) still accepts [-128 .. 127].

How big can a MySQL database get before performance starts to degrade

2GB and about 15M records is a very small database - I've run much bigger ones on a pentium III(!) and everything has still run pretty fast.. If yours is slow it is a database/application design problem, not a mysql one.

Determine if char is a num or letter

You can normally check for ASCII letters or numbers using simple conditions

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
    /*This is an alphabet*/
}

For digits you can use

if (ch >= '0' && ch <= '9')
{
    /*It is a digit*/
}

But since characters in C are internally treated as ASCII values you can also use ASCII values to check the same.

How to check if a character is number or letter

Biggest differences of Thrift vs Protocol Buffers?

They both offer many of the same features; however, there are some differences:

  • Thrift supports 'exceptions'
  • Protocol Buffers have much better documentation/examples
  • Thrift has a builtin Set type
  • Protocol Buffers allow "extensions" - you can extend an external proto to add extra fields, while still allowing external code to operate on the values. There is no way to do this in Thrift
  • I find Protocol Buffers much easier to read

Basically, they are fairly equivalent (with Protocol Buffers slightly more efficient from what I have read).

Vertical Text Direction

From developer.mozilla.org

The text-orientation CSS property sets the orientation of the text characters in a line. It only affects text in vertical mode (when writing-mode is not horizontal-tb). It is useful for controlling the display of languages that use vertical script, and also for making vertical table headers.

writing-mode: vertical-rl;
text-orientation: mixed;

You can also review all the Syntax here

/* Keyword values */
text-orientation: mixed;
text-orientation: upright;
text-orientation: sideways-right;
text-orientation: sideways;
text-orientation: use-glyph-orientation;

/* Global values */
text-orientation: inherit;
text-orientation: initial;
text-orientation: unset;

How to correct indentation in IntelliJ

Code ? Reformat Code... (default Ctrl + Alt + L) for the whole file or Code ? Auto-Indent Lines (default Ctrl + Alt + I) for the current line or selection.

You can customise the settings for how code is auto-formatted under File ? Settings ? Editor ? Code Style.


To ensure comments are also indented to the same level as the code, you can simply do as follows:

UI screenshot (example for JavaScript)

How to check programmatically if an application is installed or not in Android?

Try this

This code is used to check weather your application with package name is installed or not if not then it will open playstore link of your app otherwise your installed app

String your_apppackagename="com.app.testing";
    PackageManager packageManager = getPackageManager();
    ApplicationInfo applicationInfo = null;
    try {
        applicationInfo = packageManager.getApplicationInfo(your_apppackagename, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    if (applicationInfo == null) {
        // not installed it will open your app directly on playstore
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + your_apppackagename)));
    } else {
        // Installed
        Intent LaunchIntent = packageManager.getLaunchIntentForPackage(your_apppackagename);
        startActivity( LaunchIntent );
    }

List(of String) or Array or ArrayList

You can do something like this,

  Dim lstOfStrings As New List(Of String) From {"Value1", "Value2", "Value3"}

Collection Initializers

"The operation is not valid for the state of the transaction" error and transaction scope

For any wanderer that comes across this in the future. If your application and database are on different machines and you are getting the above error especially when using TransactionScope, enable Network DTC access. Steps to do this are:

  1. Add firewall rules to allow your machines to talk to each other.
  2. Ensure the distributed transaction coordinator service is running
  3. Enable network dtc access. Run dcomcnfg. Go to Component sevices > My Computer > Distributed Transaction Coordinator > Local DTC. Right click properties.
  4. Enable network dtc access as shown.

Important: Do not edit/change the user account and password in the DTC Logon account field, leave it as is, you will end up re-installing windows if you do.

DTC photo

Cannot read property 'length' of null (javascript)

This also works - evaluate, if capital is defined. If not, this means, that capital is undefined or null (or other value, that evaluates to false in js)

if (capital && capital.length < 1) {do your stuff}

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

How to pass a list from Python, by Jinja2 to JavaScript

To add up on the selected answer, I have been testing a new option that is working too using jinja2 and flask:

@app.route('/')
def my_view():
    data = [1, 2, 3, 4, 5]
    return render_template('index.html', data=data)

The template:

<script>
    console.log( {{ data | tojson }} )
</script>

the output of the rendered template:

<script>
    console.log( [1, 2, 3, 4] )
</script>

The safe could be added but as well like {{ data | tojson | safe }} to avoid html escape but it is working without too.

Set an empty DateTime variable

The .addwithvalue needs dbnull. You could do something like this:

DateTime? someDate = null;
//...
if (someDate == null)
    myCommand.Parameters.AddWithValue("@SurgeryDate", DBnull.value);

or use a method extension...

  public static class Extensions
    {
        public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
        {
            if (value == null)
                return collection.AddWithValue(parameterName, DBNull.Value);
            else
                return collection.AddWithValue(parameterName, value);
        }
    }

How to set custom ActionBar color / style?

in the style.xml add this code

<resources>
    <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyAction</item>
    </style>

    <style name="MyActionBarTheme" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#333333</item>
    </style>
</resources>

How can I call a WordPress shortcode within a template?

echo do_shortcode('[CONTACT-US-FORM]');

Use this in your template.

Look here for more: Do Shortcode

How can I make an entire HTML form "readonly"?

I'd rather use jQuery:

$('#'+formID).find(':input').attr('disabled', 'disabled');

find() would go much deeper till nth nested child than children(), which looks for immediate children only.

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

Best way to determine user's locale within browser

Combining the multiple ways browsers are using to store the user's language, you get this function :

const getNavigatorLanguage = () => {
  if (navigator.languages && navigator.languages.length) {
    return navigator.languages[0];
  } else {
    return navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
  }
}

We first check the navigator.languages array for its first element.
Then we get either navigator.userLanguage or navigator.language.
If this fails we get navigator.browserLanguage.
Finally, we set it to 'en' if everything else failed.


And here's the sexy one-liner :

const getNavigatorLanguage = () => (navigator.languages && navigator.languages.length) ? navigator.languages[0] : navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';

Load image from url

Try this add picasso lib jar file

Picasso.with(context)
                .load(ImageURL)
                .resize(width,height).noFade().into(imageView);

How to view file history in Git?

Use git log to view the commit history. Each commit has an associated revision specifier that is a hash key (e.g. 14b8d0982044b0c49f7a855e396206ee65c0e787 and b410ad4619d296f9d37f0db3d0ff5b9066838b39). To view the difference between two different commits, use git diff with the first few characters of the revision specifiers of both commits, like so:

# diff between commits 14b8... and b410...
git diff 14b8..b410
# only include diff of specified files
git diff 14b8..b410 path/to/file/a path/to/file/b

If you want to get an overview over all the differences that happened from commit to commit, use git log or git whatchanged with the patch option:

# include patch displays in the commit history
git log -p
git whatchanged -p
# only get history of those commits that touch specified paths
git log path/a path/b
git whatchanged path/c path/d

Error: Cannot pull with rebase: You have unstaged changes

This works for me:

git fetch
git rebase --autostash FETCH_HEAD

Getting index value on razor foreach

Take a look at this solution using Linq. His example is similar in that he needed different markup for every 3rd item.

foreach( var myItem in Model.Members.Select(x,i) => new {Member = x, Index = i){
    ...
}

Toggle button using two image on different state

You can try something like this. Here on click of image button I toggle the imageview.

holder.imgitem.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!onclick){
            mSparseBooleanArray.put((Integer) view.getTag(), true);
            holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
            onclick=true;}
            else if(onclick)
            {
                 mSparseBooleanArray.put((Integer) view.getTag(), false);
                  holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);

            onclick=false;
            }
        }
    });

IPython Notebook save location

Yes, you can specify the notebooks location in your profile configuration. Since it's not saving them to the directory where you started the notebook, I assume that you have this option set in your profile. You can find out the the path to the profiles directory by using:

$ ipython locate

Either in your default profile or in the profile you use, edit the ipython_notebook_config.py file and change the lines:

Note: In case you don't have a profile, or the profile folder does not contain the ipython_notebook_config.py file, use ipython profile create.

# The directory to use for notebooks.
c.NotebookManager.notebook_dir = u'/path/to/your/notebooks'

and

# The directory to use for notebooks.
c.FileNotebookManager.notebook_dir = u'/path/to/your/notebooks'

Or just comment them out if you want the notebooks saved in the current directory.

Update (April 11th 2014): in IPython 2.0 the property name in the config file changed, so it's now:

c.NotebookApp.notebook_dir = u'/path/to/your/notebooks'

Parsing boolean values with argparse

Simplest & most correct way is:

from distutils.util import strtobool

parser.add_argument('--feature', dest='feature', 
                    type=lambda x: bool(strtobool(x)))

Do note that True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

Creating a script for a Telnet session?

I like the example given by Active State using python. Here is the full link. I added the simple log in part from the link but you can get the gist of what you could do.

import telnetlib

prdLogBox='142.178.1.3'
uid = 'uid'
pwd = 'yourpassword'

tn = telnetlib.Telnet(prdLogBox)
tn.read_until("login: ")
tn.write(uid + "\n")
tn.read_until("Password:")
tn.write(pwd + "\n")
tn.write("exit\n")
tn.close()

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

string s = "hello";
char c = s[1];
// now c == 'e'

See also Substring, to return more than one character.

How do I send an HTML email?

You can find a complete and very simple java class for sending emails using Google(gmail) account here, Send email message using java application

It uses following properties

Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");

Short rot13 function - Python

From the builtin module this.py (import this):

s = "foobar"

d = {}
for c in (65, 97):
    for i in range(26):
        d[chr(i+c)] = chr((i+13) % 26 + c)

print("".join([d.get(c, c) for c in s]))  # sbbone

How do I print the content of a .txt file in Python?

to input a file:

fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'

to output this file you can do:

for element in fin:
    print element 

if the elements are a string you'd better add this before print:

element = element.strip()

strip() remove notations like this: /n

Swap two variables without using a temporary variable

C# 7 introduced tuples which enables swapping two variables without a temporary one:

int a = 10;
int b = 2;
(a, b) = (b, a);

This assigns b to a and a to b.

Store output of sed into a variable

Use command substitution like this:

line=$(sed -n '2p' myfile)
echo "$line"

Also note that there is no space around the = sign.

Download multiple files with a single action

_x000D_
_x000D_
var links = [_x000D_
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.exe',_x000D_
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.dmg',_x000D_
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar'_x000D_
];_x000D_
_x000D_
function downloadAll(urls) {_x000D_
  var link = document.createElement('a');_x000D_
_x000D_
  link.setAttribute('download', null);_x000D_
  link.style.display = 'none';_x000D_
_x000D_
  document.body.appendChild(link);_x000D_
_x000D_
  for (var i = 0; i < urls.length; i++) {_x000D_
    link.setAttribute('href', urls[i]);_x000D_
    link.click();_x000D_
  }_x000D_
_x000D_
  document.body.removeChild(link);_x000D_
}
_x000D_
<button onclick="downloadAll(window.links)">Test me!</button>
_x000D_
_x000D_
_x000D_

Copying from one text file to another using Python

If all of that did not work try this.

with open("hello.txt") as f:
with open("copy.txt", "w") as f1:
    for line in f:
        f1.write(line)

How to Update a Component without refreshing full page - Angular

One of many solutions is to create an @Injectable() class which holds data that you want to show in the header. Other components can also access this class and alter this data, effectively changing the header.

Another option is to set up @Input() variables and @Output() EventEmitters which you can use to alter the header data.

Edit Examples as you requested:

@Injectable()
export class HeaderService {
    private _data;
    set data(value) {
        this._data = value;
    }
    get data() {
        return this._data;
    }
}

in other component:

constructor(private headerService: HeaderService) {}

// Somewhere
this.headerService.data = 'abc';

in header component:

let headerData;

constructor(private headerService: HeaderService) {
    this.headerData = this.headerService.data;
}

I haven't actually tried this. If the get/set doesn't work you can change it to use a Subject();

// Simple Subject() example:
let subject = new Subject();
this.subject.subscribe(response => {
  console.log(response); // Logs 'hello'
});
this.subject.next('hello');

How do I run all Python unit tests in a directory?

Based on the answer of Stephen Cagle I added support for nested test modules.

import fnmatch
import os
import unittest

def all_test_modules(root_dir, pattern):
    test_file_names = all_files_in(root_dir, pattern)
    return [path_to_module(str) for str in test_file_names]

def all_files_in(root_dir, pattern):
    matches = []

    for root, dirnames, filenames in os.walk(root_dir):
        for filename in fnmatch.filter(filenames, pattern):
            matches.append(os.path.join(root, filename))

    return matches

def path_to_module(py_file):
    return strip_leading_dots( \
        replace_slash_by_dot(  \
            strip_extension(py_file)))

def strip_extension(py_file):
    return py_file[0:len(py_file) - len('.py')]

def replace_slash_by_dot(str):
    return str.replace('\\', '.').replace('/', '.')

def strip_leading_dots(str):
    while str.startswith('.'):
       str = str[1:len(str)]
    return str

module_names = all_test_modules('.', '*Tests.py')
suites = [unittest.defaultTestLoader.loadTestsFromName(mname) for mname 
    in module_names]

testSuite = unittest.TestSuite(suites)
runner = unittest.TextTestRunner(verbosity=1)
runner.run(testSuite)

The code searches all subdirectories of . for *Tests.py files which are then loaded. It expects each *Tests.py to contain a single class *Tests(unittest.TestCase) which is loaded in turn and executed one after another.

This works with arbitrary deep nesting of directories/modules, but each directory in between needs to contain an empty __init__.py file at least. This allows the test to load the nested modules by replacing slashes (or backslashes) by dots (see replace_slash_by_dot).

ScrollIntoView() causing the whole page to move

Play around with scrollIntoViewIfNeeded() ... make sure it's supported by the browser.

Multi-line strings in PHP

Maybe try ".=" indead of "="?

$xml="l";
$xml.="vv";

will give you "lvv";

Counting the number of occurences of characters in a string

You should be able to utilize the StringUtils class and the countMatches() method.

public static int countMatches(String str, String sub)

Counts how many times the substring appears in the larger String.

Try the following:

int count = StringUtils.countMatches("a.b.c.d", ".");

PHP sessions that have already been started

I encountered this issue while trying to fix $_SESSION's blocking behavior.

http://konrness.com/php5/how-to-prevent-blocking-php-requests/

The session file remains locked until the script completes or the session is manually closed.

So, by default, a page should open a session in read-only mode. But once it's open in read-only, it has to be closed-and-reopened in to get it into write mode.

const SESSION_DEFAULT_COOKIE_LIFETIME = 86400;

/**
 * Open _SESSION read-only
 */
function OpenSessionReadOnly() {
    session_start([
                      'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME,
                      'read_and_close'  => true,    // READ ACCESS FAST
                  ]);
    // $_SESSION is now defined. Call WriteSessionValues() to write out values
}

/**
 * _SESSION is read-only by default. Call this function to save a new value
 * call this function like `WriteSessionValues(["username"=>$login_user]);`
 * to set $_SESSION["username"]
 *
 * @param array $values_assoc_array
 */
function WriteSessionValues($values_assoc_array) {
    // this is required to close the read-only session and 
    // not get a warning on the next line.
    session_abort();

    // now open the session with write access
    session_start([ 'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME ]);

    foreach ($values_assoc_array as $key => $value) {
        $_SESSION[ $key ] = $value;
    }
    session_write_close();  // Write session data and end session

    OpenSessionReadOnly(); // now reopen the session in read-only mode.
}

OpenSessionReadOnly();  // start the session for this page

Then when you go to write some value:

WriteSessionValues(["username"=>$login_user]);

The function takes an array of key=>value pairs to make it even more efficient.

How do you check whether a number is divisible by another number (Python)?

You can simply use % Modulus operator to check divisibility.
For example: n % 2 == 0 means n is exactly divisible by 2 and n % 2 != 0 means n is not exactly divisible by 2.

javascript regex - look behind alternative?

If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.

Creating a BAT file for python script

--- xxx.bat ---

@echo off
set NAME1="Marc"
set NAME2="Travis"
py -u "CheckFile.py" %NAME1% %NAME2%
echo %ERRORLEVEL%
pause

--- yyy.py ---

import sys
import os
def names(f1,f2):

    print (f1)
    print (f2)
    res= True
    if f1 == "Travis":
         res= False
    return res

if __name__ == "__main__":
     a = sys.argv[1]
     b = sys.argv[2]
     c = names(a, b) 
     if c:
        sys.exit(1)
    else:
        sys.exit(0)        

Create ul and li elements in javascript.

Try out below code snippet:

 var list = [];
 var text;

function update() {
    console.log(list);    

    for (var i = 0; i < list.length; i++) {
       console.log( i );
       var letters;
       var ul = document.getElementById("list");
       var li = document.createElement("li");

       li.appendChild(document.createTextNode(list[i]));
       ul.appendChild(li);

       letters += "<li>"  + list[i] + "</li>";
    }

 document.getElementById("list").innerHTML = letters;

}

function myFunction() {
    text = prompt("enter TODO");  
    list.push(text);
    update();
}   

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

Based on Matt Johanson's comment on the solution provided by Sheldon Griffin I created the following code:

    Date.prototype.stdTimezoneOffset = function() {
        var fy=this.getFullYear();
        if (!Date.prototype.stdTimezoneOffset.cache.hasOwnProperty(fy)) {

            var maxOffset = new Date(fy, 0, 1).getTimezoneOffset();
            var monthsTestOrder=[6,7,5,8,4,9,3,10,2,11,1];

            for(var mi=0;mi<12;mi++) {
                var offset=new Date(fy, monthsTestOrder[mi], 1).getTimezoneOffset();
                if (offset!=maxOffset) { 
                    maxOffset=Math.max(maxOffset,offset);
                    break;
                }
            }
            Date.prototype.stdTimezoneOffset.cache[fy]=maxOffset;
        }
        return Date.prototype.stdTimezoneOffset.cache[fy];
    };

    Date.prototype.stdTimezoneOffset.cache={};

    Date.prototype.isDST = function() {
        return this.getTimezoneOffset() < this.stdTimezoneOffset(); 
    };

It tries to get the best of all worlds taking into account all the comments and previously suggested answers and specifically it:

1) Caches the result for per year stdTimezoneOffset so that you don't need to recalculate it when testing multiple dates in the same year.

2) It does not assume that DST (if it exists at all) is necessarily in July, and will work even if it will at some point and some place be any month. However Performance-wise it will work faster if indeed July (or near by months) are indeed DST.

3) Worse case it will compare the getTimezoneOffset of the first of each month. [and do that Once per tested year].

The assumption it does still makes is that the if there is DST period is larger then a single month.

If someone wants to remove that assumption he can change loop into something more like whats in the solutin provided by Aaron Cole - but I would still jump half a year ahead and break out of the loop when two different offsets are found]

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

What's the difference between an element and a node in XML?

As described in the various XML specifications, an element is that which consists of a start tag, and end tag, and the content in between, or alternately an empty element tag (which has no content or end tag). In other words, these are all elements:

<foo> stuff </foo>
<foo bar="baz"></foo>
<foo baz="qux" />

Though you hear "node" used with roughly the same meaning, it has no precise definition per XML specs. It's usually used to refer to nodes of things like DOMs, which may be closely related to XML or use XML for their representation.

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

The code marked as the solution did not work for me. This was my solution.

/*
 * http://www.java2s.com/Code/Java/Security/EncryptingaStringwithDES.htm
 * https://stackoverflow.com/questions/23561104/how-to-encrypt-and-decrypt-string-with-my-passphrase-in-java-pc-not-mobile-plat
 */
package encryptiondemo;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 *
 * @author zchumager
 */
public class EncryptionDemo {

  Cipher ecipher;
  Cipher dcipher;

  EncryptionDemo(SecretKey key) throws Exception {
    ecipher = Cipher.getInstance("AES");
    dcipher = Cipher.getInstance("AES");
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    dcipher.init(Cipher.DECRYPT_MODE, key);
  }

  public String encrypt(String str) throws Exception {
    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");

    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);

    // Encode bytes to base64 to get a string
    return new sun.misc.BASE64Encoder().encode(enc);
  }

  public String decrypt(String str) throws Exception {
    // Decode base64 to get bytes
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

    byte[] utf8 = dcipher.doFinal(dec);

    // Decode using utf-8
    return new String(utf8, "UTF8");
  }


    public static void main(String args []) throws Exception
    {

        String data = "Don't tell anybody!";
        String k = "Bar12345Bar12345";

        //SecretKey key = KeyGenerator.getInstance("AES").generateKey();
        SecretKey key = new SecretKeySpec(k.getBytes(), "AES");
        EncryptionDemo encrypter = new EncryptionDemo(key);

        System.out.println("Original String: " + data);

        String encrypted = encrypter.encrypt(data);

        System.out.println("Encrypted String: " + encrypted);

        String decrypted = encrypter.decrypt(encrypted);

        System.out.println("Decrypted String: " + decrypted);
    }
}

What are access specifiers? Should I inherit with private, protected or public?

The explanation from Scott Meyers in Effective C++ might help understand when to use them:

Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.

Android canvas draw rectangle

The code is fine just setStyle of paint as STROKE

paint.setStyle(Paint.Style.STROKE);

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

WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));

This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.


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

Element is Clickable - it is Displayed and Enabled.

From WebDriver docs: Explicit and Implicit Waits

"Gradle Version 2.10 is required." Error

this work for me.

create a new project in android studio. Open project setting and copy the local gradle path. now open the project having gradle problem and paste that url and select local path.

click apply problem will get solved.

how do I get the bullet points of a <ul> to center with the text?

ul {
  padding-left: 0;
  list-style-position: inside;
}

Explanation: The first property padding-left: 0 clears the default padding/spacing for the ul element while list-style-position: inside makes the dots/bullets of li aligned like a normal text.

So this code

<p>The ul element</p>
<ul>
asdfas
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

without any CSS will give us this:
enter image description here
but if we add in the CSS give at the top, that will give us this:
enter image description here

When should you NOT use a Rules Engine?

I will give 2 examples from personal experience where using a Rules Engine was a bad idea, maybe that will help:-

  1. On a past project, I noticed that the rules files (the project used Drools) contained a lot of java code, including loops, functions etc. They were essentially java files masquerading as rules file. When I asked the architect on his reasoning for the design I was told that the "Rules were never intended to be maintained by business users".

Lesson: They are called "Business Rules" for a reason, do not use rules when you cannot design a system that can be easily maintained/understood by Business users.

  1. Another case; The project used rules because requirements were poorly defined/understood and changed often. The development team's solution was to use rules extensively to avoid frequent code deploys.

Lesson: Requirements tend to change a lot during initial release changes and do not warrant usage of rules. Use rules when your business changes often (not requirements). Eg:- A software that does your taxes will change every year as taxation laws change and usage of rules is an excellent idea. Release 1.0 of an web app will change often as users identify new requirements but will stabilize over time. Do not use rules as an alternative to code deploy. ?

Get value from SimpleXMLElement Object

You have to cast simpleXML Object to a string.

$value = (string) $xml->code[0]->lat;

Finding median of list in Python

The sorted() function is very helpful for this. Use the sorted function to order the list, then simply return the middle value (or average the two middle values if the list contains an even amount of elements).

def median(lst):
    sortedLst = sorted(lst)
    lstLen = len(lst)
    index = (lstLen - 1) // 2
   
    if (lstLen % 2):
        return sortedLst[index]
    else:
        return (sortedLst[index] + sortedLst[index + 1])/2.0

Most efficient way to map function over numpy array

squares = squarer(x)

Arithmetic operations on arrays are automatically applied elementwise, with efficient C-level loops that avoid all the interpreter overhead that would apply to a Python-level loop or comprehension.

Most of the functions you'd want to apply to a NumPy array elementwise will just work, though some may need changes. For example, if doesn't work elementwise. You'd want to convert those to use constructs like numpy.where:

def using_if(x):
    if x < 5:
        return x
    else:
        return x**2

becomes

def using_where(x):
    return numpy.where(x < 5, x, x**2)

how to implement a pop up dialog box in iOS

Different people who come to this question mean different things by a popup box. I highly recommend reading the Temporary Views documentation. My answer is largely a summary of this and other related documentation.

Alert (show me an example)

enter image description here

Alerts display a title and an optional message. The user must acknowledge it (a one-button alert) or make a simple choice (a two-button alert) before going on. You create an alert with a UIAlertController.

It is worth quoting the documentation's warning and advice about creating unnecessary alerts.

enter image description here

Notes:

Action Sheet (show me an example)

enter image description here

Action Sheets give the user a list of choices. They appear either at the bottom of the screen or in a popover depending on the size and orientation of the device. As with alerts, a UIAlertController is used to make an action sheet. Before iOS 8, UIActionSheet was used, but now the documentation says:

Important: UIActionSheet is deprecated in iOS 8. (Note that UIActionSheetDelegate is also deprecated.) To create and manage action sheets in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleActionSheet.

Modal View (show me an example)

enter image description here

A modal view is a self-contained view that has everything it needs to complete a task. It may or may not take up the full screen. To create a modal view, use a UIPresentationController with one of the Modal Presentation Styles.

See also

Popover (show me an example)

enter image description here

A Popover is a view that appears when a user taps on something and disappears when tapping off it. It has an arrow showing the control or location from where the tap was made. The content can be just about anything you can put in a View Controller. You make a popover with a UIPopoverPresentationController. (Before iOS 8, UIPopoverController was the recommended method.)

In the past popovers were only available on the iPad, but starting with iOS 8 you can also get them on an iPhone (see here, here, and here).

See also

Notifications

enter image description here

Notifications are sounds/vibrations, alerts/banners, or badges that notify the user of something even when the app is not running in the foreground.

enter image description here

See also

A note about Android Toasts

enter image description here

In Android, a Toast is a short message that displays on the screen for a short amount of time and then disappears automatically without disrupting user interaction with the app.

People coming from an Android background want to know what the iOS version of a Toast is. Some examples of these questions can he found here, here, here, and here. The answer is that there is no equivalent to a Toast in iOS. Various workarounds that have been presented include:

  • Make your own with a subclassed UIView
  • Import a third party project that mimics a Toast
  • Use a buttonless Alert with a timer

However, my advice is to stick with the standard UI options that already come with iOS. Don't try to make your app look and behave exactly the same as the Android version. Think about how to repackage it so that it looks and feels like an iOS app.

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

Here it is! - SP 25 works on Visual Studio 2019, SP 21 on Visual Studio 2017

SAP released SAP Crystal Reports, developer version for Microsoft Visual Studio

You can get it here (click "Installation package for Visual Studio IDE")

To integrate “SAP Crystal Reports, developer version for Microsoft Visual Studio” you must run the Install Executable. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.

New In SP25 Release

Visual Studio 2019, Addressed incidents, Win10 1809, Security update

How to send an HTTP request using Telnet

To somewhat expand on earlier answers, there are a few complications.

telnet is not particularly scriptable; you might prefer to use nc (aka netcat) instead, which handles non-terminal input and signals better.

Also, unlike telnet, nc actually allows SSL (and so https instead of http traffic -- you need port 443 instead of port 80 then).

There is a difference between HTTP 1.0 and 1.1. The recent version of the protocol requires the Host: header to be included in the request on a separate line after the POST or GET line, and to be followed by an empty line to mark the end of the request headers.

The HTTP protocol requires carriage return / line feed line endings. Many servers are lenient about this, but some are not. You might want to use

printf "%\r\n" \
    "GET /questions HTTP/1.1" \
    "Host: stackoverflow.com" \
    "" |
nc --ssl stackoverflow.com 443

If you fall back to HTTP/1.0 you don't always need the Host: header, but many modern servers require the header anyway; if multiple sites are hosted on the same IP address, the server doesn't know from GET /foo HTTP/1.0 whether you mean http://site1.example.com/foo or http://site2.example.net/foo if those two sites are both hosted on the same server (in the absence of a Host: header, a HTTP 1.0 server might just default to a different site than the one you want, so you don't get the contents you wanted).

The HTTPS protocol is identical to HTTP in these details; the only real difference is in how the session is set up initially.

PHP array delete by value (not key)

If you know for definite that your array will contain only one element with that value, you can do

$key = array_search($del_val, $array);
if (false !== $key) {
    unset($array[$key]);
}

If, however, your value might occur more than once in your array, you could do this

$array = array_filter($array, function($e) use ($del_val) {
    return ($e !== $del_val);
});

Note: The second option only works for PHP5.3+ with Closures

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.