Programs & Examples On #Cross process

How to retrieve the hash for the current commit in Git?

There's always git describe as well. By default it gives you --

john@eleanor:/dev/shm/mpd/ncmpc/pkg (master)$ git describe --always
release-0.19-11-g7a68a75

How remove border around image in css?

it's a good idea to use a reset CSS. add this at the top of your CSS file

img, a {border:none, outline: none;}

hope this helps

" app-release.apk" how to change this default generated apk name

First rename your module from app to i.e. SurveyApp

Second add this to your project top-level (root project) gradle. It's working with Gradle 3.0

//rename apk for all sub projects
subprojects {
    afterEvaluate { project ->
        if (project.hasProperty("android")) {
            android.applicationVariants.all { variant ->
                variant.outputs.all {
                    outputFileName = "${project.name}-${variant.name}-${variant.versionName}.apk"
                }
            }
        }
    }
}

Error: unmappable character for encoding UTF8 during maven compilation

When i inspect the console i found that the version of maven compiler is 2.5.1 but in other side i try to build my project with maven 3.2.2.So after writting the exact version in pom.xml, it works good. Here is the full tag:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.2</version>
  <configuration>
   ....
  <configuration>
</plugin>

Render HTML to PDF in Django site

Try wkhtmltopdf with either one of the following wrappers

django-wkhtmltopdf or python-pdfkit

This worked great for me,supports javascript and css or anything for that matter which a webkit browser supports.

For more detailed tutorial please see this blog post

How do I use FileSystemObject in VBA?

Within Excel you need to set a reference to the VB script run-time library. The relevant file is usually located at \Windows\System32\scrrun.dll

  • To reference this file, load the Visual Basic Editor (ALT+F11)
  • Select Tools > References from the drop-down menu
  • A listbox of available references will be displayed
  • Tick the check-box next to 'Microsoft Scripting Runtime'
  • The full name and path of the scrrun.dll file will be displayed below the listbox
  • Click on the OK button.

This can also be done directly in the code if access to the VBA object model has been enabled.

Access can be enabled by ticking the check-box Trust access to the VBA project object model found at File > Options > Trust Center > Trust Center Settings > Macro Settings

VBA Macro settings

To add a reference:

Sub Add_Reference()

    Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\System32\scrrun.dll"
'Add a reference

End Sub

To remove a reference:

Sub Remove_Reference()

Dim oReference As Object

    Set oReference = Application.VBE.ActiveVBProject.References.Item("Scripting")

    Application.VBE.ActiveVBProject.References.Remove oReference
'Remove a reference

End Sub

How to create a DataFrame from a text file in Spark

Update - as of Spark 1.6, you can simply use the built-in csv data source:

spark: SparkSession = // create the Spark Session
val df = spark.read.csv("file.txt")

You can also use various options to control the CSV parsing, e.g.:

val df = spark.read.option("header", "false").csv("file.txt")

For Spark version < 1.6: The easiest way is to use spark-csv - include it in your dependencies and follow the README, it allows setting a custom delimiter (;), can read CSV headers (if you have them), and it can infer the schema types (with the cost of an extra scan of the data).

Alternatively, if you know the schema you can create a case-class that represents it and map your RDD elements into instances of this class before transforming into a DataFrame, e.g.:

case class Record(id: Int, name: String)

val myFile1 = myFile.map(x=>x.split(";")).map {
  case Array(id, name) => Record(id.toInt, name)
} 

myFile1.toDF() // DataFrame will have columns "id" and "name"

How to NodeJS require inside TypeScript file?

Use typings to access node functions from TypeScript:

typings install env~node --global

If you don't have typings install it:

npm install typings --global

Detecting attribute change of value of an attribute I made

There is this extensions that adds an event listener to attribute changes.

Usage:

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
  src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>

Bind attrchange handler function to selected elements

$(selector).attrchange({
    trackValues: true, /* Default to false, if set to true the event object is 
                updated with old and new value.*/
    callback: function (event) { 
        //event               - event object
        //event.attributeName - Name of the attribute modified
        //event.oldValue      - Previous value of the modified attribute
        //event.newValue      - New value of the modified attribute
        //Triggered when the selected elements attribute is added/updated/removed
    }        
});

Saving numpy array to txt file row wise

An alternative answer is to reshape the array so that it has dimensions (1, N) like so:

savetext(filename, a.reshape(1, a.shape[0]))

Producer/Consumer threads using a Queue

Use this typesafe pattern with poison pills:

public sealed interface BaseMessage {

    final class ValidMessage<T> implements BaseMessage {

        @Nonnull
        private final T value;


        public ValidMessage(@Nonnull T value) {
            this.value = value;
        }

        @Nonnull
        public T getValue() {
            return value;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            ValidMessage<?> that = (ValidMessage<?>) o;
            return value.equals(that.value);
        }

        @Override
        public int hashCode() {
            return Objects.hash(value);
        }

        @Override
        public String toString() {
            return "ValidMessage{value=%s}".formatted(value);
        }
    }

    final class PoisonedMessage implements BaseMessage {

        public static final PoisonedMessage INSTANCE = new PoisonedMessage();


        private PoisonedMessage() {
        }

        @Override
        public String toString() {
            return "PoisonedMessage{}";
        }
    }
}

public class Producer implements Callable<Void> {

    @Nonnull
    private final BlockingQueue<BaseMessage> messages;

    Producer(@Nonnull BlockingQueue<BaseMessage> messages) {
        this.messages = messages;
    }

    @Override
    public Void call() throws Exception {
        messages.put(new BaseMessage.ValidMessage<>(1));
        messages.put(new BaseMessage.ValidMessage<>(2));
        messages.put(new BaseMessage.ValidMessage<>(3));
        messages.put(BaseMessage.PoisonedMessage.INSTANCE);
        return null;
    }
}

public class Consumer implements Callable<Void> {

    @Nonnull
    private final BlockingQueue<BaseMessage> messages;

    private final int maxPoisons;


    public Consumer(@Nonnull BlockingQueue<BaseMessage> messages, int maxPoisons) {
        this.messages = messages;
        this.maxPoisons = maxPoisons;
    }

    @Override
    public Void call() throws Exception {
        int poisonsReceived = 0;
        while (poisonsReceived < maxPoisons && !Thread.currentThread().isInterrupted()) {
            BaseMessage message = messages.take();
            if (message instanceof BaseMessage.ValidMessage<?> vm) {
                Integer value = (Integer) vm.getValue();
                System.out.println(value);
            } else if (message instanceof BaseMessage.PoisonedMessage) {
                ++poisonsReceived;
            } else {
                throw new IllegalArgumentException("Invalid BaseMessage type: " + message);
            }
        }
        return null;
    }
}

Equivalent of Math.Min & Math.Max for Dates?

public static class DateTool
{
    public static DateTime Min(DateTime x, DateTime y)
    {
        return (x.ToUniversalTime() < y.ToUniversalTime()) ? x : y;
    }
    public static DateTime Max(DateTime x, DateTime y)
    {
        return (x.ToUniversalTime() > y.ToUniversalTime()) ? x : y;
    }
}

This allows the dates to have different 'kinds' and returns the instance that was passed in (not returning a new DateTime constructed from Ticks or Milliseconds).

[TestMethod()]
    public void MinTest2()
    {
        DateTime x = new DateTime(2001, 1, 1, 1, 1, 2, DateTimeKind.Utc);
        DateTime y = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Local);

        //Presumes Local TimeZone adjustment to UTC > 0
        DateTime actual = DateTool.Min(x, y);
        Assert.AreEqual(x, actual);
    }

Note that this test would fail East of Greenwich...

Join String list elements with a delimiter in one step

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

The Network Adapter could not establish the connection when connecting with Oracle DB

Take a look at this post on Java Ranch:

http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could

"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."

Managing jQuery plugin dependency in webpack

This works for me on the webpack.config.js

    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    }),

in another javascript or into HTML add:

global.jQuery = require('jquery');

Removing unwanted table cell borders with CSS

After trying the above suggestions, the only thing that worked for me was changing the border attribute to "0" in the following sections of a child theme's style.css (do a "Find" operation to locate each one -- the following are just snippets):

.comment-content table {
    border-bottom: 1px solid #ddd;

.comment-content td {
    border-top: 1px solid #ddd;
    padding: 6px 10px 6px 0;
}

Thus looking like this afterwards:

.comment-content table {
    border-bottom: 0;

.comment-content td {
    border-top: 0;
    padding: 6px 10px 6px 0;
}

JavaScript OR (||) variable assignment explanation

Return output first true value.

If all are false return last false value.

Example:-

  null || undefined || false || 0 || 'apple'  // Return apple

how to File.listFiles in alphabetical order?

In Java 8:

Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));

Reverse order:

Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));

How do I get the currently-logged username from a Windows service in .NET?

ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem") solution worked fine for me. BUT it does not work if the service is started over a Remote Desktop Connection. To work around this, we can ask for the username of the owner of an interactive process that always is running on a PC: explorer.exe. This way, we always get the currently Windows logged-in username from our Windows service:

foreach (System.Management.ManagementObject Process in Processes.Get())
{
    if (Process["ExecutablePath"] != null && 
        System.IO.Path.GetFileName(Process["ExecutablePath"].ToString()).ToLower() == "explorer.exe" )
    {
        string[] OwnerInfo = new string[2];
        Process.InvokeMethod("GetOwner", (object[])OwnerInfo);

        Console.WriteLine(string.Format("Windows Logged-in Interactive UserName={0}", OwnerInfo[0]));

        break;
    }
}

npm check and update package if needed

  • To update a single local package:

    1. First find out your outdated packages:

      npm outdated

    2. Then update the package or packages that you want manually as:

      npm update --save package_name

This way it is not necessary to update your local package.json file.

Note that this will update your package to the latest version.

  • If you write some version in your package.json file and do:

    npm update package_name

    In this case you will get just the next stable version (wanted) regarding the version that you wrote in your package.json file.

And with npm list (package_name) you can find out the current version of your local packages.

How to use if, else condition in jsf to display image

Instead of using the "c" tags, you could also do the following:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?

Reference - What does this error mean in PHP?

Warning: [function]: failed to open stream: [reason]

It happens when you call a file usually by include, require or fopen and PHP couldn't find the file or have not enough permission to load the file.

This can happen for a variety of reasons :

  • the file path is wrong
  • the file path is relative
  • include path is wrong
  • permissions are too restrictive
  • SELinux is in force
  • and many more ...

One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like __DIR__ or dirname(__FILE__):

include __DIR__ . '/inc/globals.inc.php';

or:

require dirname(__FILE__) . '/inc/globals.inc.php';

Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.

The best way to solve this problem quickly is to follow the troubleshooting checklist below.

Related Questions:

Related Errors:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

In your JSOn file, please make below change.

 {
    "data":
    [
      {
        "id": 1,
        "name": "Safa",
        "email": "[email protected]",
        "purpose": "thesis",
        "programme": "Software Engineering",
        "year": 2016,
        "language": "Estonian",
        "comments": "In need of correcting a dangling participle.",
        "status": "RECEIVED"
      },
      {
        "id": 2,
        "name": "Safa",
        "email": "[email protected]",
        "purpose": "thesis",
        "programme": "Software Engineering",
        "year": 2016,
        "language": "Estonian",
        "comments": "In need of correcting a dangling participle.",
        "status": "RECEIVED"
      },
      {
        "id": 3,
        "name": "Salman",
        "email": "[email protected]",
        "purpose": "thesis",
        "programme": "Software Engineering",
        "year": 2016,
        "language": "Estonian",
        "comments": "In need of correcting a dangling participle.",
        "status": "RECEIVED"
      }
    ]
    }

And after that:

 this.http.get(url).map(res:Response) => res.json().data);

The data is actually the name of tge collection of json file. Please try the code above, I am sure it will work.

Jquery change background color

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

The .queue() function waits for running animations to run out and then fires whatever's in the supplied function.

Is there a code obfuscator for PHP?

Thicket™ Obfuscator for PHP

The PHP Obfuscator tool scrambles PHP source code to make it very difficult to understand or reverse-engineer (example). This provides significant protection for source code intellectual property that must be hosted on a website or shipped to a customer. It is a member of SD's family of Source Code Obfuscators.

How can I enable the MySQLi extension in PHP 7?

sudo phpenmod mysqli
sudo service apache2 restart

  • phpenmod moduleName enables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • phpdismod moduleName disables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • php -m lists the loaded modules

bypass invalid SSL certificate in .net core

I faced off the same problem when working with self-signed certs and client cert auth on .NET Core 2.2 and Docker Linux containers. Everything worked fine on my dev Windows machine, but in Docker I got such error:

System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure

Fortunately, the certificate was generated using a chain. Of course, you can always ignore this solution and use the above solutions.

So here is my solution:

  1. I saved the certificate using Chrome on my computer in P7B format.

  2. Convert certificate to PEM format using this command:
    openssl pkcs7 -inform DER -outform PEM -in <cert>.p7b -print_certs > ca_bundle.crt

  3. Open the ca_bundle.crt file and delete all Subject recordings, leaving a clean file. Example below:

    -----BEGIN CERTIFICATE-----
    _BASE64 DATA_
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    _BASE64 DATA_
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    _BASE64 DATA_
    -----END CERTIFICATE-----
  1. Put these lines to the Dockerfile (in the final steps):
    # Update system and install curl and ca-certificates
    RUN apt-get update && apt-get install -y curl && apt-get install -y ca-certificates
    # Copy your bundle file to the system trusted storage
    COPY ./ca_bundle.crt /usr/local/share/ca-certificates/ca_bundle.crt
    # During docker build, after this line you will get such output: 1 added, 0 removed; done.
    RUN update-ca-certificates
  1. In the app:
    var address = new EndpointAddress("https://serviceUrl");                
    var binding = new BasicHttpsBinding
    {
        CloseTimeout = new TimeSpan(0, 1, 0),
        OpenTimeout = new TimeSpan(0, 1, 0),
        ReceiveTimeout = new TimeSpan(0, 1, 0),
        SendTimeout = new TimeSpan(0, 1, 0),
        MaxBufferPoolSize = 524288,
        MaxBufferSize = 65536,
        MaxReceivedMessageSize = 65536,
        TextEncoding = Encoding.UTF8,
        TransferMode = TransferMode.Buffered,
        UseDefaultWebProxy = true,
        AllowCookies = false,
        BypassProxyOnLocal = false,
        ReaderQuotas = XmlDictionaryReaderQuotas.Max,
        Security =
        {
            Mode = BasicHttpsSecurityMode.Transport,
            Transport = new HttpTransportSecurity
            {
                ClientCredentialType = HttpClientCredentialType.Certificate,
                ProxyCredentialType = HttpProxyCredentialType.None
            }
        }
    };
    var client = new MyWSClient(binding, address);
    client.ClientCredentials.ClientCertificate.Certificate = GetClientCertificate("clientCert.pfx", "passwordForClientCert");
    // Client certs must be installed
    client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication
    {
        CertificateValidationMode = X509CertificateValidationMode.ChainTrust,
        TrustedStoreLocation = StoreLocation.LocalMachine,
        RevocationMode = X509RevocationMode.NoCheck
    };

GetClientCertificate method:

private static X509Certificate2 GetClientCertificate(string clientCertName, string password)
{
    //Create X509Certificate2 object from .pfx file
    byte[] rawData = null;
    using (var f = new FileStream(Path.Combine(AppContext.BaseDirectory, clientCertName), FileMode.Open, FileAccess.Read))
    {
        var size = (int)f.Length;
        var rawData = new byte[size];
        f.Read(rawData, 0, size);
        f.Close();
    }
    return new X509Certificate2(rawData, password);
}

How to change the color of progressbar in C# .NET 3.5?

I know its way too old to be answered now.. but still, a small tweak to @Daniel's answer for rectifying the problem of not showing zero valued progress bar. Just draw the Progress only if the inner rectangle's width is found to be non-zero.

Thanks to all the contributers.

        public class ProgressBarEx : ProgressBar
        {
            public ProgressBarEx()
            {
                this.SetStyle(ControlStyles.UserPaint, true);
            }

            protected override void OnPaintBackground(PaintEventArgs pevent){}
                // None... Helps control the flicker.                

            protected override void OnPaint(PaintEventArgs e)
            {
                const int inset = 2; // A single inset value to control teh sizing of the inner rect.

                using (Image offscreenImage = new Bitmap(this.Width, this.Height))
                {
                    using (Graphics offscreen = Graphics.FromImage(offscreenImage))
                    {
                        Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);

                        if (ProgressBarRenderer.IsSupported)
                            ProgressBarRenderer.DrawHorizontalBar(offscreen, rect);

                        rect.Inflate(new Size(-inset, -inset)); // Deflate inner rect.
                        rect.Width = (int)(rect.Width * ((double)this.Value / this.Maximum));

                        if (rect.Width != 0)
                        {
                            LinearGradientBrush brush = new LinearGradientBrush(rect, this.ForeColor, this.BackColor, LinearGradientMode.Vertical);
                            offscreen.FillRectangle(brush, inset, inset, rect.Width, rect.Height);
                            e.Graphics.DrawImage(offscreenImage, 0, 0);
                            offscreenImage.Dispose();
                        }
                    }
                }
            }
        }

Check if string contains only whitespace

Use the str.isspace() method:

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

Combine that with a special case for handling the empty string.

Alternatively, you could use str.strip() and check if the result is empty.

How to validate an email address in JavaScript

One of my coworker shared this regex with me. I like it a lot.

function isValidEmailAddress (email) {
    var validEmail = false;
    if (email) {
        email = email.trim().toLowerCase();
        var pattern = /^[\w-']+(\.[\w-']+)*@([a-zA-Z0-9]+[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*?\.[a-zA-Z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/;
        validEmail = pattern.exec(email);
    }

    return validEmail;
}

if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };
}

jquery UI dialog: how to initialize without a title bar?

I believe you can hide it with CSS:

.ui-dialog-titlebar {
    display: none;
}

Alternatively, you can apply this to specific dialogs with the dialogClass option:

$( "#createUserDialog" ).dialog({
    dialogClass: "no-titlebar"
});
.no-titlebar .ui-dialog-titlebar {
    display: none;
}

Check out "Theming" the Dialog. The above suggestion makes use of the dialogClass option, which appears to be on it's way out in favor of a new method.

Disable form autofill in Chrome without disabling autocomplete

Autofill works with name attribute of the input, so if you set a name for an input like "firstname", chrome will fill it.

If you want to disable it, use an odd name like "supermanname".

Javascript can't solve your problem.

Second solution: You can make your inputs hidden with the same names, and set their values with other inputs. I simplified the Js with jQUery.

<form action="handlerfile.php" method="post">
<input type="text" id="1" onclick="$("#2").val($("#1").val())"/>
<input type="hidden" name="username" id="2">
</form>

Questions every good Java/Java EE Developer should be able to answer?

Write a program to accept two integers and output the largest of two numbers to a file at a location of your choice. Now describe what each statement does.

It's possible to drill down pretty deep starting from the significance of the import statement, right down to abnormal termination

SQL Server 2008 - Case / If statements in SELECT Clause

CASE is the answer, but you will need to have a separate case statement for each column you want returned. As long as the WHERE clause is the same, there won't be much benefit separating it out into multiple queries.

Example:

SELECT
    CASE @var
        WHEN 'xyz' THEN col1
        WHEN 'zyx' THEN col2
        ELSE col7
    END,
    CASE @var
        WHEN 'xyz' THEN col2
        WHEN 'zyx' THEN col3
        ELSE col8
    END
FROM Table
...

How to read/write a boolean when implementing the Parcelable interface?

I normally have them in an array and call writeBooleanArray and readBooleanArray

If it's a single boolean you need to pack, you could do this:

parcel.writeBooleanArray(new boolean[] {myBool});

Get selected value in dropdown list using JavaScript

The previous answers still leave room for improvement because of the possibilities, the intuitiveness of the code, and the use of id versus name. One can get a read-out of three data of a selected option -- its index number, its value and its text. This simple, cross-browser code does all three:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo GetSelectOptionData</title>
</head>
<body>
    <form name="demoForm">
        <select name="demoSelect" onchange="showData()">
            <option value="zilch">Select:</option>
            <option value="A">Option 1</option>
            <option value="B">Option 2</option>
            <option value="C">Option 3</option>
        </select>
    </form>

    <p id="firstP">&nbsp;</p>
    <p id="secondP">&nbsp;</p>
    <p id="thirdP">&nbsp;</p>

    <script>
    function showData() {
        var theSelect = demoForm.demoSelect;
        var firstP = document.getElementById('firstP');
        var secondP = document.getElementById('secondP');
        var thirdP = document.getElementById('thirdP');
        firstP.innerHTML = ('This option\'s index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
        secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
        thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
    }
     </script>
</body>
</html>

Live demo: http://jsbin.com/jiwena/1/edit?html,output .

id should be used for make-up purposes. For functional form purposes, name is still valid, also in HTML5, and should still be used. Lastly, mind the use of square versus round brackets in certain places. As was explained before, only (older versions of) Internet Explorer will accept round ones in all places.

SQL Server - Case Statement

The query can be written slightly simpler, like this:

DECLARE @T INT = 2 

SELECT CASE 
         WHEN @T < 1 THEN 'less than one' 
         WHEN @T = 1 THEN 'one' 
         ELSE 'greater than one' 
       END T

Print to standard printer from Python?

To print to any printer on the network you can send a PJL/PCL print job directly to a network printer on port 9100.

Please have a look at the below link that should give a good start:

http://frank.zinepal.com/printing-directly-to-a-network-printer

Also, If there is a way to call Windows cmd you can use FTP put to print your page on 9100. Below link should give you details, I have used this method for HP printers but I believe it will work for other printers.

http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?objectID=bpj06165

Update records using LINQ

I assume person_id is the primary key of Person table, so here's how you update a single record:

Person result = (from p in Context.Persons
              where p.person_id == 5
              select p).SingleOrDefault();

result.is_default = false;

Context.SaveChanges();

and here's how you update multiple records:

List<Person> results = (from p in Context.Persons
                        where .... // add where condition here
                        select p).ToList();

foreach (Person p in results)
{
    p.is_default = false;
}

Context.SaveChanges();

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

CSS


input
{
    width: 300px;
    height: 40px;
} 

HTML


<textarea rows="4" cols="50">HELLO</textarea>

Calling a Javascript Function from Console

This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].

I wasn't able to run functions from the Developer Tools console, but I then found this

https://developer.mozilla.org/en-US/docs/Tools/Scratchpad

and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.

I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).

https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn

Image 1 (Firefox): http://imgur.com/a/ofkOp

enter image description here

Image 2 (Chrome): http://imgur.com/a/dLnRX

enter image description here

Difference between Visual Basic 6.0 and VBA

Actually VBA can be used to compile DLLs. The Office 2000 and Office XP Developer editions included a VBA editor that could be used for making DLLs for use as COM Addins.

This functionality was removed in later versions (2003 and 2007) with the advent of the VSTO (VS Tools for Office) software, although obviously you could still create COM addins in a similar fashion without the use of VSTO (or VS.Net) by using VB6 IDE.

How to clear browsing history using JavaScript?

to disable back function of the back button:

window.addEventListener('popstate', function (event) {
  history.pushState(null, document.title, location.href);
});

Visual Studio Code Search and Replace with Regular Expressions

Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

I had this issue in VS 2015. The following solved it for me:

Find "webpages:Version" in the appsettings and update it to version 3.0.0.0. My web.config had

<add key="webpages:Version" value="2.0.0.0" />

and I updated it to

<add key="webpages:Version" value="3.0.0.0" />

Converting dict to OrderedDict

Most of the time we go for OrderedDict when we required a custom order not a generic one like ASC etc.

Here is the proposed solution:

import collections
ship = {"NAME": "Albatross",
         "HP":50,
         "BLASTERS":13,
         "THRUSTERS":18,
         "PRICE":250}

ship = collections.OrderedDict(ship)

print ship


new_dict = collections.OrderedDict()
new_dict["NAME"]=ship["NAME"]
new_dict["HP"]=ship["HP"]
new_dict["BLASTERS"]=ship["BLASTERS"]
new_dict["THRUSTERS"]=ship["THRUSTERS"]
new_dict["PRICE"]=ship["PRICE"]


print new_dict

This will be output:

OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
OrderedDict([('NAME', 'Albatross'), ('HP', 50), ('BLASTERS', 13), ('THRUSTERS', 18), ('PRICE', 250)])

Note: The new sorted dictionaries maintain their sort order when entries are deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.(official doc)

How to call a PHP file from HTML or Javascript

As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:

$.post("yourfile.php", {data : "This can be as long as you want"});

And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.

How can I store the result of a system command in a Perl variable?

Use backticks for system commands, which helps to store their results into Perl variables.

my $pid = 5892;
my $not = ``top -H -p $pid -n 1 | grep myprocess | wc -l`; 
print "not = $not\n";

What is the meaning of ToString("X2")?

It formats the string as two uppercase hexadecimal characters.

In more depth, the argument "X2" is a "format string" that tells the ToString() method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.

byte.ToString() without any arguments returns the number in its natural decimal representation, with no padding.

Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString() methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString().

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

How to check if anonymous object has a method?

You want hasOwnProperty():

_x000D_
_x000D_
var myObj1 = { _x000D_
 prop1: 'no',_x000D_
 prop2: function () { return false; }_x000D_
}_x000D_
var myObj2 = { _x000D_
 prop1: 'no'_x000D_
}_x000D_
_x000D_
console.log(myObj1.hasOwnProperty('prop2')); // returns true_x000D_
console.log(myObj2.hasOwnProperty('prop2')); // returns false_x000D_
 
_x000D_
_x000D_
_x000D_

References: Mozilla, Microsoft, phrogz.net.

Laravel 5 – Remove Public from URL

Here is the Best and shortest solution that works for me as of may, 2018 for Laravel 5.5

  1. just cut your .htaccess file from the /public directory to the root directory and replace it content with the following code:

    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
           Options -MultiViews
        </IfModule>
    
        RewriteEngine On
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)/$ /$1 [L,R=301]
    
        RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ server.php [L]
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_URI} !^/public/
        RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
    </IfModule>
    
  2. Just save the .htaccess file and that is all.

  3. Rename your server.php file to index.php. that is all enjoy!

Is Unit Testing worth the effort?

For years, I've tried to convince people that they needed to write unit test for their code. Whether they wrote the tests first (as in TDD) or after they coded the functionality, I always tried to explain them all the benefits of having unit tests for code. Hardly anyone disagreed with me. You cannot disagree with something that is obvious, and any smart person will see the benefits of unit test and TDD.

The problem with unit testing is that it requires a behavioral change, and it is very hard to change people's behavior. With words, you will get a lot of people to agree with you, but you won't see many changes in the way they do things.

You have to convince people by doing. Your personal success will atract more people than all the arguments you may have. If they see you are not just talking about unit test or TDD, but you are doing what you preach, and you are successful, people will try to imitate you.

You should also take on a lead role because no one writes unit test right the first time, so you may need to coach them on how to do it, show them the way, and the tools available to them. Help them while they write their first tests, review the tests they write on their own, and show them the tricks, idioms and patterns you've learned through your own experiences. After a while, they will start seeing the benefits on their own, and they will change their behavior to incorporate unit tests or TDD into their toolbox.

Changes won't happen over night, but with a little of patience, you may achieve your goal.

Git reset single file in feature branch to be the same as in master

If you want to revert the file to its state in master:

git checkout origin/master [filename]

Why calling react setState method doesn't mutate the state immediately?

Simply putting - this.setState({data: value}) is asynchronous in nature that means it moves out of the Call Stack and only comes back to the Call Stack unless it is resolved.

Please read about Event Loop to have a clear picture about Asynchronous nature in JS and why it takes time to update -

https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4

Hence -

    this.setState({data:value});
    console.log(this.state.data); // will give undefined or unupdated value

as it takes time to update. To achieve the above process -

    this.setState({data:value},function () {
     console.log(this.state.data);
    });

Fixed digits after decimal with f-strings

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

When using a Settings.settings file in .NET, where is the config actually stored?

I know it's already answered but couldn't you just synchronize the settings in the settings designer to move back to your default settings?

How do I install a NuGet package .nupkg file locally?

You can also use the Package Manager Console and invoke the Install-Package cmdlet by specifying the path to the directory that contains the package file in the -Source parameter:

Install-Package SomePackage -Source C:\PathToThePackageDir\

Add line break to 'git commit -m' from the command line

If you just want, say, a head line and a content line, you can use:

git commit -m "My head line" -m "My content line."

Note that this creates separate paragraphs - not lines. So there will be a blank line between each two -m lines, e.g.:

My head line

My content line.

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

You need to link the with the -lm linker option

You need to compile as

gcc test.c  -o test -lm

gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm. To link with these functions you have to advise the linker to include the library -l linker option followed by the library name m thus -lm.

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

Sort array of objects by object fields

If you need local based string comparison, you can use strcoll instead of strcmp.

Remeber to first use setlocale with LC_COLLATE to set locale information if needed.

  usort($your_data,function($a,$b){
    setlocale (LC_COLLATE, 'pl_PL.UTF-8'); // Example of Polish language collation
    return strcoll($a->name,$b->name);
  });

Why do I get PLS-00302: component must be declared when it exists?

You can get that error if you have an object with the same name as the schema. For example:

create sequence s2;

begin
  s2.a;
end;
/

ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored

When you refer to S2.MY_FUNC2 the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2 there is no confusion, so it works.

The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.

It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.

select owner, object_type, object_name
from all_objects
where object_name = 'S2';

Can I set state inside a useEffect hook

? 1. Can I set state inside a useEffect hook?

In principle, you can set state freely where you need it - including inside useEffect and even during rendering. Just make sure to avoid infinite loops by settting Hook deps properly and/or state conditionally.


? 2. Lets say I have some state that is dependent on some other state. Is it appropriate to create a hook that observes A and sets B inside the useEffect hook?

You just described the classic use case for useReducer:

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. (React docs)

When setting a state variable depends on the current value of another state variable, you might want to try replacing them both with useReducer. [...] When you find yourself writing setSomething(something => ...), it’s a good time to consider using a reducer instead. (Dan Abramov, Overreacted blog)

_x000D_
_x000D_
let MyComponent = () => {_x000D_
  let [state, dispatch] = useReducer(reducer, { a: 1, b: 2 });_x000D_
_x000D_
  useEffect(() => {_x000D_
    console.log("Some effect with B");_x000D_
  }, [state.b]);_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>A: {state.a}, B: {state.b}</p>_x000D_
      <button onClick={() => dispatch({ type: "SET_A", payload: 5 })}>_x000D_
        Set A to 5 and Check B_x000D_
      </button>_x000D_
      <button onClick={() => dispatch({ type: "INCREMENT_B" })}>_x000D_
        Increment B_x000D_
      </button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
// B depends on A. If B >= A, then reset B to 1._x000D_
function reducer(state, { type, payload }) {_x000D_
  const someCondition = state.b >= state.a;_x000D_
_x000D_
  if (type === "SET_A")_x000D_
    return someCondition ? { a: payload, b: 1 } : { ...state, a: payload };_x000D_
  else if (type === "INCREMENT_B") return { ...state, b: state.b + 1 };_x000D_
  return state;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect } = React</script>
_x000D_
_x000D_
_x000D_


? 3. Will the effects cascade such that, when I click the button, the first effect will fire, causing b to change, causing the second effect to fire, before the next render?

useEffect always runs after the render is committed and DOM changes are applied. The first effect fires, changes b and causes a re-render. After this render has completed, second effect will run due to b changes.

_x000D_
_x000D_
let MyComponent = props => {_x000D_
  console.log("render");_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
_x000D_
  let isFirstRender = useRef(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect a, value:", a);_x000D_
    if (isFirstRender.current) isFirstRender.current = false;_x000D_
    else setB(3);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect a, value:", a);_x000D_
    };_x000D_
  }, [a]);_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
    };_x000D_
  }, [b]);_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>a: {a}, b: {b}</p>_x000D_
      <button_x000D_
        onClick={() => {_x000D_
          console.log("Clicked!");_x000D_
          setA(5);_x000D_
        }}_x000D_
      >_x000D_
        click me_x000D_
      </button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_


? 4. Are there any performance downsides to structuring code like this?

Yes. By wrapping the state change of b in a separate useEffect for a, the browser has an additional layout/paint phase - these effects are potentially visible for the user. If there is no way you want give useReducer a try, you could change b state together with a directly:

_x000D_
_x000D_
let MyComponent = () => {_x000D_
  console.log("render");_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
    };_x000D_
  }, [b]);_x000D_
_x000D_
  const handleClick = () => {_x000D_
    console.log("Clicked!");_x000D_
    setA(5);_x000D_
    b >= 5 ? setB(1) : setB(b + 1);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>_x000D_
        a: {a}, b: {b}_x000D_
      </p>_x000D_
      <button onClick={handleClick}>click me</button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_

Is Java a Compiled or an Interpreted programming language ?

Java implementations typically use a two-step compilation process. Java source code is compiled down to bytecode by the Java compiler. The bytecode is executed by a Java Virtual Machine (JVM). Modern JVMs use a technique called Just-in-Time (JIT) compilation to compile the bytecode to native instructions understood by hardware CPU on the fly at runtime.

Some implementations of JVM may choose to interpret the bytecode instead of JIT compiling it to machine code, and running it directly. While this is still considered an "interpreter," It's quite different from interpreters that read and execute the high level source code (i.e. in this case, Java source code is not interpreted directly, the bytecode, output of Java compiler, is.)

It is technically possible to compile Java down to native code ahead-of-time and run the resulting binary. It is also possible to interpret the Java code directly.

To summarize, depending on the execution environment, bytecode can be:

  • compiled ahead of time and executed as native code (similar to most C++ compilers)
  • compiled just-in-time and executed
  • interpreted
  • directly executed by a supported processor (bytecode is the native instruction set of some CPUs)

How to edit/save a file through Ubuntu Terminal

Open the file using vi or nano. and then press " i " ,

For save and quit

  Enter Esc    

and write the following command

  :wq

without save and quit

  :q!

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

The best way I have found to get a feel for things like this is to try them out:

import java.io.File;
public class PathTesting {
    public static void main(String [] args) {
        File f = new File("test/.././file.txt");
        System.out.println(f.getPath());
        System.out.println(f.getAbsolutePath());
        try {
            System.out.println(f.getCanonicalPath());
        }
        catch(Exception e) {}
    }
}

Your output will be something like:

test\..\.\file.txt
C:\projects\sandbox\trunk\test\..\.\file.txt
C:\projects\sandbox\trunk\file.txt

So, getPath() gives you the path based on the File object, which may or may not be relative; getAbsolutePath() gives you an absolute path to the file; and getCanonicalPath() gives you the unique absolute path to the file. Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path.

When to use each? Depends on what you're trying to accomplish, but if you were trying to see if two Files are pointing at the same file on disk, you could compare their canonical paths. Just one example.

What is a database transaction?

A transaction is a way of representing a state change. Transactions ideally have four properties, commonly known as ACID:

  • Atomic (if the change is committed, it happens in one fell swoop; you can never see "half a change")
  • Consistent (the change can only happen if the new state of the system will be valid; any attempt to commit an invalid change will fail, leaving the system in its previous valid state)
  • Isolated (no-one else sees any part of the transaction until it's committed)
  • Durable (once the change has happened - if the system says the transaction has been committed, the client doesn't need to worry about "flushing" the system to make the change "stick")

See the Wikipedia ACID entry for more details.

Although this is typically applied to databases, it doesn't have to be. (In particular, see Software Transactional Memory.)

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

jQuery .attr("disabled", "disabled") not working in Chrome

For me, none of these answers worked, but I finally found one that did.

I needed this for IE-

$('input:text').attr("disabled", 'disabled');

I also had to add this for Chrome and Firefox -

$('input:text').AddClass("notactive");

and this -

<style type="text/css">
    .notactive {
        pointer-events: none;
        cursor: default;
    }
 </style>

Difference between <input type='button' /> and <input type='submit' />

<input type="button" /> buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.

<input type="submit"> buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.

How to save RecyclerView's scroll position using RecyclerView.State?

I Set variables in onCreate(), save scroll position in onPause() and set scroll position in onResume()

public static int index = -1;
public static int top = -1;
LinearLayoutManager mLayoutManager;

@Override
public void onCreate(Bundle savedInstanceState)
{
    //Set Variables
    super.onCreate(savedInstanceState);
    cRecyclerView = ( RecyclerView )findViewById(R.id.conv_recycler);
    mLayoutManager = new LinearLayoutManager(this);
    cRecyclerView.setHasFixedSize(true);
    cRecyclerView.setLayoutManager(mLayoutManager);

}

@Override
public void onPause()
{
    super.onPause();
    //read current recyclerview position
    index = mLayoutManager.findFirstVisibleItemPosition();
    View v = cRecyclerView.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - cRecyclerView.getPaddingTop());
}

@Override
public void onResume()
{
    super.onResume();
    //set recyclerview position
    if(index != -1)
    {
        mLayoutManager.scrollToPositionWithOffset( index, top);
    }
}

Auto refresh code in HTML using meta tags

It looks like you probably pasted this (or used a word processor like MS Word) using a kind of double-quotes that are not recognized by the browser. Please check that your code uses actual double-quotes like this one ", which is different from the following character:

Replace the meta tag with this one and try again:

<meta http-equiv="refresh" content="5" >

Should I put input elements inside a label element?

Behavior difference: clicking in the space between label and input

If you click on the space between the label and the input it activates the input only if the label contains the input.

This makes sense since in this case the space is just another character of the label.

_x000D_
_x000D_
<p>Inside:</p>_x000D_
_x000D_
<label>_x000D_
  <input type="checkbox" />_x000D_
  |&lt;----- Label. Click between me and the checkbox._x000D_
</label>_x000D_
_x000D_
<p>Outside:</p>_x000D_
_x000D_
<input type="checkbox" id="check" />_x000D_
<label for="check">|&lt;----- Label. Click between me and the checkbox.</label>
_x000D_
_x000D_
_x000D_

Being able to click between label and box means that it is:

  • easier to click
  • less clear where things start and end

Bootstrap checkbox v3.3 examples use the input inside: http://getbootstrap.com/css/#forms Might be wise to follow them. But they changed their minds in v4.0 https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios so I don't know what is wise anymore:

Checkboxes and radios use are built to support HTML-based form validation and provide concise, accessible labels. As such, our <input>s and <label>s are sibling elements as opposed to an <input> within a <label>. This is slightly more verbose as you must specify id and for attributes to relate the <input> and <label>.

UX question that discusses this point in detail: https://ux.stackexchange.com/questions/23552/should-the-space-between-the-checkbox-and-label-be-clickable

PHP Get Highest Value from Array

Here a solution inside an exercise:

function high($sentence)
{
    $alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    $alphabet = array_flip($alphabet);

    $words = explode(" ", $sentence);

    foreach ($words as $word) {
        $letters = str_split($word);
        $points = 0;
        foreach ($letters as $letter)
            $points += $alphabet[$letter];
        $score[$word] = $points;
    }

    $value = max($score);
    $key = array_search($value, $score);

    return $key;
}

echo high("what time are we climbing up the volcano");

How do I properly compare strings in C?

Welcome to the concept of the pointer. Generations of beginning programmers have found the concept elusive, but if you wish to grow into a competent programmer, you must eventually master this concept — and moreover, you are already asking the right question. That's good.

Is it clear to you what an address is? See this diagram:

----------     ----------
| 0x4000 |     | 0x4004 |
|    1   |     |    7   |
----------     ----------

In the diagram, the integer 1 is stored in memory at address 0x4000. Why at an address? Because memory is large and can store many integers, just as a city is large and can house many families. Each integer is stored at a memory location, as each family resides in a house. Each memory location is identified by an address, as each house is identified by an address.

The two boxes in the diagram represent two distinct memory locations. You can think of them as if they were houses. The integer 1 resides in the memory location at address 0x4000 (think, "4000 Elm St."). The integer 7 resides in the memory location at address 0x4004 (think, "4004 Elm St.").

You thought that your program was comparing the 1 to the 7, but it wasn't. It was comparing the 0x4000 to the 0x4004. So what happens when you have this situation?

----------     ----------
| 0x4000 |     | 0x4004 |
|    1   |     |    1   |
----------     ----------

The two integers are the same but the addresses differ. Your program compares the addresses.

How to pass parameters to a modal?

To pass the parameter you need to use resolve and inject the items in controller

$scope.Edit = function (Id) {
   var modalInstance = $modal.open({
      templateUrl: '/app/views/admin/addeditphone.html',
      controller: 'EditCtrl',
      resolve: {
         editId: function () {
           return Id;
         }
       }
    });
}

Now if you will use like this:

app.controller('EditCtrl', ['$scope', '$location'
       , function ($scope, $location, editId)

in this case editId will be undefined. You need to inject it, like this:

app.controller('EditCtrl', ['$scope', '$location', 'editId'
     , function ($scope, $location, editId)

Now it will work smooth, I face the same problem many time, once injected, everything start working!

Convert hex color value ( #ffffff ) to integer value

I have the same problem that I found some color in form of #AAAAAA and I want to conver that into a form that android could make use of. I found that you can just use 0xFFAAAAAA so that android could automatically tell the color. Notice the first FF is telling alpha value. Hope it helps

Drop primary key using script in SQL Server database

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

How do I set up CLion to compile and run?

I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.

The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.

SHORT ANSWER (should be similar for MinGW too but I haven't tried it):

  1. Install Cygwin with GCC, G++, GDB and CMake (the required versions)
  2. Add full path to Cygwin 'bin' directory to Windows Environment variables
  3. Restart CLion and check 'Settings' -> 'Build, Execution, Deployment' to make sure CLion has picked up the right versions of Cygwin, make and gdb
  4. Check the project configuration ('Run' -> 'Edit configuration') to make sure your project name appears there and you can select options in 'Target', 'Configuration' and 'Executable' fields.
  5. Build and then Run
  6. Enjoy

LONG ANSWER:

Below are the detailed steps that solved this issue for me:

  1. Uninstall/delete the previous version of Cygwin (MinGW in your case)

  2. Make sure that CLion is up-to-date

  3. Run Cygwin setup (x64 for my 64-bit OS)

  4. Install at least the following packages for Cygwin: gcc g++ make Cmake gdb Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).

  5. Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows

[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']

  1. Add the 'bin' folder to the Path variable. For Cygwin, I added: D:\cygwin64\bin

  2. Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings

  3. Select 'Build, Execution, Deployment' and then click on 'Toolchains'

  4. Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)

  5. For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)

  6. 'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]

  7. Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'

See screenshot: Check all paths to the compiler, make and gdb

  1. Now go to 'Run' -> 'Edit configuration'. You should see your project name in the left-side panel and the configurations on the right side

See screenshot: Check the configuration to run the project

  1. There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active

  2. Build your project and then run the project. You should see the output in the terminal window

Hope this helps! Good luck and enjoy CLion.

How can I get a Dialog style activity window to fill the screen?

Set a minimum width at the top most layout.

android:minWidth="300dp"

For example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
  xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="300dp">

<!-- Put remaining contents here -->

</LinearLayout>

Is it possible to start activity through adb shell?

For example this will start XBMC:

adb shell am start -a android.intent.action.MAIN -n org.xbmc.xbmc/android.app.NativeActivity

(More general answers are already posted, but I missed a nice example here.)

GDB: break if variable equal value

You can use a watchpoint for this (A breakpoint on data instead of code).

You can start by using watch i.
Then set a condition for it using condition <breakpoint num> i == 5

You can get the breakpoint number by using info watch

How do I split a string on a delimiter in Bash?

you can apply awk to many situations

echo "[email protected];[email protected]"|awk -F';' '{printf "%s\n%s\n", $1, $2}'

also you can use this

echo "[email protected];[email protected]"|awk -F';' '{print $1,$2}' OFS="\n"

SQLite UPSERT / UPDATE OR INSERT

Option 1: Insert -> Update

If you like to avoid both changes()=0 and INSERT OR IGNORE even if you cannot afford deleting the row - You can use this logic;

First, insert (if not exists) and then update by filtering with the unique key.

Example

-- Table structure
CREATE TABLE players (
    id        INTEGER       PRIMARY KEY AUTOINCREMENT,
    user_name VARCHAR (255) NOT NULL
                            UNIQUE,
    age       INTEGER       NOT NULL
);

-- Insert if NOT exists
INSERT INTO players (user_name, age)
SELECT 'johnny', 20
WHERE NOT EXISTS (SELECT 1 FROM players WHERE user_name='johnny' AND age=20);

-- Update (will affect row, only if found)
-- no point to update user_name to 'johnny' since it's unique, and we filter by it as well
UPDATE players 
SET age=20 
WHERE user_name='johnny';

Regarding Triggers

Notice: I haven't tested it to see the which triggers are being called, but I assume the following:

if row does not exists

  • BEFORE INSERT
  • INSERT using INSTEAD OF
  • AFTER INSERT
  • BEFORE UPDATE
  • UPDATE using INSTEAD OF
  • AFTER UPDATE

if row does exists

  • BEFORE UPDATE
  • UPDATE using INSTEAD OF
  • AFTER UPDATE

Option 2: Insert or replace - keep your own ID

in this way you can have a single SQL command

-- Table structure
CREATE TABLE players (
    id        INTEGER       PRIMARY KEY AUTOINCREMENT,
    user_name VARCHAR (255) NOT NULL
                            UNIQUE,
    age       INTEGER       NOT NULL
);

-- Single command to insert or update
INSERT OR REPLACE INTO players 
(id, user_name, age) 
VALUES ((SELECT id from players WHERE user_name='johnny' AND age=20),
        'johnny',
        20);

Edit: added option 2.

How to convert entire dataframe to numeric while preserving decimals?

df2 <- data.frame(apply(df1, 2, function(x) as.numeric(as.character(x))))

Bypass invalid SSL certificate errors when calling web services in .Net

I was having same error using DownloadString; and was able to make it works as below with suggestions on this page

System.Net.WebClient client = new System.Net.WebClient();            
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string sHttpResonse = client.DownloadString(sUrl);

How get total sum from input box values using Javascript?

Try this:

function add() 
{
  var sum = 0;
  var inputs = document.getElementsByTagName("input");
  for(i = 0; i <= inputs.length; i++) 
  {
   if( inputs[i].name == 'qty'+i) 
   {
     sum += parseInt(input[i].value);
   }
  }
  console.log(sum)

}

How do I copy a folder from remote to local using scp?

The question was how to copy a folder from remote to local with scp command.

$ scp -r userRemote@remoteIp:/path/remoteDir /path/localDir

But here is the better way for do it with sftp - SSH File Transfer Protocol (also Secure File Transfer Protocol, or SFTP) is a network protocol that provides file access, file transfer, and file management over any reliable data stream.(wikipedia).

$ sftp user_remote@remote_ip

sftp> cd /path/to/remoteDir

sftp> get -r remoteDir

Fetching /path/to/remoteDir to localDir 100% 398 0.4KB/s 00:00

For help about sftp command just type help or ?.

jQuery AutoComplete Trigger Change Event

They are binding to keydown in the autocomplete source, so triggering the keydown will case it to update.

$("#CompanyList").trigger('keydown');

They aren't binding to the 'change' event because that only triggers at the DOM level when the form field loses focus. The autocomplete needs to respond faster than 'lost focus' so it has to bind to a key event.

Doing this:

companyList.autocomplete('option','change').call(companyList);

Will cause a bug if the user retypes the exact option that was there before.

The default for KeyValuePair

To avoid the boxing of KeyValuePair.Equals(object) you can use a ValueTuple.

if ((getResult.Key, getResult.Value) == default)

Adding a simple UIAlertView

UIAlertView *alert = [[UIAlertView alloc]
 initWithTitle:@"Title" 
 message:@"Message" 
 delegate:nil //or self
 cancelButtonTitle:@"OK"
 otherButtonTitles:nil];

 [alert show];
 [alert autorelease];

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

When should I use GET or POST method? What's the difference between them?

Use GET method if you want to retrieve the resources from URL. You could always see the last page if you hit the back button of your browser, and it could be bookmarked, so it is not as secure as POST method.

Use POST method if you want to 'submit' something to the URL. For example you want to create a google account and you may need to fill in all the detailed information, then you hit 'submit' button (POST method is called here), once you submit successfully, and try to hit back button of your browser, you will get error or a new blank form, instead of last page with filled form.

Set markers for individual points on a line in Matplotlib

A simple trick to change a particular point marker shape, size... is to first plot it with all the other data then plot one more plot only with that point (or set of points if you want to change the style of multiple points). Suppose we want to change the marker shape of second point:

x = [1,2,3,4,5]
y = [2,1,3,6,7]

plt.plot(x, y, "-o")
x0 = [2]
y0 = [1]
plt.plot(x0, y0, "s")

plt.show()

Result is: Plot with multiple markers

enter image description here

Why do we need middleware for async flow in Redux?

Redux can't return a function instead of an action. It's just a fact. That's why people use Thunk. Read these 14 lines of code to see how it allows the async cycle to work with some added function layering:

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => (next) => (action) => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

https://github.com/reduxjs/redux-thunk

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

How can I convert JSON to CSV?

Try this

import csv, json, sys

input = open(sys.argv[1])
data = json.load(input)
input.close()

output = csv.writer(sys.stdout)

output.writerow(data[0].keys())  # header row

for item in data:
    output.writerow(item.values())

The name 'ViewBag' does not exist in the current context

You need to add the MVC-specific Razor configuration to your web.config. See here: Razor HtmlHelper Extensions (or other namespaces for views) Not Found

Use the MVC 3 upgrade tool to automatically ensure you have the right config values.

Proper use of 'yield return'

Assuming your products LINQ class uses a similar yield for enumerating/iterating, the first version is more efficient because its only yielding one value each time its iterated over.

The second example is converting the enumerator/iterator to a list with the ToList() method. This means it manually iterates over all the items in the enumerator and then returns a flat list.

Any tools to generate an XSD schema from an XML instance document?

There also is XML schema learner which is available on Github.

It can take multiple xml files and extract a common XSD from all of those files.

How to declare a vector of zeros in R

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

dereferencing pointer to incomplete type

What do you mean, the error only shows up when you assign? For example on GCC, with no assignment in sight:

int main() {
    struct blah *b = 0;
    *b; // this is line 6
}

incompletetype.c:6: error: dereferencing pointer to incomplete type.

The error is at line 6, that's where I used an incomplete type as if it were a complete type. I was fine up until then.

The mistake is that you should have included whatever header defines the type. But the compiler can't possibly guess what line that should have been included at: any line outside of a function would be fine, pretty much. Neither is it going to go trawling through every text file on your system, looking for a header that defines it, and suggest you should include that.

Alternatively (good point, potatoswatter), the error is at the line where b was defined, when you meant to specify some type which actually exists, but actually specified blah. Finding the definition of the variable b shouldn't be too difficult in most cases. IDEs can usually do it for you, compiler warnings maybe can't be bothered. It's some pretty heinous code, though, if you can't find the definitions of the things you're using.

How to extract closed caption transcript from YouTube video?

With the YouTube video updated as of June 2020 it's very straight forward

  1. select on the 3 dots next to like/dislike buttons to open further menu options
  2. select "add translations"
  3. select language
  4. click autogenerate if needed
  5. click Actions > Download

You will get and .sbv file

android ellipsize multiline textview

Got this problem to, and finaly, I build myself a short solution. You just have to ellipsize manually the line you want, your maxLine attribute will cut your text.

This example cut your text for 3 lines max

        final TextView title = (TextView)findViewById(R.id.text);
        title.setText("A really long text");
        ViewTreeObserver vto = title.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                ViewTreeObserver obs = title.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if(title.getLineCount() > 3){
                    Log.d("","Line["+title.getLineCount()+"]"+title.getText());
                    int lineEndIndex = title.getLayout().getLineEnd(2);
                    String text = title.getText().subSequence(0, lineEndIndex-3)+"...";
                    title.setText(text);
                    Log.d("","NewText:"+text);
                }

            }
        });

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

I had the same problem.
I've installed fresh mysql at Ubuntu but I left mysql password empty, and as a result I couldn't connect to mysql in any way.
Lately I've revealed that there is a table of users where are names, hosts, passwords and some plugins. So for my user root@localhost mysql while installing assigned a plugin called auth_socket, which let Unix user "root" log in as a mysql user "root" without password, but don't allow login as another Unix user. So to fix that you should turn off this plugin and set usual authentication:

  1. open Linux terminal
  2. enter "sudo mysql"
    you will see "mysql >" which means you've connected to mysql as a 'root' Unix user and you can type SQL queries.
  3. enter SQL query to change a way how you will log in:
    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_new_password';
    where 'mysql_native_password' means - to turn off auth_socket plugin.

Getting msbuild.exe without installing Visual Studio

The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/

Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)

See this question for additional information.

How can I iterate over files in a given directory?

Since Python 3.5, things are much easier with os.scandir()

with os.scandir(path) as it:
    for entry in it:
        if entry.name.endswith(".asm") and entry.is_file():
            print(entry.name, entry.path)

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

How to add a Hint in spinner in XML

You can set the spinner prompt:

spinner.setPrompt("Select gender...");

Trying to get property of non-object in

$sidemenu is not an object, so you can't call methods on it. It is probably not being sent to your view, or $sidemenus is empty.

How can I decode HTML characters in C#?

On .Net 4.0:

System.Net.WebUtility.HtmlDecode()

No need to include assembly for a C# project

How to get query string parameter from MVC Razor markup?

For Asp.net Core 2

ViewContext.ModelState["id"].AttemptedValue

Can Javascript read the source of any web page?

<script>
    $.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('hhttps://example.com/') + '&callback=?', function (data) {
        alert(data.contents);
    });

</script>

Include jQuery and use this code to get HTML of other website. Replace example.com with your website.

This method involves an external server fetching the sites HTML & sending it to you. :)

Directly assigning values to C Pointers

The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.

You need to create an int variable somewhere in memory for the int * variable to point at.

Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:

int main(){
    int variable;
    int *ptr = &variable;
    *ptr = 20;
    printf("%d", *ptr);
    return 0;
}

Here, the int variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20. The key is that the pointer is initialized to point to the variable. In fact, you could just allocate some raw memory to point to, if you want:

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

Open multiple Eclipse workspaces on the Mac

You can create an AppleScript file to open Eclipse with a given workspace. You can even save the AppleScript file as an Application, which is equivalent to creating an alias with arguments in Windows OS.

Open Script Editor and type the following:

do shell script "open '/path/to/your/Eclipse/installation' -n --args -data /path/to/your/workspace"

For instance:

do shell script "open '/Applications/Eclipse.app' -n --args -data /MyWorkspaces/Personal" 

Press the Run button to check it's working.

This script can be saved as such, but I prefer to save it as an Application. That way I can customize the icon by copying the *.icns icon from the original Eclipse.app bundle to the script application bundle.

To open an App folder, use the "see contents" contextual menu option. It should look like this:

contents of script app

Where "main.scpt" is the AppleScript file and "applet.icns" is the icon from the original Eclipse bundle.

Compare two files and write it to "match" and "nomatch" files

Though its really long back this question was posted, I wish to answer as it might help others. This can be done easily by means of JOINKEYS in a SINGLE step. Here goes the pseudo code:

  • Code JOINKEYS PAIRED(implicit) and get both the records via reformatting filed. If there is NO match from either of files then append/prefix some special character say '$'
  • Compare via IFTHEN for '$', if exists then it doesnt have a paired record, it'll be written into unpaired file and rest to paired file.

Please do get back incase of any questions.

Advantages of SQL Server 2008 over SQL Server 2005?

The Denver SQL Server Users group has had some really good presentations over the last couple of months on the new features in SQL 2008 including one from Paul Nielsen just last week shortly after he got back from "Jump Start" up in Redmond (if I remember the name of the event correctly).

A couple of caveats on all of the "new features" for SQL 2008, the triage to determine which features will be in the various editions is still in progress. Many/most of the new/very cool features like data compression, partitioned indexes, policies, etc. are only going to be in the enterprise edition. Unless you're planning on running enterprise edition a lot of the features that are in the CTP's will probably not be in SQL 2008 standard, etc.

On other minor but often overlooked issue - SQL 2008 will only be 64-bit, if you're buying new hardware shouldn't be an issue but if you're planning on using existing hardware... also, if you've got dependencies on third party drivers (e.g. oracle) best be sure that a 64-bit version is available/works

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

How to run shell script file using nodejs?

Also, you can use shelljs plugin. It's easy and it's cross-platform.

Install command:

npm install [-g] shelljs

What is shellJS

ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!

An example of how it works:

var shell = require('shelljs');

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');

// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');

// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed');
  shell.exit(1);
}

Also, you can use from the command line:

$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo

Online code beautifier and formatter

For PHP, Java, C++, C, Perl, JavaScript, CSS you can try:

http://www.prettyprinter.de/index.php

Apache Proxy: No protocol handler was valid

I am posting an answer here, since I had the same error message for a different reason.

This error message can happen, for example, if you are using apache httpd to proxy requests from a source on protocol A to target on protocol B.

Here is the example of my situation:

AH01144: No protocol handler was valid for the URL /sockjs-node/info (scheme 'ws').

In the case above, what was happening was simply the following. I had enabled mod proxy to proxy websocket requests to nodejs based on path /sockjs-node.

The problem is that node does not use the path /sockjs-node for websocket requests exclusively. It also uses this path for hosting REST entrypoints that deliver information about websockets.

In this manner, when the application would try to open http://localhost:7001/sockjs-node/info, apache httpd would be trying to route the rest call from HTTP protocol to to a Webscoket endpoint call. Node did not accept this.

This lead to the exception above.

So be mindful that even if you enable the right modules, if you try to do the wrong forwarding, this will end with apache httpd informing you that the protocol you tried to use on the target server is not valid.

Disabling Log4J Output in Java

In addition, it is also possible to turn logging off programmatically:

Logger.getRootLogger().setLevel(Level.OFF);

Or

Logger.getRootLogger().removeAllAppenders();
Logger.getRootLogger().addAppender(new NullAppender());

These use imports:

import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.NullAppender;

How can I sanitize user input with PHP?

Methods for sanitizing user input with PHP:

  • Use Modern Versions of MySQL and PHP.

  • Set charset explicitly:

    • $mysqli->set_charset("utf8");
      manual
    • $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF8', $user, $password);
      manual
    • $pdo->exec("set names utf8");
      manual
    • $pdo = new PDO(
      "mysql:host=$host;dbname=$db", $user, $pass, 
      array(
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
      )
      );
      manual
    • mysql_set_charset('utf8')
      [deprecated in PHP 5.5.0, removed in PHP 7.0.0].
  • Use secure charsets:

    • Select utf8, latin1, ascii.., dont use vulnerable charsets big5, cp932, gb2312, gbk, sjis.
  • Use spatialized function:

    • MySQLi prepared statements:
      $stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); 
      $param = "' OR 1=1 /*";
      $stmt->bind_param('s', $param);
      $stmt->execute();
    • PDO::quote() - places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver:

      $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF8', $user, $password);explicit set the character set
      $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);disable emulating prepared statements to prevent fallback to emulating statements that MySQL can't prepare natively (to prevent injection)
      $var = $pdo->quote("' OR 1=1 /*");not only escapes the literal, but also quotes it (in single-quote ' characters) $stmt = $pdo->query("SELECT * FROM test WHERE name = $var LIMIT 1");

    • PDO Prepared Statements: vs MySQLi prepared statements supports more database drivers and named parameters:

      $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF8', $user, $password);explicit set the character set
      $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);disable emulating prepared statements to prevent fallback to emulating statements that MySQL can't prepare natively (to prevent injection) $stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); $stmt->execute(["' OR 1=1 /*"]);

    • mysql_real_escape_string [deprecated in PHP 5.5.0, removed in PHP 7.0.0].
    • mysqli_real_escape_string Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection. But recommended to use Prepared Statements because they are not simply escaped strings, a statement comes up with a complete query execution plan, including which tables and indexes it would use, it is a optimized way.
    • Use single quotes (' ') around your variables inside your query.
  • Check the variable contains what you are expecting for:

    • If you are expecting an integer, use:
      ctype_digit — Check for numeric character(s);
      $value = (int) $value;
      $value = intval($value);
      $var = filter_var('0755', FILTER_VALIDATE_INT, $options);
    • For Strings use:
      is_string() — Find whether the type of a variable is string

      Use Filter Function filter_var() — filters a variable with a specified filter:
      $email = filter_var($email, FILTER_SANITIZE_EMAIL);
      $newstr = filter_var($str, FILTER_SANITIZE_STRING);
      more predefined filters
    • filter_input() — Gets a specific external variable by name and optionally filters it:
      $search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
    • preg_match() — Perform a regular expression match;
    • Write Your own validation function.

Convert base-2 binary number string to int

Just type 0b11111111 in python interactive interface:

>>> 0b11111111
    255

Optional Parameters in Web Api Attribute Routing

Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:

[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]

The ? character is put always before the last } character

For more information see: Optional URI Parameters and Default Values

Check for special characters (/*-+_@&$#%) in a string?

Try this way.

public static bool hasSpecialChar(string input)
    {
        string specialChar = @"\|!#$%&/()=?»«@£§€{}.-;'<>_,";
        foreach (var item in specialChar)
        {
            if (input.Contains(item)) return true;
        }

        return false;
    }

How do I auto-hide placeholder text upon focus using css or jquery?

Sometimes you need SPECIFICITY to make sure your styles are applied with strongest factor id Thanks for @Rob Fletcher for his great answer, in our company we have used

So please consider adding styles prefixed with the id of the app container

_x000D_
_x000D_
    #app input:focus::-webkit-input-placeholder, #app  textarea:focus::-webkit-input-placeholder {_x000D_
        color: #FFFFFF;_x000D_
    }_x000D_
_x000D_
    #app input:focus:-moz-placeholder, #app textarea:focus:-moz-placeholder {_x000D_
        color: #FFFFFF;_x000D_
    }
_x000D_
_x000D_
_x000D_

How to stop process from .BAT file?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate

wmic offer even more flexibility than taskkill .With wmic Path win32_process get you can see the available fileds you can filter.

In Java, how do I get the difference in seconds between 2 dates?

Use this method:

private Long secondsBetween(Date first, Date second){
    return (second.getTime() - first.getTime())/1000;
}

Multidimensional arrays in Swift

For future readers, here is an elegant solution(5x5):

var matrix = [[Int]](repeating: [Int](repeating: 0, count: 5), count: 5)

and a dynamic approach:

var matrix = [[Int]]() // creates an empty matrix
var row = [Int]() // fill this row
matrix.append(row) // add this row

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

Check if have a python interpreter alive in any of the terminal windows. If so kill it and try sudo pip which worked for me.

Matplotlib scatterplot; colour as a function of a third variable

There's no need to manually set the colors. Instead, specify a grayscale colormap...

import numpy as np
import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()

plt.show()

enter image description here

Or, if you'd prefer a wider range of colormaps, you can also specify the cmap kwarg to scatter. To use the reversed version of any of these, just specify the "_r" version of any of them. E.g. gray_r instead of gray. There are several different grayscale colormaps pre-made (e.g. gray, gist_yarg, binary, etc).

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Get most recent row for given ID

SELECT *
FROM   tbl
WHERE  id = 1
ORDER  BY signin DESC
LIMIT  1;

The obvious index would be on (id), or a multicolumn index on (id, signin DESC).

Conveniently for the case, MySQL sorts NULL values last in descending order. That's what you typically want if there can be NULL values: the row with the latest not-null signin.

To get NULL values first:

ORDER BY signin IS NOT NULL, signin DESC

You may want to append more expressions to ORDER BY to get a deterministic pick from (potentially) multiple rows with NULL.
The same applies without NULL if signin is not defined UNIQUE.

Related:

The SQL standard does not explicitly define a default sort order for NULL values. The behavior varies quite a bit across different RDBMS. See:

But there are the NULLS FIRST / NULLS LAST clauses defined in the SQL standard and supported by most major RDBMS, but not by MySQL. See:

Programmatically navigate using react router V4

My answer is similar to Alex's. I'm not sure why React-Router made this so needlessly complicated. Why should I have to wrap my component with a HoC just to get access to what's essentially a global?

Anyway, if you take a look at how they implemented <BrowserRouter>, it's just a tiny wrapper around history.

We can pull that history bit out so that we can import it from anywhere. The trick, however, is if you're doing server-side rendering and you try to import the history module, it won't work because it uses browser-only APIs. But that's OK because we usually only redirect in response to a click or some other client-side event. Thus it's probably OK to fake it:

// history.js
if(__SERVER__) {
    module.exports = {};
} else {
    module.exports = require('history').createBrowserHistory();
}

With the help of webpack, we can define some vars so we know what environment we're in:

plugins: [
    new DefinePlugin({
        '__SERVER__': 'false',
        '__BROWSER__': 'true', // you really only need one of these, but I like to have both
    }),

And now you can

import history from './history';

From anywhere. It'll just return an empty module on the server.

If you don't want use these magic vars, you'll just have to require in the global object where it's needed (inside your event handler). import won't work because it only works at the top-level.

String, StringBuffer, and StringBuilder

Do you mean, for concatenation?

Real world example: You want to create a new string out of many others.

For instance to send a message:

String

String s = "Dear " + user.name + "<br>" + 
" I saw your profile and got interested in you.<br>" +
" I'm  " + user.age + "yrs. old too"

StringBuilder

String s = new StringBuilder().append.("Dear ").append( user.name ).append( "<br>" ) 
          .append(" I saw your profile and got interested in you.<br>") 
          .append(" I'm  " ).append( user.age ).append( "yrs. old too")
          .toString()

Or

String s = new StringBuilder(100).appe..... etc. ...
// The difference is a size of 100 will be allocated upfront as  fuzzy lollipop points out.

StringBuffer ( the syntax is exactly as with StringBuilder, the effects differ )

About

StringBuffer vs. StringBuilder

The former is synchonized and later is not.

So, if you invoke it several times in a single thread ( which is 90% of the cases ), StringBuilder will run much faster because it won't stop to see if it owns the thread lock.

So, it is recommendable to use StringBuilder ( unless of course you have more than one thread accessing to it at the same time, which is rare )

String concatenation ( using the + operator ) may be optimized by the compiler to use StringBuilder underneath, so, it not longer something to worry about, in the elder days of Java, this was something that everyone says should be avoided at all cost, because every concatenation created a new String object. Modern compilers don't do this anymore, but still it is a good practice to use StringBuilder instead just in case you use an "old" compiler.

edit

Just for who is curious, this is what the compiler does for this class:

class StringConcatenation {
    int x;
    String literal = "Value is" + x;
    String builder = new StringBuilder().append("Value is").append(x).toString();
}

javap -c StringConcatenation

Compiled from "StringConcatenation.java"
class StringConcatenation extends java.lang.Object{
int x;

java.lang.String literal;

java.lang.String builder;

StringConcatenation();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   aload_0
   5:   new #2; //class java/lang/StringBuilder
   8:   dup
   9:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   12:  ldc #4; //String Value is
   14:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   17:  aload_0
   18:  getfield    #6; //Field x:I
   21:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
   24:  invokevirtual   #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   27:  putfield    #9; //Field literal:Ljava/lang/String;
   30:  aload_0
   31:  new #2; //class java/lang/StringBuilder
   34:  dup
   35:  invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   38:  ldc #4; //String Value is
   40:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   43:  aload_0
   44:  getfield    #6; //Field x:I
   47:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
   50:  invokevirtual   #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   53:  putfield    #10; //Field builder:Ljava/lang/String;
   56:  return

}

Lines numbered 5 - 27 are for the String named "literal"

Lines numbered 31-53 are for the String named "builder"

Ther's no difference, exactly the same code is executed for both strings.

Formatting Phone Numbers in PHP

All,

I think I fixed it. Working for current input files and have following 2 functions to get this done!

function format_phone_number:

        function format_phone_number ( $mynum, $mask ) {
        /*********************************************************************/
        /*   Purpose: Return either masked phone number or false             */
        /*     Masks: Val=1 or xxx xxx xxxx                                             */
        /*            Val=2 or xxx xxx.xxxx                                             */
        /*            Val=3 or xxx.xxx.xxxx                                             */
        /*            Val=4 or (xxx) xxx xxxx                                           */
        /*            Val=5 or (xxx) xxx.xxxx                                           */
        /*            Val=6 or (xxx).xxx.xxxx                                           */
        /*            Val=7 or (xxx) xxx-xxxx                                           */
        /*            Val=8 or (xxx)-xxx-xxxx                                           */
        /*********************************************************************/         
        $val_num        = self::validate_phone_number ( $mynum );
        if ( !$val_num && !is_string ( $mynum ) ) { 
            echo "Number $mynum is not a valid phone number! \n";
            return false;
        }   // end if !$val_num
        if ( ( $mask == 1 ) || ( $mask == 'xxx xxx xxxx' ) ) { 
            $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', 
                    '$1 $2 $3'." \n", $mynum);
            return $phone;
        }   // end if $mask == 1
        if ( ( $mask == 2 ) || ( $mask == 'xxx xxx.xxxx' ) ) { 
            $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', 
                    '$1 $2.$3'." \n", $mynum);
            return $phone;
        }   // end if $mask == 2
        if ( ( $mask == 3 ) || ( $mask == 'xxx.xxx.xxxx' ) ) { 
            $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', 
                    '$1.$2.$3'." \n", $mynum);
            return $phone;
        }   // end if $mask == 3
        if ( ( $mask == 4 ) || ( $mask == '(xxx) xxx xxxx' ) ) { 
            $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', 
                    '($1) $2 $3'." \n", $mynum);
            return $phone;
        }   // end if $mask == 4
        if ( ( $mask == 5 ) || ( $mask == '(xxx) xxx.xxxx' ) ) { 
            $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', 
                    '($1) $2.$3'." \n", $mynum);
            return $phone;
        }   // end if $mask == 5
        if ( ( $mask == 6 ) || ( $mask == '(xxx).xxx.xxxx' ) ) { 
            $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', 
                    '($1).$2.$3'." \n", $mynum);
            return $phone;
        }   // end if $mask == 6
        if ( ( $mask == 7 ) || ( $mask == '(xxx) xxx-xxxx' ) ) { 
            $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', 
                    '($1) $2-$3'." \n", $mynum);
            return $phone;
        }   // end if $mask == 7
        if ( ( $mask == 8 ) || ( $mask == '(xxx)-xxx-xxxx' ) ) { 
            $phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~', 
                    '($1)-$2-$3'." \n", $mynum);
            return $phone;
        }   // end if $mask == 8
        return false;       // Returns false if no conditions meet or input
    }  // end function format_phone_number

function validate_phone_number:

        function validate_phone_number ( $phone ) {
        /*********************************************************************/
        /*   Purpose:   To determine if the passed string is a valid phone  */
        /*              number following one of the establish formatting        */
        /*                  styles for phone numbers.  This function also breaks    */
        /*                  a valid number into it's respective components of:      */
        /*                          3-digit area code,                                      */
        /*                          3-digit exchange code,                                  */
        /*                          4-digit subscriber number                               */
        /*                  and validates the number against 10 digit US NANPA  */
        /*                  guidelines.                                                         */
        /*********************************************************************/         
        $format_pattern =   '/^(?:(?:\((?=\d{3}\)))?(\d{3})(?:(?<=\(\d{3})\))'.
                                    '?[\s.\/-]?)?(\d{3})[\s\.\/-]?(\d{4})\s?(?:(?:(?:'.
                                    '(?:e|x|ex|ext)\.?\:?|extension\:?)\s?)(?=\d+)'.
                                    '(\d+))?$/';
        $nanpa_pattern      =   '/^(?:1)?(?(?!(37|96))[2-9][0-8][0-9](?<!(11)))?'.
                                    '[2-9][0-9]{2}(?<!(11))[0-9]{4}(?<!(555(01([0-9]'.
                                    '[0-9])|1212)))$/';

        // Init array of variables to false
        $valid = array('format' =>  false,
                            'nanpa' => false,
                            'ext'       => false,
                            'all'       => false);

        //Check data against the format analyzer
        if ( preg_match ( $format_pattern, $phone, $matchset ) ) {
            $valid['format'] = true;    
        }

        //If formatted properly, continue
        //if($valid['format']) {
        if ( !$valid['format'] ) {
            return false;
        } else {
            //Set array of new components
            $components =   array ( 'ac' => $matchset[1], //area code
                                                            'xc' => $matchset[2], //exchange code
                                                            'sn' => $matchset[3] //subscriber number
                                                            );
            //              $components =   array ( 'ac' => $matchset[1], //area code
            //                                              'xc' => $matchset[2], //exchange code
            //                                              'sn' => $matchset[3], //subscriber number
            //                                              'xn' => $matchset[4] //extension number             
            //                                              );

            //Set array of number variants
            $numbers    =   array ( 'original' => $matchset[0],
                                        'stripped' => substr(preg_replace('[\D]', '', $matchset[0]), 0, 10)
                                        );

            //Now let's check the first ten digits against NANPA standards
            if(preg_match($nanpa_pattern, $numbers['stripped'])) {
                $valid['nanpa'] = true;
            }

            //If the NANPA guidelines have been met, continue
            if ( $valid['nanpa'] ) {
                if ( !empty ( $components['xn'] ) ) {
                    if ( preg_match ( '/^[\d]{1,6}$/', $components['xn'] ) ) {
                        $valid['ext'] = true;
                    }   // end if if preg_match 
                } else {
                    $valid['ext'] = true;
                }   // end if if  !empty
            }   // end if $valid nanpa

            //If the extension number is valid or non-existent, continue
            if ( $valid['ext'] ) {
                $valid['all'] = true;
            }   // end if $valid ext
        }   // end if $valid
        return $valid['all'];
    }   // end functon validate_phone_number

Notice I have this in a class lib, so thus the "self::validate_phone_number" call from the first function/method.

Notice line # 32 of the "validate_phone_number" function where I added the:

            if ( !$valid['format'] ) {
            return false;
        } else {

to get me the false return needed if not valid phone number.

Still need to test this against more data, but working on current data, with current format and I'm using style '8' for this particular data batch.

Also I commented out the "extension" logic as I was constantly getting errors from it, seeing I do not have any of that info in my data.

How to find my realm file?

The above answers missing a way to find the realm file in Android platform and believe me this way will save your lot's of time which we generally waste in other approaches to get the realm file. So let's start...

First open "Device File Explorer" in android studio(View -> Tools Windows -> Device File Explorer.

This will open your device explorer.

enter image description here

now open data -> data -> (your_app_package_name) -> files -> default.realm

default.realm is the file for which we are here. Now Save_as this file at your location and access the file from the realm_browser and you will get your database.

NOTE: Mentioned approach is tested on non-rooted phone(one+3).

The way to check a HDFS directory's size?

hdfs dfs -count <dir>

info from man page:

-count [-q] [-h] [-v] [-t [<storage type>]] [-u] <path> ... :
  Count the number of directories, files and bytes under the paths
  that match the specified file pattern.  The output columns are:
  DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME
  or, with the -q option:
  QUOTA REM_QUOTA SPACE_QUOTA REM_SPACE_QUOTA
        DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME

How to configure Git post commit hook

As mentioned in "Polling must die: triggering Jenkins builds from a git hook", you can notify Jenkins of a new commit:

With the latest Git plugin 1.1.14 (that I just release now), you can now do this more >easily by simply executing the following command:

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>

This will scan all the jobs that’s configured to check out the specified URL, and if they are also configured with polling, it’ll immediately trigger the polling (and if that finds a change worth a build, a build will be triggered in turn.)

This allows a script to remain the same when jobs come and go in Jenkins.
Or if you have multiple repositories under a single repository host application (such as Gitosis), you can share a single post-receive hook script with all the repositories. Finally, this URL doesn’t require authentication even for secured Jenkins, because the server doesn’t directly use anything that the client is sending. It runs polling to verify that there is a change, before it actually starts a build.

As mentioned here, make sure to use the right address for your Jenkins server:

since we're running Jenkins as standalone Webserver on port 8080 the URL should have been without the /jenkins, like this:

http://jenkins:8080/git/notifyCommit?url=git@gitserver:tools/common.git

To reinforce that last point, ptha adds in the comments:

It may be obvious, but I had issues with:

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>. 

The url parameter should match exactly what you have in Repository URL of your Jenkins job.
When copying examples I left out the protocol, in our case ssh://, and it didn't work.


You can also use a simple post-receive hook like in "Push based builds using Jenkins and GIT"

#!/bin/bash
/usr/bin/curl --user USERNAME:PASS -s \

http://jenkinsci/job/PROJECTNAME/build?token=1qaz2wsx

Configure your Jenkins job to be able to “Trigger builds remotely” and use an authentication token (1qaz2wsx in this example).

However, this is a project-specific script, and the author mentions a way to generalize it.
The first solution is easier as it doesn't depend on authentication or a specific project.


I want to check in change set whether at least one java file is there the build should start.
Suppose the developers changed only XML files or property files, then the build should not start.

Basically, your build script can:

  • put a 'build' notes (see git notes) on the first call
  • on the subsequent calls, grab the list of commits between HEAD of your branch candidate for build and the commit referenced by the git notes 'build' (git show refs/notes/build): git diff --name-only SHA_build HEAD.
  • your script can parse that list and decide if it needs to go on with the build.
  • in any case, create/move your git notes 'build' to HEAD.

May 2016: cwhsu points out in the comments the following possible url:

you could just use curl --user USER:PWD http://JENKINS_SERVER/job/JOB_NAME/build?token=YOUR_TOKEN if you set trigger config in your item

http://i.imgur.com/IolrOOj.png


June 2016, polaretto points out in the comments:

I wanted to add that with just a little of shell scripting you can avoid manual url configuration, especially if you have many repositories under a common directory.
For example I used these parameter expansions to get the repo name

repository=${PWD%/hooks}; 
repository=${repository##*/} 

and then use it like:

curl $JENKINS_URL/git/notifyCommit?url=$GIT_URL/$repository

Cannot set content-type to 'application/json' in jQuery.ajax

So all you need to do for this to work is add:

headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

as a field to your post request and it'll work.

How to change a nullable column to not nullable in a Rails migration?

In Rails 4, this is a better (DRYer) solution:

change_column_null :my_models, :date_column, false

To ensure no records exist with NULL values in that column, you can pass a fourth parameter, which is the default value to use for records with NULL values:

change_column_null :my_models, :date_column, false, Time.now

System.Net.WebException: The remote name could not be resolved:

I had a similar issue when trying to access a service (old ASMX service). The call would work when accessing via an IP however when calling with an alias I would get the remote name could not be resolved.

Added the following to the config and it resolved the issue:

<system.net>
    <defaultProxy enabled="true">
    </defaultProxy>
</system.net>

How do you change the width and height of Twitter Bootstrap's tooltips?

On BS3

.tooltip-inner {
    min-width: 150px; /* the minimum width */
}

convert NSDictionary to NSString

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

What is the purpose of willSet and didSet in Swift?

One thing where didSet is really handy is when you use outlets to add additional configuration.

@IBOutlet weak var loginOrSignupButton: UIButton! {
  didSet {
        let title = NSLocalizedString("signup_required_button")
        loginOrSignupButton.setTitle(title, for: .normal)
        loginOrSignupButton.setTitle(title, for: .highlighted)
  }

Xcode 'CodeSign error: code signing is required'

It happens when Xcode doesn't recognize your certificate.

It's just a pain in the ass to solve it, there are a lot of possibilities to help you.

But the first thing you should try is removing in the "Window" tab => Organizer, the provisioning that is in your device. Then re-add them (download them again on the apple website). And try to compile again.

By the way, did you check in the Project Info Window the "code signing identity" ?

Good Luck.

How to make a DIV not wrap?

you can use

display: table;

for your container and therfore avoid the overflow: hidden;. It should do the job if you used it just for warpping purpose.

#1071 - Specified key was too long; max key length is 1000 bytes

This error means that length of index index is more then 1000 bytes. MySQL and storage engines may have this restriction. I have got similar error on MySQL 5.5 - 'Specified key was too long; max key length is 3072 bytes' when ran this script:

CREATE TABLE IF NOT EXISTS test_table1 (
  column1 varchar(500) NOT NULL,
  column2 varchar(500) NOT NULL,
  column3 varchar(500) NOT NULL,
  column4 varchar(500) NOT NULL,
  column5 varchar(500) NOT NULL,
  column6 varchar(500) NOT NULL,
  KEY `index` (column1, column2, column3, column4, column5, column6)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

UTF8 is multi-bytes, and key length is calculated in this way - 500 * 3 * 6 = 9000 bytes.

But note, next query works!

CREATE TABLE IF NOT EXISTS test_table1 (
  column1 varchar(500) NOT NULL,
  column2 varchar(500) NOT NULL,
  column3 varchar(500) NOT NULL,
  column4 varchar(500) NOT NULL,
  column5 varchar(500) NOT NULL,
  column6 varchar(500) NOT NULL,
  KEY `index` (column1, column2, column3, column4, column5, column6)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

...because I used CHARSET=latin1, in this case key length is 500 * 6 = 3000 bytes.

Getting a list of values from a list of dicts

Assuming every dict has a value key, you can write (assuming your list is named l)

[d['value'] for d in l]

If value might be missing, you can use

[d['value'] for d in l if 'value' in d]

How do I make WRAP_CONTENT work on a RecyclerView

UPDATE

By Android Support Library 23.2 update, all WRAP_CONTENT should work correctly.

Please update version of a library in gradle file.

compile 'com.android.support:recyclerview-v7:23.2.0'

Original Answer

As answered on other question, you need to use original onMeasure() method when your recycler view height is bigger than screen height. This layout manager can calculate ItemDecoration and can scroll with more.

    public class MyLinearLayoutManager extends LinearLayoutManager {

public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {
        measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);

        if (getOrientation() == HORIZONTAL) {
            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }

    // If child view is more than screen size, there is no need to make it wrap content. We can use original onMeasure() so we can scroll view.
    if (height < heightSize && width < widthSize) {

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    } else {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
    }
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                               int heightSpec, int[] measuredDimension) {

   View view = recycler.getViewForPosition(position);

   // For adding Item Decor Insets to view
   super.measureChildWithMargins(view, 0, 0);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom() + getPaddingBottom() + getDecoratedBottom(view) , p.height);
            view.measure(childWidthSpec, childHeightSpec);

            // Get decorated measurements
            measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
            measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }
}

original answer : https://stackoverflow.com/a/28510031/1577792

html select option SELECTED

foreach ($array as $value => $name) {
     echo '<option value="' . htmlentities($value) . '"' . (($_GET['sel'] === $value) ? ' selected="selected"') . '>' . htmlentities($name) . '</option>';
}

This is fairly neat, and, I think, self-explanatory.

How to use Typescript with native ES6 Promises

This the most recent way to do this, the above answer is outdated:

typings install --global es6-promise

ASP.NET 4.5 has not been registered on the Web server

tl;dr; Clicking OK is the workaround, everything will work fine after that.

I also received this error message.

Configuring Web http://localhost:xxxxx/ for ASP.NET 4.5 failed. You must manually configure this site for ASP.NET 4.5 in order for the site to run correctly. ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly.

Environment: Windows 10, IIS8, VS 2012 Web.

After finding this page, along with several seemingly invasive solutions, I read through the hotfix option at https://support.microsoft.com/en-us/help/3002339/unexpected-dialog-box-appears-when-you-open-projects-in-visual-studio as suggested here.

Please avoid doing anything too drastic, and note the section of that page marked "Workaround" as shown below:

Workaround


To work around this issue, click OK when the dialog box appears after you either create a new project or open an existing Web Site Project or Windows Azure project. After you do this, the project works as expected.

In other words, click OK on the dialog box one time, and the message is gone forever. The project will work just fine.

Intellij JAVA_HOME variable

So far, nobody has answered the actual question.

Someone can figure what is happening ?

The problem here is that while the value of your $JAVA_HOME is correct, you defined it in the wrong place.

  • When you open a terminal and launch a Bash session, it will read the ~/.bash_profile file. Thus, when you enter echo $JAVA_HOME, it will return the value that has been set there.
  • When you launch IntelliJ directly, it will not read ~/.bash_profile … why should it? So to IntelliJ, this variable is not set.

There are two possible solutions to this:

  • Launch IntelliJ from a Bash session: open a terminal and run "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea". The idea process will inherit any environment variables of Bash that have been exported. (Since you did export JAVA_HOME=…, it works!), or, the sophisticated way:
  • Set global environment variables that apply to all programs, not only Bash sessions. This is more complicated than you might think, and is explained here and here, for example. What you should do is run

    /bin/launchctl setenv JAVA_HOME $(/usr/libexec/java_home)
    

    However, this gets reset after a reboot. To make sure this gets run on every boot, execute

    cat << EOF > ~/Library/LaunchAgents/setenv.JAVA_HOME.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
        <key>Label</key>
        <string>setenv.JAVA_HOME</string>
        <key>ProgramArguments</key>
        <array>
          <string>/bin/launchctl</string>
          <string>setenv</string>
          <string>JAVA_HOME</string>
          <string>$(/usr/libexec/java_home)</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>ServiceIPC</key>
        <false/>
      </dict>
    </plist>
    EOF
    

    Note that this also affects the Terminal process, so there is no need to put anything in your ~/.bash_profile.

How to initialize a vector with fixed length in R

Just for the sake of completeness you can just take the wanted data type and add brackets with the number of elements like so:

x <- character(10)

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

You can use method shown here and replace isNull with isnan:

from pyspark.sql.functions import isnan, when, count, col

df.select([count(when(isnan(c), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
|      0|         0|  3|
+-------+----------+---+

or

df.select([count(when(isnan(c) | col(c).isNull(), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
|      0|         0|  5|
+-------+----------+---+

How can I make all images of different height and width the same via CSS?

For those using Bootstrap and not wanting to lose the responsivness just do not set the width of the container. The following code is based on gillytech post.

index.hmtl

<div id="image_preview" class="row">  
    <div class='crop col-xs-12 col-sm-6 col-md-6 '>
         <img class="col-xs-12 col-sm-6 col-md-6" 
          id="preview0" src='img/preview_default.jpg'/>
    </div>
    <div class="col-xs-12 col-sm-6 col-md-6">
         more stuff
    </div>

</div> <!-- end image preview -->

style.css

/*images with the same width*/
.crop {
    height: 300px;
    /*width: 400px;*/
    overflow: hidden;
}
.crop img {
    height: auto;
    width: 100%;
}

OR style.css

/*images with the same height*/
.crop {
    height: 300px;
    /*width: 400px;*/
    overflow: hidden;
}
.crop img {
    height: 100%;
    width: auto;
}

Button that refreshes the page on click

window.opener.location.href ='workItem.adm?wiId='+${param.wiId};

It will go to the required path and you won't get any resend prompt.

How to convert float to varchar in SQL Server

I just came across a similar situation and was surprised at the rounding issues of 'very large numbers' presented within SSMS v17.9.1 / SQL 2017.

I am not suggesting I have a solution, however I have observed that FORMAT presents a number which appears correct. I can not imply this reduces further rounding issues or is useful within a complicated mathematical function.

T SQL Code supplied which should clearly demonstrate my observations while enabling others to test their code and ideas should the need arise.

WITH Units AS 
(
   SELECT 1.0 AS [RaisedPower] , 'Ten' As UnitDescription
   UNION ALL
   SELECT 2.0 AS [RaisedPower] , 'Hundred' As UnitDescription
   UNION ALL
   SELECT 3.0 AS [RaisedPower] , 'Thousand' As UnitDescription
   UNION ALL
   SELECT 6.0 AS [RaisedPower] , 'Million' As UnitDescription
   UNION ALL
   SELECT 9.0 AS [RaisedPower] , 'Billion' As UnitDescription
   UNION ALL
   SELECT 12.0 AS [RaisedPower] , 'Trillion' As UnitDescription
   UNION ALL
   SELECT 15.0 AS [RaisedPower] , 'Quadrillion' As UnitDescription
   UNION ALL
   SELECT 18.0 AS [RaisedPower] , 'Quintillion' As UnitDescription
   UNION ALL
   SELECT 21.0 AS [RaisedPower] , 'Sextillion' As UnitDescription
   UNION ALL
   SELECT 24.0 AS [RaisedPower] , 'Septillion' As UnitDescription
   UNION ALL
   SELECT 27.0 AS [RaisedPower] , 'Octillion' As UnitDescription
   UNION ALL
   SELECT 30.0 AS [RaisedPower] , 'Nonillion' As UnitDescription
   UNION ALL
   SELECT 33.0  AS [RaisedPower] , 'Decillion' As UnitDescription

)

SELECT UnitDescription

   ,              POWER( CAST(10.0 AS FLOAT(53)) , [RaisedPower] )                                                             AS ReturnsFloat
   ,        CAST( POWER( CAST(10.0 AS FLOAT(53)) , [RaisedPower] )  AS NUMERIC (38,0) )                                        AS RoundingIssues
   , STR(   CAST( POWER( CAST(10.0 AS FLOAT(53)) , [RaisedPower] )  AS NUMERIC (38,0) ) ,   CAST([RaisedPower] AS INT) + 2, 0) AS LessRoundingIssues
   , FORMAT(      POWER( CAST(10.0 AS FLOAT(53)) , [RaisedPower] )  , '0')                                                     AS NicelyFormatted

FROM Units
ORDER BY [RaisedPower]

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

If you are using debug configuration for maven, use the command

clean install

And skip all the tests.

How to remove a class from elements in pure JavaScript?

var elems = document.querySelectorAll(".widget.hover");

[].forEach.call(elems, function(el) {
    el.classList.remove("hover");
});

You can patch .classList into IE9. Otherwise, you'll need to modify the .className.

var elems = document.querySelectorAll(".widget.hover");

[].forEach.call(elems, function(el) {
    el.className = el.className.replace(/\bhover\b/, "");
});

The .forEach() also needs a patch for IE8, but that's pretty common anyway.

Screenshot sizes for publishing android app on Google Play

The files need to be in a JPEG or PNG format of 24 bits, in a 2:1 ratio if it is a portrait and a 16:9 ratio for landscapes. Be careful that if you go for different sizes: the maximum size should not be more than twice bigger than the minimum size.

how to sort an ArrayList in ascending order using Collections and Comparator

Just throwing this out there...Can't you just do:

Collections.sort(myarrayList);

It's been awhile though...

Detect rotation of Android phone in the browser with JavaScript

You could always listen to the window resize event. If, on that event, the window went from being taller than it is wide to wider than it is tall (or vice versa), you can be pretty sure the phone orientation was just changed.

Nginx -- static file serving confusion with root & alias

alias is used to replace the location part path (LPP) in the request path, while the root is used to be prepended to the request path.

They are two ways to map the request path to the final file path.

alias could only be used in location block, and it will override the outside root.

alias and root cannot be used in location block together.

Change limit for "Mysql Row size too large"

I ran into this problem recently and solved it a different way. If you are running MySQL version 5.6.20 there is a known bug in the system. See MySQL docs

Important Due to Bug #69477, redo log writes for large, externally stored BLOB fields could overwrite the most recent checkpoint. To address this bug, a patch introduced in MySQL 5.6.20 limits the size of redo log BLOB writes to 10% of the redo log file size. As a result of this limit, innodb_log_file_size should be set to a value greater than 10 times the largest BLOB data size found in the rows of your tables plus the length of other variable length fields (VARCHAR, VARBINARY, and TEXT type fields).

In my situation the offending blob table was around 16MB. Thus, the way I solved it was by adding a line to my.cnf that ensured I had at least 10x that amount and then some:

innodb_log_file_size = 256M

Editing the date formatting of x-axis tick labels in matplotlib

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.

So for everyone in need here is a full working example:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

Explaining the 'find -mtime' command

To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.

find . -mtime -1 -ls

Git says local branch is behind remote branch, but it's not

This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:

git co master
git pull

Which fetched those changes. Then,

git co develop
git pull

Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.

MAVEN_HOME, MVN_HOME or M2_HOME

I stumbled over this as chocolatey sets M2_HOME. I wanted to locate settings.xml.

The current way for settings.xml is to go to %USERPROFILE%. There, a directory .m2 is contained, where one finds settings.xml.

Never use M2_HOME. It is unsupported since Apache Maven 3.5.0.

Details:

Based on problems in using M2_HOME related to different Maven versions installed and to simplify things, the usage of M2_HOME has been removed and is not supported any more MNG-5823, MNG-5836, MNG-5607.

Important change for windows users: The usage of %HOME% has been replaced with %USERPROFILE% MNG-6001

Source: https://maven.apache.org/docs/3.5.0/release-notes.html#overview-about-the-changes

Getting data from Yahoo Finance

As from the answer from BrianC use the YQL console. But after selecting the "Show Community Tables" go to the bottom of the tables list and expand yahoo where you find plenty of yahoo.finance tables:

Stock Quotes:

  • yahoo.finance.quotes
  • yahoo.finance.historicaldata

Fundamental analysis:

  • yahoo.finance.keystats
  • yahoo.finance.balancesheet
  • yahoo.finance.incomestatement
  • yahoo.finance.analystestimates
  • yahoo.finance.dividendhistory

Technical analysis:

  • yahoo.finance.historicaldata
  • yahoo.finance.quotes
  • yahoo.finance.quant
  • yahoo.finance.option*

General financial information:

  • yahoo.finance.industry
  • yahoo.finance.sectors
  • yahoo.finance.isin
  • yahoo.finance.quoteslist
  • yahoo.finance.xchange

2/Nov/2017: Yahoo finance has apparently killed this API, for more info and alternative resources see https://news.ycombinator.com/item?id=15616880

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

I had the same error while including file from root of my project in codeigniter.I was using this in common.php of my project.

<?php include_once base_url().'csrf-magic-master/csrf-magic.php';  ?>

i changed it to

<?php include_once ('csrf-magic-master/csrf-magic.php');  ?>

Working fine now.

Fatal error: Call to undefined function mysql_connect()

PHP.INI

Check if you forgot to enable the options below(loads the modules for mysql among others):

; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "ext"

Open another application from your own (intent)

Try this code, Hope this will help you. If this package is available then this will open the app or else open the play store for downloads

    String  packageN = "aman4india.com.pincodedirectory";

            Intent i = getPackageManager().getLaunchIntentForPackage(packageN);
            if (i != null) {
                i.addCategory(Intent.CATEGORY_LAUNCHER);
                startActivity(i);
            } else {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
                }
                catch (android.content.ActivityNotFoundException anfe) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
                }
            }

TypeError: $(...).modal is not a function with bootstrap Modal

For me, I had //= require jquery after //= require bootstrap. Once I moved jquery before bootstrap, everything worked.

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

Right query to get the current number of connections in a PostgreSQL DB

From looking at the source code, it seems like the pg_stat_database query gives you the number of connections to the current database for all users. On the other hand, the pg_stat_activity query gives the number of connections to the current database for the querying user only.

Saving Excel workbook to constant path with filename from two fields

Ok, at that time got it done with the help of a friend and the code looks like this.

Sub Saving()

Dim part1 As String

Dim part2 As String


part1 = Range("C5").Value

part2 = Range("C8").Value


ActiveWorkbook.SaveAs Filename:= _

"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

End Sub

How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou

Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?

How can I access Oracle from Python?

You can use any of the following way based on Service Name or SID whatever you have.

With SID:

import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', 'sid')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select count(*) from TABLE_NAME')
for row in c:
   print(row)
conn.close()

OR

With Service Name:

import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', service_name='service_name')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select count(*) from TABLE_NAME')
for row in c:
   print(row)
conn.close()

Toggle Checkboxes on/off

Setting 'checked' or null instead of true or false respectively will do the work.

// checkbox selection
var $chk=$(':checkbox');
$chk.prop('checked',$chk.is(':checked') ? null:'checked');

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Comparing two collections for equality irrespective of the order of items in them

erickson is almost right: since you want to match on counts of duplicates, you want a Bag. In Java, this looks something like:

(new HashBag(collection1)).equals(new HashBag(collection2))

I'm sure C# has a built-in Set implementation. I would use that first; if performance is a problem, you could always use a different Set implementation, but use the same Set interface.

Lollipop : draw behind statusBar with its color set to transparent

The accepted answer worked for me using a CollapsingToolbarLayout. It's important to note though, that setSytstemUiVisibility() overrides any previous calls to that function. So if you're using that function somewhere else for the same view, you need to include the View.SYSTEM_UI_FLAG_LAYOUT_STABLE and View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN flags, or they will be overridden with the new call.

This was the case for me, and once I added the two flags to the other place I was making a call to setSystemUiVisibility(), the accepted answer worked perfectly.

LEFT JOIN only first row

I've used something else (I think better...) and want to share it:

I created a VIEW that has a "group" clause

CREATE VIEW vCountries AS SELECT * PROVINCES GROUP BY country_code

SELECT * FROM client INNER JOIN vCountries on client_province = province_id

I want to say yet, that I think that we need to do this solution BECAUSE WE DID SOMETHING WRONG IN THE ANALYSIS... at least in my case... but sometimes it's cheaper to do this that to redesign everything...

I hope it helps!

#1214 - The used table type doesn't support FULLTEXT indexes

Before MySQL 5.6 Full-Text Search is supported only with MyISAM Engine.

Therefore either change the engine for your table to MyISAM

CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

Here is SQLFiddle demo

or upgrade to 5.6 and use InnoDB Full-Text Search.

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

I had a similar problem recently, and needed to change the permissions of my vendor folder

By running following commands :

  1. php artisan cache:clear
  2. chmod -R 777 storage vendor
  3. composer dump-autoload

I need to give all the permissions required to open and write vendor files to solve this issue

remove legend title in ggplot

This works too and also demonstrates how to change the legend title:

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  scale_color_discrete(name="")

How to wait for async method to complete?

Here is a workaround using a flag:

//outside your event or method, but inside your class
private bool IsExecuted = false;

private async Task MethodA()
{

//Do Stuff Here

IsExecuted = true;
}

.
.
.

//Inside your event or method

{
await MethodA();

while (!isExecuted) Thread.Sleep(200); // <-------

await MethodB();
}

How can I escape a single quote?

Represent it as a text entity (ASCII 39):

<input type='text' id='abc' value='hel&#39;lo'>

Rails 4: how to use $(document).ready() with turbo-links

Either use the

$(document).on "page:load", attachRatingHandler

or use jQuery's .on function to achieve the same effect

$(document).on 'click', 'span.star', attachRatingHandler

see here for more details: http://srbiv.github.io/2013/04/06/rails-4-my-first-run-in-with-turbolinks.html

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Had this issue on Python 2.7.9, solved by updating to Python 2.7.10 (unreleased when this question was asked and answered).

how to release localhost from Error: listen EADDRINUSE

I used the command netstat -ano | grep "portnumber" in order to list out the port number/PID for that process. Then, you can use taskkill -f //pid 111111 to kill the process, last value being the pid you find from the first command.

One problem I run into at times is node respawning even after killing the process, so I have to use the good old task manager to manually kill the node process.

align right in a table cell with CSS

What worked for me now is:

CSS:

.right {
  text-align: right;
  margin-right: 1em;
}

.left {
  text-align: left;
  margin-left: 1em;
}

HTML:

<table width="100%">
  <tbody>
    <tr>
      <td class="left">
        <input id="abort" type="submit" name="abort" value="Back">
        <input id="save" type="submit" name="save" value="Save">
      </td>
      <td class="right">
        <input id="delegate" type="submit" name="delegate" value="Delegate">
        <input id="unassign" type="submit" name="unassign" value="Unassign">
        <input id="complete" type="submit" name="complete" value="Complete">
      </td>
    </tr>
  </tbody>
</table>

See the following fiddle:

http://jsfiddle.net/Joysn/3u3SD/

How to implement a binary search tree in Python?

class Node: 
    rChild,lChild,data = None,None,None

This is wrong - it makes your variables class variables - that is, every instance of Node uses the same values (changing rChild of any node changes it for all nodes!). This is clearly not what you want; try

class Node: 
    def __init__(self, key):
        self.rChild = None
        self.lChild = None
        self.data = key

now each node has its own set of variables. The same applies to your definition of Tree,

class Tree:
    root,size = None,0    # <- lose this line!
    def __init__(self):
        self.root = None
        self.size = 0

Further, each class should be a "new-style" class derived from the "object" class and should chain back to object.__init__():

class Node(object): 
    def __init__(self, data, rChild=None, lChild=None):
        super(Node,self).__init__()
        self.data   = data
        self.rChild = rChild
        self.lChild = lChild

class Tree(object):
    def __init__(self):
        super(Tree,self).__init__()
        self.root = None
        self.size = 0

Also, main() is indented too far - as shown, it is a method of Tree which is uncallable because it does not accept a self argument.

Also, you are modifying the object's data directly (t.root = Node(4)) which kind of destroys encapsulation (the whole point of having classes in the first place); you should be doing something more like

def main():
    t = Tree()
    t.add(4)    # <- let the tree create a data Node and insert it
    t.add(5)