Programs & Examples On #Loadcontrol

SQL Error: 0, SQLState: 08S01 Communications link failure

I'm answering on specific to this error code(08s01).

usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".

1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.

2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days

3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.

MVC 4 Razor File Upload

Clarifying it. Model:

public class ContactUsModel
{
    public string FirstName { get; set; }             
    public string LastName { get; set; }              
    public string Email { get; set; }                 
    public string Phone { get; set; }                 
    public HttpPostedFileBase attachment { get; set; }

Post Action

public virtual ActionResult ContactUs(ContactUsModel Model)
{
 if (Model.attachment.HasFile())
 {
   //save the file

   //Send it as an attachment 
    Attachment messageAttachment = new Attachment(Model.attachment.InputStream,       Model.attachment.FileName);
  }
}

Finally the Extension method for checking the hasFile

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AtlanticCMS.Web.Common
{
     public static class ExtensionMethods 
     {
         public static bool HasFile(this HttpPostedFileBase file)
         {
             return file != null && file.ContentLength > 0;
         }        
     }
 }

Create intermediate folders if one doesn't exist

You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.

You can use File#mkdirs() method to create the directory: -

theFile.mkdirs();

Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

With JBoss 7.2(Undertow) and PrimeFaces 6.0 org.primefaces.webapp.filter.FileUploadFilter should be removed from web.xml and context param file uploader should be set to native:

<context-param>
    <param-name>primefaces.UPLOADER</param-name>
    <param-value>native</param-value>
</context-param>

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

I saw that someone was wondering how to do it for another controller.

In my case I had all of my email templates in the Views/Email folder, but you could modify this to pass in the controller in which you have views associated for.

public static string RenderViewToString(Controller controller, string viewName, object model)
    {
        var oldController = controller.RouteData.Values["controller"].ToString();

        if (controller.GetType() != typeof(EmailController))
            controller.RouteData.Values["controller"] = "Email";

        var oldModel = controller.ViewData.Model;
        controller.ViewData.Model = model;
        try
        {
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName,
                                                                           null);

                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);

                //Cleanup
                controller.ViewData.Model = oldModel;
                controller.RouteData.Values["controller"] = oldController;

                return sw.GetStringBuilder().ToString();
            }
        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);

            throw ex;
        }
    }

Essentially what this does is take a controller, such as AccountController and modify it to think it's an EmailController so that the code will look in the Views/Email folder. It's necessary to do this because the FindView method doesn't take a straight up path as a parameter, it wants a ControllerContext.

Once done rendering the string, it returns the AccountController back to its initial state to be used by the Response object.

WPF User Control Parent

If you just want to get a specific parent, not only the window, a specific parent in the tree structure, and also not using recursion, or hard break loop counters, you can use the following:

public static T FindParent<T>(DependencyObject current)
    where T : class 
{
    var dependency = current;

    while((dependency = VisualTreeHelper.GetParent(dependency) ?? LogicalTreeHelper.GetParent(dependency)) != null
        && !(dependency is T)) { }

    return dependency as T;
}

Just don't put this call in a constructor (since the Parent property is not yet initialized). Add it in the loading event handler, or in other parts of your application.

Change variable name in for loop using R

You could use assign, but using assign (or get) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.

  • with a list:

    A <- lapply (1 : 10, function (x) d + rnorm (3))
    
  • with a matrix:

    A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
    

C++ multiline string literal

Well ... Sort of. The easiest is to just use the fact that adjacent string literals are concatenated by the compiler:

const char *text =
  "This text is pretty long, but will be "
  "concatenated into just a single string. "
  "The disadvantage is that you have to quote "
  "each part, and newlines must be literal as "
  "usual.";

The indentation doesn't matter, since it's not inside the quotes.

You can also do this, as long as you take care to escape the embedded newline. Failure to do so, like my first answer did, will not compile:

const char *text2 =
  "Here, on the other hand, I've gone crazy \
and really let the literal span several lines, \
without bothering with quoting each line's \
content. This works, but you can't indent.";

Again, note those backslashes at the end of each line, they must be immediately before the line ends, they are escaping the newline in the source, so that everything acts as if the newline wasn't there. You don't get newlines in the string at the locations where you had backslashes. With this form, you obviously can't indent the text since the indentation would then become part of the string, garbling it with random spaces.

Calculate time difference in minutes in SQL Server

The following works as expected:

SELECT  Diff = CASE DATEDIFF(HOUR, StartTime, EndTime)
                    WHEN 0 THEN CAST(DATEDIFF(MINUTE, StartTime, EndTime) AS VARCHAR(10))
                    ELSE CAST(60 - DATEPART(MINUTE, StartTime) AS VARCHAR(10)) +
                        REPLICATE(',60', DATEDIFF(HOUR, StartTime, EndTime) - 1) + 
                        + ',' + CAST(DATEPART(MINUTE, EndTime) AS VARCHAR(10))
                END
FROM    (VALUES 
            (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
            (CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
            (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
        ) t (StartTime, EndTime);

To get 24 columns, you could use 24 case expressions, something like:

SELECT  [0] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 0
                        THEN DATEDIFF(MINUTE, StartTime, EndTime)
                    ELSE 60 - DATEPART(MINUTE, StartTime)
                END,
        [1] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 1 
                        THEN DATEPART(MINUTE, EndTime)
                    WHEN DATEDIFF(HOUR, StartTime, EndTime) > 1 THEN 60
                END,
        [2] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 2
                        THEN DATEPART(MINUTE, EndTime)
                    WHEN DATEDIFF(HOUR, StartTime, EndTime) > 2 THEN 60
                END -- ETC
FROM    (VALUES 
            (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
            (CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
            (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
        ) t (StartTime, EndTime);

The following also works, and may end up shorter than repeating the same case expression over and over:

WITH Numbers (Number) AS
(   SELECT  ROW_NUMBER() OVER(ORDER BY t1.N) - 1
    FROM    (VALUES (1), (1), (1), (1), (1), (1)) AS t1 (N)
            CROSS JOIN (VALUES (1), (1), (1), (1)) AS t2 (N)
), YourData AS
(   SELECT  StartTime, EndTime
    FROM    (VALUES 
                (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
                (CAST('09:45' AS TIME), CAST('18:59' AS TIME)),
                (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
            ) AS t (StartTime, EndTime)
), PivotData AS
(   SELECT  t.StartTime,
            t.EndTime,
            n.Number,
            MinuteDiff = CASE WHEN n.Number = 0 AND DATEDIFF(HOUR, StartTime, EndTime) = 0 THEN DATEDIFF(MINUTE, StartTime, EndTime)
                                WHEN n.Number = 0 THEN 60 - DATEPART(MINUTE, StartTime)
                                WHEN DATEDIFF(HOUR, t.StartTime, t.EndTime) <= n.Number THEN DATEPART(MINUTE, EndTime)
                                ELSE 60
                            END
    FROM    YourData AS t
            INNER JOIN Numbers AS n
                ON n.Number <= DATEDIFF(HOUR, StartTime, EndTime)
)
SELECT  *
FROM    PivotData AS d
        PIVOT 
        (   MAX(MinuteDiff)
            FOR Number IN 
            (   [0], [1], [2], [3], [4], [5], 
                [6], [7], [8], [9], [10], [11],
                [12], [13], [14], [15], [16], [17], 
                [18], [19], [20], [21], [22], [23]
            ) 
        ) AS pvt;

It works by joining to a table of 24 numbers, so the case expression doesn't need to be repeated, then rolling these 24 numbers back up into columns using PIVOT

Make: how to continue after a command fails?

make -k (or --keep-going on gnumake) will do what you are asking for, I think.

You really ought to find the del or rm line that is failing and add a -f to it to keep that error from happening to others though.

What should be the package name of android app?

Presently Package name starting with "com.example" is not allowed to upload in the app -store. Otherwise , all other package names starting with "com" are allowed .

Invalid application path

Problem was installing iis manager after .net framework aspnet_regiis had run. Run run aspnet_regiis from x64 .net framework directory

aspnet_regiis -iru // From x64 .net framework directory

IIS Manager can't configure .NET Compilation on .NET 4 Applications

PL/SQL print out ref cursor returned by a stored procedure

If you want to print all the columns in your select clause you can go with the autoprint command.

CREATE OR REPLACE PROCEDURE sps_detail_dtest(v_refcur OUT sys_refcursor)
AS
BEGIN
  OPEN v_refcur FOR 'select * from dummy_table';
END;

SET autoprint on;

--calling the procedure
VAR vcur refcursor;
DECLARE 
BEGIN
  sps_detail_dtest(vrefcur=>:vcur);
END;

Hope this gives you an alternate solution

How do I auto size a UIScrollView to fit its content

The size depends on the content loaded inside of it, and the clipping options. If its a textview, then it also depends on the wrapping, how many lines of text, the font size, and so on and on. Nearly impossible for you to compute yourself. The good news is, it is computed after the view is loaded and in the viewWillAppear. Before that, it's all unknown and and content size will be the same as frame size. But, in the viewWillAppear method and after (such as the viewDidAppear) the content size will be the actual.

How can I discover the "path" of an embedded resource?

I use the following method to grab embedded resources:

    protected static Stream GetResourceStream(string resourcePath)
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        List<string> resourceNames = new List<string>(assembly.GetManifestResourceNames());

        resourcePath = resourcePath.Replace(@"/", ".");
        resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath));

        if (resourcePath == null)
            throw new FileNotFoundException("Resource not found");

        return assembly.GetManifestResourceStream(resourcePath);
    }

I then call this with the path in the project:

GetResourceStream(@"DirectoryPathInLibrary/Filename")

How to add users to Docker container?

Adding user in docker and running your app under that user is very good practice for security point of view. To do that I would recommend below steps:

FROM node:10-alpine

# Copy source to container
RUN mkdir -p /usr/app/src

# Copy source code
COPY src /usr/app/src
COPY package.json /usr/app
COPY package-lock.json /usr/app

WORKDIR /usr/app

# Running npm install for production purpose will not run dev dependencies.
RUN npm install -only=production    

# Create a user group 'xyzgroup'
RUN addgroup -S xyzgroup

# Create a user 'appuser' under 'xyzgroup'
RUN adduser -S -D -h /usr/app/src appuser xyzgroup

# Chown all the files to the app user.
RUN chown -R appuser:xyzgroup /usr/app

# Switch to 'appuser'
USER appuser

# Open the mapped port
EXPOSE 3000

# Start the process
CMD ["npm", "start"]

Above steps is a full example of the copying NodeJS project files, creating a user group and user, assigning permissions to the user for the project folder, switching to the newly created user and running the app under that user.

How to find the extension of a file in C#?

This solution also helps in cases of more than one extension like "Avishay.student.DB"

                FileInfo FileInf = new FileInfo(filePath);
                string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");

How to find keys of a hash?

I believe you can loop through the properties of the object using for/in, so you could do something like this:

function getKeys(h) {
  Array keys = new Array();
  for (var key in h)
    keys.push(key);
  return keys;
}

what is the basic difference between stack and queue?

Stack is a LIFO (last in first out) data structure. The associated link to wikipedia contains detailed description and examples.

Queue is a FIFO (first in first out) data structure. The associated link to wikipedia contains detailed description and examples.

How to make execution pause, sleep, wait for X seconds in R?

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)

Yielding

> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 

How can I increment a date by one day in Java?

long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);

This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

How to make a rest post call from ReactJS code?

Here is an example: https://jsfiddle.net/69z2wepo/9888/

$.ajax({
    type: 'POST',
    url: '/some/url',
    data: data
  })
  .done(function(result) {
    this.clearForm();
    this.setState({result:result});   
  }.bind(this)
  .fail(function(jqXhr) {
    console.log('failed to register');
  });

It used jquery.ajax method but you can easily replace it with AJAX based libs like axios, superagent or fetch.

How to parse a JSON string into JsonNode in Jackson?

A slight variation on Richards answer but readTree can take a string so you can simplify it to:

ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"k1\":\"v1\"}");

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

BackgroundWorker vs background Thread

Some of my thoughts...

  1. Use BackgroundWorker if you have a single task that runs in the background and needs to interact with the UI. The task of marshalling data and method calls to the UI thread are handled automatically through its event-based model. Avoid BackgroundWorker if...
    • your assembly does not have or does not interact directly with the UI,
    • you need the thread to be a foreground thread, or
    • you need to manipulate the thread priority.
  2. Use a ThreadPool thread when efficiency is desired. The ThreadPool helps avoid the overhead associated with creating, starting, and stopping threads. Avoid using the ThreadPool if...
    • the task runs for the lifetime of your application,
    • you need the thread to be a foreground thread,
    • you need to manipulate the thread priority, or
    • you need the thread to have a fixed identity (aborting, suspending, discovering).
  3. Use the Thread class for long-running tasks and when you require features offered by a formal threading model, e.g., choosing between foreground and background threads, tweaking the thread priority, fine-grained control over thread execution, etc.

How to Automatically Start a Download in PHP?

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

python and sys.argv

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

What is a wrapper class?

A wrapper class is a class that "wraps" around something else, just like its name.

The more formal definition of it would be a class that implements the Adapter Pattern. This allows you to modify one set of APIs into a more usable, readable form. For example, in C#, if you want to use the native Windows API, it helps to wrap it into a class that conforms to the .NET design guidelines.

Javascript get object key name

Variable i is your looking key name.

Terminating a script in PowerShell

I realize this is an old post but I find myself coming back to this thread a lot as it is one of the top search results when searching for this topic. However, I always leave more confused then when I came due to the conflicting information. Ultimately I always have to perform my own tests to figure it out. So this time I will post my findings.

TL;DR Most people will want to use Exit to terminate a running scripts. However, if your script is merely declaring functions to later be used in a shell, then you will want to use Return in the definitions of said functions.

Exit vs Return vs Break

  • Exit: This will "exit" the currently running context. If you call this command from a script it will exit the script. If you call this command from the shell it will exit the shell.

    If a function calls the Exit command it will exit what ever context it is running in. So if that function is only called from within a running script it will exit that script. However, if your script merely declares the function so that it can be used from the current shell and you run that function from the shell, it will exit the shell because the shell is the context in which the function contianing the Exit command is running.

    Note: By default if you right click on a script to run it in PowerShell, once the script is done running, PowerShell will close automatically. This has nothing to do with the Exit command or anything else in your script. It is just a default PowerShell behavior for scripts being ran using this specific method of running a script. The same is true for batch files and the Command Line window.

  • Return: This will return to the previous call point. If you call this command from a script (outside any functions) it will return to the shell. If you call this command from the shell it will return to the shell (which is the previous call point for a single command ran from the shell). If you call this command from a function it will return to where ever the function was called from.

    Execution of any commands after the call point that it is returned to will continue from that point. If a script is called from the shell and it contains the Return command outside any functions then when it returns to the shell there are no more commands to run thus making a Return used in this way essentially the same as Exit.

  • Break: This will break out of loops and switch cases. If you call this command while not in a loop or switch case it will break out of the script. If you call Break inside a loop that is nested inside a loop it will only break out of the loop it was called in.

    There is also an interesting feature of Break where you can prefix a loop with a label and then you can break out of that labeled loop even if the Break command is called within several nested groups within that labeled loop.

    While ($true) {
        # Code here will run
    
        :myLabel While ($true) {
            # Code here will run
    
            While ($true) {
                # Code here will run
    
                While ($true) {
                    # Code here will run
                    Break myLabel
                    # Code here will not run
                }
    
                # Code here will not run
            }
    
            # Code here will not run
        }
    
        # Code here will run
    }
    

What is the maximum possible length of a query string?

Different web stacks do support different lengths of http-requests. I know from experience that the early stacks of Safari only supported 4000 characters and thus had difficulty handling ASP.net pages because of the USER-STATE. This is even for POST, so you would have to check the browser and see what the stack limit is. I think that you may reach a limit even on newer browsers. I cannot remember but one of them (IE6, I think) had a limit of 16-bit limit, 32,768 or something.

Meaning of "referencing" and "dereferencing" in C

Referencing

& is the reference operator. It will refer the memory address to the pointer variable.

Example:

int *p;
int a=5;
p=&a; // Here Pointer variable p refers to the address of integer variable a.

Dereferencing

Dereference operator * is used by the pointer variable to directly access the value of the variable instead of its memory address.

Example:

int *p;
int a=5;
p=&a;
int value=*p; // Value variable will get the value of variable a that pointer variable p pointing to.

How to monitor the memory usage of Node.js?

On Linux/Unix (note: Mac OS is a Unix) use top and press M (Shift+M) to sort processes by memory usage.

On Windows use the Task Manager.

replace String with another in java

Replacing one string with another can be done in the below methods

Method 1: Using String replaceAll

 String myInput = "HelloBrother";
 String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
 ---OR---
 String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
 System.out.println("My Output is : " +myOutput);       

Method 2: Using Pattern.compile

 import java.util.regex.Pattern;
 String myInput = "JAVAISBEST";
 String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
 ---OR -----
 String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
 System.out.println("My Output is : " +myOutputWithRegEX);           

Method 3: Using Apache Commons as defined in the link below:

http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)

REFERENCE

Calculate Age in MySQL (InnoDb)

If the value is stored as a DATETIME data type:

SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age 
  FROM YOUR_TABLE

Less precise when you consider leap years:

SELECT DATEDIFF(CURRENT_DATE, STR_TO_DATE(t.birthday, '%d-%m-%Y'))/365 AS ageInYears
  FROM YOUR_TABLE t 

Get only filename from url in php without any variable values which exist in the url

Your URL:

$url = 'http://learner.com/learningphp.php?lid=1348';
$file_name = basename(parse_url($url, PHP_URL_PATH));
echo $file_name;

output: learningphp.php

How can I clone a JavaScript object except for one key?

If you use Babel you can use the following syntax to copy property b from x into variable b and then copy rest of properties into variable y:

let x = {a: 1, b: 2, c: 3, z:26};
let {b, ...y} = x;

and it will be transpiled into:

"use strict";

function _objectWithoutProperties(obj, keys) {
  var target = {};
  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }
  return target;
}

var x = { a: 1, b: 2, c: 3, z: 26 };
var b = x.b;

var y = _objectWithoutProperties(x, ["b"]);

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

_x000D_
_x000D_
$("h3").text("context")
_x000D_
_x000D_
_x000D_

Just use method "text()".

The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

http://api.jquery.com/text/

Send JSON data from Javascript to PHP?

I found easy way to do but I know it not perfect

1.assign json to

if you JSON is

var data = [
    {key:1,n: "Eve"}
    ,{key:2,n:"Mom"} 
];

in ---main.php ----

    <form action="second.php" method="get" >
                <input name="data" type="text" id="data" style="display:none" >
                <input id="submit" type="submit"  style="display:none" >

     </form>

    <script>

      var data = [
        {key:1,n: "Eve"}
        ,{key:2,n:"Mom"} ];

       function setInput(data){
         var input = document.getElementById('data');
         input.value = JSON.stringify(data);
        var submit =document.getElementById('submit');

       //to submit and goto second page
        submit.click();

    }


   //call function
   setInput(data);

    </script>

in ------ second.php -----

    <script>

printJson();

function printJson(){
 var data = getUrlVars()["data"];

//decode uri to normal character
data =  decodeURI(data);
//for special character , / ? : @ & = + $ #
data =  decodeURIComponent(data);
//remove  " ' " at first and last in string before parse string to JSON
data = data.slice(1,-1);
data = JSON.parse(data);
alert(JSON.stringify(data));

}

//read get variable form url
//credit http://papermashup.com/read-url-get-variables-withjavascript/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}

</script>

Excel formula to display ONLY month and year?

Try the formula

=TEXT(TODAY(),"MMYYYY")

"python" not recognized as a command

Make sure you click on Add python.exe to path during install, and select:

"Will be installed on local hard drive"

It fixed my problem, hope it helps...

How to fill color in a cell in VBA?

You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

Excel VBA to Export Selected Sheets to PDF

I'm pretty mixed up on this. I am also running Excel 2010. I tried saving two sheets as a single PDF using:

    ThisWorkbook.Sheets(Array(1,2)).Select
    **Selection**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False

but I got nothing but blank pages. It saved both sheets, but nothing on them. It wasn't until I used:

    ThisWorkbook.Sheets(Array(1,2)).Select
    **ActiveSheet**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False

that I got a single PDF file with both sheets.

I tried manually saving these two pages using Selection in the Options dialog to save the two sheets I had selected, but got blank pages. When I tried the Active Sheet(s) option, I got what I wanted. When I recorded this as a macro, Excel used ActiveSheet when it successfully published the PDF. What gives?

Makefile If-Then Else and Loops

Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find
endif

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

How to set a cookie for another domain

In this link, we will find the solution Link.

setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "b.com", 1);

How to convert a 3D point into 2D perspective projection?

You might want to debug your system with spheres to determine whether or not you have a good field of view. If you have it too wide, the spheres with deform at the edges of the screen into more oval forms pointed toward the center of the frame. The solution to this problem is to zoom in on the frame, by multiplying the x and y coordinates for the 3 dimensional point by a scalar and then shrinking your object or world down by a similar factor. Then you get the nice even round sphere across the entire frame.

I'm almost embarrassed that it took me all day to figure this one out and I was almost convinced that there was some spooky mysterious geometric phenomenon going on here that demanded a different approach.

Yet, the importance of calibrating the zoom-frame-of-view coefficient by rendering spheres cannot be overstated. If you do not know where the "habitable zone" of your universe is, you will end up walking on the sun and scrapping the project. You want to be able to render a sphere anywhere in your frame of view an have it appear round. In my project, the unit sphere is massive compared to the region that I'm describing.

Also, the obligatory wikipedia entry: Spherical Coordinate System

Storing sex (gender) in database

In medicine there are four genders: male, female, indeterminate, and unknown. You mightn't need all four but you certainly need 1, 2, and 4. It's not appropriate to have a default value for this datatype. Even less to treat it as a Boolean with 'is' and 'isn't' states.

How to wait till the response comes from the $http request, in angularjs?

FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put

myservice.$loaded().then(function() {$rootScope.myservice = myservice;});

and in the view I just did

ng-if="myservice" ng-init="somevar=myfunct()"

in the first/parent view element/wrapper so the controller can run everything inside

myfunct()

without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.

Finding height in Binary Search Tree

 int getHeight(Node* root)
 {
   if(root == NULL) return -1;
   else             return max(getHeight(root->left), getHeight(root->right)) + 1;
 }

Print raw string from variable? (not getting the answers)

try this. Based on what type of output you want. sometime you may not need single quote around printed string.

test = "qweqwe\n1212as\t121\\2asas"
print(repr(test)) # output: 'qweqwe\n1212as\t121\\2asas'
print( repr(test).strip("'"))  # output: qweqwe\n1212as\t121\\2asas

How to get first two characters of a string in oracle query?

select substr(orderno,1,2) from shipment;

You may want to have a look at the documentation too.

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

How to make an Asynchronous Method return a value?

There are a few ways of doing that... the simplest is to have the async method also do the follow-on operation. Another popular approach is to pass in a callback, i.e.

void RunFooAsync(..., Action<bool> callback) {
     // do some stuff
     bool result = ...

     if(callback != null) callback(result);
}

Another approach would be to raise an event (with the result in the event-args data) when the async operation is complete.

Also, if you are using the TPL, you can use ContinueWith:

Task<bool> outerTask = ...;
outerTask.ContinueWith(task =>
{
    bool result = task.Result;
    // do something with that
});

Insert the same fixed value into multiple rows

UPDATE `table` SET table_column='test';

How to run a makefile in Windows?

Firstly, add path of visual studio common tools (c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools) into the system path. To learn how to add a path into system path, please check this website: http://www.computerhope.com/issues/ch000549.htm. You just need to this once.

After that, whenever you need, open a command line and execute vsvars32.bat to add all required visual studio tools' paths into the system path.

Then, you can call nmake -f makefile.mak

PS: Path of visual studio common tools might be different in your system. Please change it accordingly.

How to center buttons in Twitter Bootstrap 3?

add to your style:

display: table; margin: 0 auto;

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

While the json begins with "[" and ends with "]" that means this is the Json Array, use JSONArray instead:

JSONArray jsonArray = new JSONArray(JSON);

And then you can map it with the List Test Object if you need:

ObjectMapper mapper = new ObjectMapper();
List<TestExample> listTest = mapper.readValue(String.valueOf(jsonArray), List.class);

Why are Python's 'private' methods not actually private?

Why are Python's 'private' methods not actually private?

As I understand it, they can't be private. How could privacy be enforced?

The obvious answer is "private members can only be accessed through self", but that wouldn't work - self is not special in Python, it is nothing more than a commonly-used name for the first parameter of a function.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

xhr.send(null);
if (xhr.status == 204) 
    Reload();
else 
    dropdown.innerHTML = xhr.responseText;

Here is the Reload() function:

function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
    }

submit a form in a new tab

<form target="_blank" [....]

will submit the form in a new tab... I am not sure if is this what you are looking for, please explain better...

How to pass multiple parameters in thread in VB

Dim evaluator As New Thread(Sub() Me.testthread(goodList, 1))
With evaluator
.IsBackground = True ' not necessary...
.Start()
End With

What EXACTLY is meant by "de-referencing a NULL pointer"?

It means

myclass *p = NULL;
*p = ...;  // illegal: dereferencing NULL pointer
... = *p;  // illegal: dereferencing NULL pointer
p->meth(); // illegal: equivalent to (*p).meth(), which is dereferencing NULL pointer

myclass *p = /* some legal, non-NULL pointer */;
*p = ...;  // Ok
... = *p;  // Ok
p->meth(); // Ok, if myclass::meth() exists

basically, almost anything involving (*p) or implicitly involving (*p), e.g. p->... which is a shorthand for (*p). ...; except for pointer declaration.

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

"multiple target patterns" Makefile error

I just want to add, if you get this error because you are using Cygwin make and auto-generated files, you can fix it with the following sed,

sed -e 's@\\\([^ ]\)@/\1@g' -e 's@[cC]:@/cygdrive/c@' -i filename.d

You may need to add more characters than just space to the escape list in the first substitution but you get the idea. The concept here is that /cygdrive/c is an alias for c: that cygwin's make will recognize.

And may as well throw in

-e 's@^ \+@\t@'

just in case you did start with spaces on accident (although I /think/ this will usually be a "missing separator" error).

How do I check form validity with angularjs?

Example

<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>
  </form>
</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {
       return;
     }
  }]);
</script>

How to [recursively] Zip a directory in PHP?

Try this link <-- MORE SOURCE CODE HERE

/** Include the Pear Library for Zip */
include ('Archive/Zip.php');

/** Create a Zipping Object...
* Name of zip file to be created..
* You can specify the path too */
$obj = new Archive_Zip('test.zip');
/**
* create a file array of Files to be Added in Zip
*/
$files = array('black.gif',
'blue.gif',
);

/**
* creating zip file..if success do something else do something...
* if Error in file creation ..it is either due to permission problem (Solution: give 777 to that folder)
* Or Corruption of File Problem..
*/

if ($obj->create($files)) {
// echo 'Created successfully!';
} else {
//echo 'Error in file creation';
}

?>; // We'll be outputting a ZIP
header('Content-type: application/zip');

// It will be called test.zip
header('Content-Disposition: attachment; filename="test.zip"');

//read a file and send
readfile('test.zip');
?>;

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

How to extract extension from filename string in Javascript?

get the value in the variable & then separate its extension just like this.

var find_file_ext=document.getElementById('filename').value;
var file_ext=/[^.]+$/.exec(find_file_ext); 

This will help you.

Adding a month to a date in T SQL

DATEADD is the way to go with this

See the W3Schools tutorial: http://www.w3schools.com/sql/func_dateadd.asp

How to reset a select element with jQuery

Reset single select field to default option.

<select id="name">
    <option>select something</option>
    <option value="1" >something 1</option>
    <option value="2" selected="selected" >Default option</option>
</select>
<script>
    $('name').val( $('name').find("option[selected]").val() );
</script>


Or if you want to reset all form fields to the default option:

<script>
    $('select').each( function() {
        $(this).val( $(this).find("option[selected]").val() );
    });
</script>

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

How to execute a MySQL command from a shell script?

To "automate" the process of importing the generated .sql file, while avoiding all the traps that can be hidden in trying to pass files through stdin and stdout, just tell MySQL to execute the generated .sql file using the SOURCE command in MySQL.

The syntax in the short, but excellent, answer, from Kshitij Sood, gives the best starting point. In short, modify the OP's command according to Kshitij Sood's syntax and replace the commands in that with the SOURCE command:

#!/bin/bash
mysql -u$user -p$password $dbname -Bse "SOURCE ds_fbids.sql
SOURCE ds_fbidx.sql"

If the database name is included in the generated .sql file, it can be dropped from the command.

The presumption here is that the generated file is valid as an .sql file on its own. By not having the file redirected, piped, or in any other manner handled by the shell, there is no issue with needing to escape any of the characters in the generated output because of the shell. The rules with respect to what needs to be escaped in an .sql file, of course, still apply.

How to deal with the security issues around the password on the command line, or in a my.cnf file, etc., has been well addressed in other answers, with some excellent suggestions. My favorite answer, from Danny, covers that, including how to handle the issue when dealing with cron jobs, or anything else.


To address a comment (question?) on the short answer I mentioned: No, it cannot be used with a HEREDOC syntax, as that shell command is given. HEREDOC can be used in the redirection version syntax, (without the -Bse option), since I/O redirection is what HEREDOC is built around. If you need the functionality of HEREDOC, it would be better to use it in the creation of a .sql file, even if it's a temporary one, and use that file as the "command" to execute with the MySQL batch line.

#!/bin/bash
cat >temp.sql <<SQL_STATEMENTS
...
SELECT \`column_name\` FROM \`table_name\` WHERE \`column_name\`='$shell_variable';
...
SQL_STATEMENTS
mysql -u $user -p$password $db_name -Be "SOURCE temp.sql"
rm -f temp.sql

Bear in mind that because of shell expansion you can use shell and environment variables within the HEREDOC. The down-side is that you must escape each and every backtick. MySQL uses them as the delimiters for identifiers but the shell, which gets the string first, uses them as executable command delimiters. Miss the escape on a single backtick of the MySQL commands, and the whole thing explodes with errors. The whole issue can be solved by using a quoted LimitString for the HEREDOC:

#!/bin/bash
cat >temp.sql <<'SQL_STATEMENTS'
...
SELECT `column_name` FROM `table_name` WHERE `column_name`='constant_value';
...
SQL_STATEMENTS
mysql -u $user -p$password $db_name -Be "SOURCE temp.sql"
rm -f temp.sql

Removing shell expansion that way eliminates the need to escape the backticks, and other shell-special characters. It also removes the ability to use shell and environment variables within it. That pretty much removes the benefits of using a HEREDOC inside the shell script to begin with.

The other option is to use the multi-line quoted strings allowed in Bash with the batch syntax version (with the -Bse). I don't know other shells, so I cannot say if they work therein as well. You would need to use this for executing more than one .sql file with the SOURCE command anyway, since that is not terminated by a ; as other MySQL commands are, and only one is allowed per line. The multi-line string can be either single or double quoted, with the normal effects on shell expansion. It also has the same caveats as using the HEREDOC syntax does for backticks, etc.

A potentially better solution would be to use a scripting language, Perl, Python, etc., to create the .sql file, as the OP did, and SOURCE that file using the simple command syntax at the top. The scripting languages are much better at string manipulation than the shell is, and most have in-built procedures to handle the quoting and escaping needed when dealing with MySQL.

How do I determine height and scrolling position of window in jQuery?

from http://api.jquery.com/height/ (Note: The difference between the use for the window and the document object)

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

from http://api.jquery.com/scrollTop/

$(window).scrollTop() // return the number of pixels scrolled vertically

Better way to remove specific characters from a Perl string

Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.

You take that string, call it $place_older say. And then when you want to eliminate the text, you call quotemeta, and you use that value to substitute:

my $subs = quotemeta $place_holder;
s/$subs//g;

Typescript import/as vs import/require?

These are mostly equivalent, but import * has some restrictions that import ... = require doesn't.

import * as creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or newable - it only has properties. If you're trying to import a function or class, you should use

import express = require('express');

or (depending on your module loader)

import express from 'express';

Attempting to use import * as express and then invoking express() is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.

Do you use source control for your database items?

Wow, so many answers. For solid database versioning you need to version control the code that changes your database. Some CMS offer configuration management tools, such as the one in Drupal 8. Here is an overview with practical steps to arrange your workflow and ensure the database configuration is versioned, even in team environments:

How can I find the product GUID of an installed MSI setup?

For upgrade code retrieval: How can I find the Upgrade Code for an installed MSI file?


Short Version

The information below has grown considerably over time and may have become a little too elaborate. How to get product codes quickly? (four approaches):

1 - Use the Powershell "one-liner"

Scroll down for screenshot and step-by-step. Disclaimer also below - minor or moderate risks depending on who you ask. Works OK for me. Any self-repair triggered by this option should generally be possible to cancel. The package integrity checks triggered does add some event log "noise" though. Note! IdentifyingNumber is the ProductCode (WMI peculiarity).

get-wmiobject Win32_Product | Sort-Object -Property Name |Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

Quick start of Powershell: hold Windows key, tap R, type in "powershell" and press Enter

2 - Use VBScript (script on github.com)

Described below under "Alternative Tools" (section 3). This option may be safer than Powershell for reasons explained in detail below. In essence it is (much) faster and not capable of triggering MSI self-repair since it does not go through WMI (it accesses the MSI COM API directly - at blistering speed). However, it is more involved than the Powershell option (several lines of code).

3 - Registry Lookup

Some swear by looking things up in the registry. Not my recommended approach - I like going through proper APIs (or in other words: OS function calls). There are always weird exceptions accounted for only by the internals of the API-implementation:

  • HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
  • HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
  • HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall

4 - Original MSI File / WiX Source

You can find the Product Code in the Property table of any MSI file (and any other property as well). However, the GUID could conceivably (rarely) be overridden by a transform applied at install time and hence not match the GUID the product is registered under (approach 1 and 2 above will report the real product code - that is registered with Windows - in such rare scenarios).

You need a tool to view MSI files. See towards the bottom of the following answer for a list of free tools you can download (or see quick option below): How can I compare the content of two (or more) MSI files?

UPDATE: For convenience and need for speed :-), download SuperOrca without delay and fuss from this direct-download hotlink - the tool is good enough to get the job done - install, open MSI and go straight to the Property table and find the ProductCode row (please always virus check a direct-download hotlink - obviously - you can use virustotal.com to do so - online scan utilizing dozens of anti-virus and malware suites to scan what you upload).

Orca is Microsoft's own tool, it is installed with Visual Studio and the Windows SDK. Try searching for Orca-x86_en-us.msi - under Program Files (x86) and install the MSI if found.

  • Current path: C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x86
  • Change version numbers as appropriate

And below you will find the original answer which "organically grew" into a lot of detail.

Maybe see "Uninstall MSI Packages" section below if this is the task you need to perform.


Retrieve Product Codes

UPDATE: If you also need the upgrade code, check this answer: How can I find the Upgrade Code for an installed MSI file? (retrieves associated product codes, upgrade codes & product names in a table output - similar to the one below).

  • Can't use PowerShell? See "Alternative Tools" section below.
  • Looking to uninstall? See "Uninstall MSI packages" section below.

Fire up Powershell (hold down the Windows key, tap R, release the Windows key, type in "powershell" and press OK) and run the command below to get a list of installed MSI package product codes along with the local cache package path and the product name (maximize the PowerShell window to avoid truncated names).

Before running this command line, please read the disclaimer below (nothing dangerous, just some potential nuisances). Section 3 under "Alternative Tools" shows an alternative non-WMI way to get the same information using VBScript. If you are trying to uninstall a package there is a section below with some sample msiexec.exe command lines:

get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

The output should be similar to this:

enter image description here

Note! For some strange reason the "ProductCode" is referred to as "IdentifyingNumber" in WMI. So in other words - in the picture above the IdentifyingNumber is the ProductCode.

If you need to run this query remotely against lots of remote computer, see "Retrieve Product Codes From A Remote Computer" section below.

DISCLAIMER (important, please read before running the command!): Due to strange Microsoft design, any WMI call to Win32_Product (like the PowerShell command below) will trigger a validation of the package estate. Besides being quite slow, this can in rare cases trigger an MSI self-repair. This can be a small package or something huge - like Visual Studio. In most cases this does not happen - but there is a risk. Don't run this command right before an important meeting - it is not ever dangerous (it is read-only), but it might lead to a long repair in very rare cases (I think you can cancel the self-repair as well - unless actively prevented by the package in question, but it will restart if you call Win32_Product again and this will persist until you let the self-repair finish - sometimes it might continue even if you do let it finish: How can I determine what causes repeated Windows Installer self-repair?).

And just for the record: some people report their event logs filling up with MsiInstaller EventID 1035 entries (see code chief's answer) - apparently caused by WMI queries to the Win32_Product class (personally I have never seen this). This is not directly related to the Powershell command suggested above, it is in context of general use of the WIM class Win32_Product.

You can also get the output in list form (instead of table):

get-wmiobject -class Win32_Product

In this case the output is similar to this:

enter image description here


Retrieve Product Codes From A Remote Computer

In theory you should just be able to specify a remote computer name as part of the command itself. Here is the same command as above set up to run on the machine "RemoteMachine" (-ComputerName RemoteMachine section added):

get-wmiobject Win32_Product -ComputerName RemoteMachine | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

This might work if you are running with domain admin rights on a proper domain. In a workgroup environment (small office / home network), you probably have to add user credentials directly to the WMI calls to make it work.

Additionally, remote connections in WMI are affected by (at least) the Windows Firewall, DCOM settings, and User Account Control (UAC) (plus any additional non-Microsoft factors - for instance real firewalls, third party software firewalls, security software of various kinds, etc...). Whether it will work or not depends on your exact setup.

UPDATE: An extensive section on remote WMI running can be found in this answer: How can I find the Upgrade Code for an installed MSI file?. It appears a firewall rule and suppression of the UAC prompt via a registry tweak can make things work in a workgroup network environment. Not recommended changes security-wise, but it worked for me.


Alternative Tools

PowerShell requires the .NET framework to be installed (currently in version 3.5.1 it seems? October, 2017). The actual PowerShell application itself can also be missing from the machine even if .NET is installed. Finally I believe PowerShell can be disabled or locked by various system policies and privileges.

If this is the case, you can try a few other ways to retrieve product codes. My preferred alternative is VBScript - it is fast and flexible (but can also be locked on certain machines, and scripting is always a little more involved than using tools).

  1. Let's start with a built-in Windows WMI tool: wbemtest.exe.
  • Launch wbemtest.exe (Hold down the Windows key, tap R, release the Windows key, type in "wbemtest.exe" and press OK).
  • Click connect and then OK (namespace defaults to root\cimv2), and click "connect" again.
  • Click "Query" and type in this WQL command (SQL flavor): SELECT IdentifyingNumber,Name,Version FROM Win32_Product and click "Use" (or equivalent - the tool will be localized).
  • Sample output screenshot (truncated). Not the nicest formatting, but you can get the data you need. IdentifyingNumber is the MSI product code:

wbemtest.exe

  1. Next, you can try a custom, more full featured WMI tool such as WMIExplorer.exe
  • This is not included in Windows. It is a very good tool, however. Recommended.
  • Check it out at: https://github.com/vinaypamnani/wmie2/releases
  • Launch the tool, click Connect, double click ROOT\CIMV2
  • From the "Query tab", type in the following query SELECT IdentifyingNumber,Name,Version FROM Win32_Product and press Execute.
  • Screenshot skipped, the application requires too much screen real estate.
  1. Finally you can try a VBScript to access information via the MSI automation interface (core feature of Windows - it is unrelated to WMI).
  • Copy the below script and paste into a *.vbs file on your desktop, and try to run it by double clicking. Your desktop must be writable for you, or you can use any other writable location.
  • This is not a great VBScript. Terseness has been preferred over error handling and completeness, but it should do the job with minimum complexity.
  • The output file is created in the folder where you run the script from (folder must be writable). The output file is called msiinfo.csv.
  • Double click the file to open in a spreadsheet application, select comma as delimiter on import - OR - just open the file in Notepad or any text viewer.
  • Opening in a spreadsheet will allow advanced sorting features.
  • This script can easily be adapted to show a significant amount of further details about the MSI installation. A demonstration of this can be found here: how to find out which products are installed - newer product are already installed MSI windows.
' Retrieve all ProductCodes (with ProductName and ProductVersion)
Set fso = CreateObject("Scripting.FileSystemObject")
Set output = fso.CreateTextFile("msiinfo.csv", True, True)
Set installer = CreateObject("WindowsInstaller.Installer")

On Error Resume Next ' we ignore all errors

For Each product In installer.ProductsEx("", "", 7)
   productcode = product.ProductCode
   name = product.InstallProperty("ProductName")
   version=product.InstallProperty("VersionString")
   output.writeline (productcode & ", " & name & ", " & version)
Next

output.Close

I can't think of any further general purpose options to retrieve product codes at the moment, please add if you know of any. Just edit inline rather than adding too many comments please.

You can certainly access this information from within your application by calling the MSI automation interface (COM based) OR the C++ MSI installer functions (Win32 API). Or even use WMI queries from within your application like you do in the samples above using PowerShell, wbemtest.exe or WMIExplorer.exe.


Uninstall MSI Packages

If what you want to do is to uninstall the MSI package you found the product code for, you can do this as follows using an elevated command prompt (search for cmd.exe, right click and run as admin):

Option 1: Basic, interactive uninstall without logging (quick and easy):

msiexec.exe /x {00000000-0000-0000-0000-00000000000C}

Quick Parameter Explanation:

/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall

You can also enable (verbose) logging and run in silent mode if you want to, leading us to option 2:

Option 2: Silent uninstall with verbose logging (better for batch files):

msiexec.exe /x {00000000-0000-0000-0000-00000000000C} /QN /L*V "C:\My.log" REBOOT=ReallySuppress

Quick Parameter Explanation:

/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall
/QN = run completely silently
/L*V "C:\My.log"= verbose logging at specified path
REBOOT=ReallySuppress = avoid unexpected, sudden reboot

There is a comprehensive reference for MSI uninstall here (various different ways to uninstall MSI packages): Uninstalling an MSI file from the command line without using msiexec. There is a plethora of different ways to uninstall.

If you are writing a batch file, please have a look at section 3 in the above, linked answer for a few common and standard uninstall command line variants.

And a quick link to msiexec.exe (command line options) (overview of the command line for msiexec.exe from MSDN). And the Technet version as well.


Retrieving other MSI Properties / Information (f.ex Upgrade Code)

UPDATE: please find a new answer on how to find the upgrade code for installed packages instead of manually looking up the code in MSI files. For installed packages this is much more reliable. If the package is not installed, you still need to look in the MSI file (or the source file used to compile the MSI) to find the upgrade code. Leaving in older section below:

If you want to get the UpgradeCode or other MSI properties, you can open the cached installation MSI for the product from the location specified by "LocalPackage" in the image show above (something like: C:\WINDOWS\Installer\50c080ae.msi - it is a hex file name, unique on each system). Then you look in the "Property table" for UpgradeCode (it is possible for the UpgradeCode to be redefined in a transform - to be sure you get the right value you need to retrieve the code programatically from the system - I will provide a script for this shortly. However, the UpgradeCode found in the cached MSI is generally correct).

To open the cached MSI files, use Orca or another packaging tool. Here is a discussion of different tools (any of them will do): What installation product to use? InstallShield, WiX, Wise, Advanced Installer, etc. If you don't have such a tool installed, your fastest bet might be to try Super Orca (it is simple to use, but not extensively tested by me).

UPDATE: here is a new answer with information on various free products you can use to view MSI files: How can I compare the content of two (or more) MSI files?

If you have Visual Studio installed, try searching for Orca-x86_en-us.msi - under Program Files (x86) - and install it (this is Microsoft's own, official MSI viewer and editor). Then find Orca in the start menu. Go time in no time :-). Technically Orca is installed as part of Windows SDK (not Visual Studio), but Windows SDK is bundled with the Visual Studio install. If you don't have Visual Studio installed, perhaps you know someone who does? Just have them search for this MSI and send you (it is a tiny half mb file) - should take them seconds. UPDATE: you need several CAB files as well as the MSI - these are found in the same folder where the MSI is found. If not, you can always download the Windows SDK (it is free, but it is big - and everything you install will slow down your PC). I am not sure which part of the SDK installs the Orca MSI. If you do, please just edit and add details here.



Similar topics (for reference and easy access - I should clean this list up):

Can't update data-attribute value

I had the same problem of the html data tag not updating when i was using jquery But changing the code that does the actual work from jquery to javascript worked.

Try using this when the button is clicked: (Note that the main code is Javascripts setAttribute() function.)

function increment(q) {

    //increment current num by adding with 1
    q = q+1;

    //change data attribute using JS setAttribute function
    div.setAttribute('data-num',q);

    //refresh data-num value (get data-num value again using JS getAttribute function)
    num = parseInt(div.getAttribute('data-num'));

    //show values
    console.log("(After Increment) Current Num: "+num);

}

//get variables, set as global vars
var div = document.getElementById('foo');
var num = parseInt(div.getAttribute('data-num'));

//increment values using click
$("#changeData").on('click',function(){

    //pass current data-num as parameter
    increment(num);

});

Windows batch: formatted date into variable

If powershell is available, you can use codes below:

# get date
$BuildDate=(get-date -format "yyMMdd")
echo BuildDate=$BuildDate

# get time
$BuildTime=(get-date -format "hhmmss")
echo BuildTime=$BuildTime

Here is the result:

BuildDate=200518
BuildTime=115919

Collections.sort with multiple fields

A lot of answers above have fields compared in single comparator method which is not actually working. There are some answers though with different comparators implemented for each field, I am posting this because this example would be much more clearer and simple to understand I am believing.

class Student{
    Integer bornYear;
    Integer bornMonth;
    Integer bornDay;
    public Student(int bornYear, int bornMonth, int bornDay) {

        this.bornYear = bornYear;
        this.bornMonth = bornMonth;
        this.bornDay = bornDay;
    }
    public Student(int bornYear, int bornMonth) {

        this.bornYear = bornYear;
        this.bornMonth = bornMonth;

    }
    public Student(int bornYear) {

        this.bornYear = bornYear;

    }
    public Integer getBornYear() {
        return bornYear;
    }
    public void setBornYear(int bornYear) {
        this.bornYear = bornYear;
    }
    public Integer getBornMonth() {
        return bornMonth;
    }
    public void setBornMonth(int bornMonth) {
        this.bornMonth = bornMonth;
    }
    public Integer getBornDay() {
        return bornDay;
    }
    public void setBornDay(int bornDay) {
        this.bornDay = bornDay;
    }
    @Override
    public String toString() {
        return "Student [bornYear=" + bornYear + ", bornMonth=" + bornMonth + ", bornDay=" + bornDay + "]";
    }


}
class TestClass
{       

    // Comparator problem in JAVA for sorting objects based on multiple fields 
    public static void main(String[] args)
    {
        int N,c;// Number of threads

        Student s1=new Student(2018,12);
        Student s2=new Student(2018,12);
        Student s3=new Student(2018,11);
        Student s4=new Student(2017,6);
        Student s5=new Student(2017,4);
        Student s6=new Student(2016,8);
        Student s7=new Student(2018);
        Student s8=new Student(2017,8);
        Student s9=new Student(2017,2);
        Student s10=new Student(2017,9);

        List<Student> studentList=new ArrayList<>();
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);
        studentList.add(s4);
        studentList.add(s5);
        studentList.add(s6);
        studentList.add(s7);
        studentList.add(s8);
        studentList.add(s9);
        studentList.add(s10);

        Comparator<Student> byMonth=new Comparator<Student>() {
            @Override
            public int compare(Student st1,Student st2) {
                if(st1.getBornMonth()!=null && st2.getBornMonth()!=null) {
                    return st2.getBornMonth()-st1.getBornMonth();
                }
                else if(st1.getBornMonth()!=null) {
                    return 1;
                }
                else {
                    return -1;
                }
        }};

        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student st1,Student st2) {
                return st2.getBornYear()-st1.getBornYear();
        }}.thenComparing(byMonth));

        System.out.println("The sorted students list in descending is"+Arrays.deepToString(studentList.toArray()));



    }

}

OUTPUT

The sorted students list in descending is[Student [bornYear=2018, bornMonth=null, bornDay=null], Student [bornYear=2018, bornMonth=12, bornDay=null], Student [bornYear=2018, bornMonth=12, bornDay=null], Student [bornYear=2018, bornMonth=11, bornDay=null], Student [bornYear=2017, bornMonth=9, bornDay=null], Student [bornYear=2017, bornMonth=8, bornDay=null], Student [bornYear=2017, bornMonth=6, bornDay=null], Student [bornYear=2017, bornMonth=4, bornDay=null], Student [bornYear=2017, bornMonth=2, bornDay=null], Student [bornYear=2016, bornMonth=8, bornDay=null]]

Match whitespace but not newlines

m/ /g just give space in / /, and it will work. Or use \S — it will replace all the special characters like tab, newlines, spaces, and so on.

How to enable core dump in my Linux C++ program

You can do it this way inside a program:

#include <sys/resource.h>

// core dumps may be disallowed by parent of this process; change that
struct rlimit core_limits;
core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
setrlimit(RLIMIT_CORE, &core_limits);

Change x axes scale in matplotlib

The scalar formatter supports collecting the exponents. The docs are as follows:

class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter

Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.

your technique would be:

from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3))  # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)

To get the exponent displayed in the format x10^5, instantiate the ScalarFormatter with useMathText=True.

After Image

You could also use:

xfmt.set_useOffset(10000)

To get a result like this:

enter image description here

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

How can I set the max-width of a table cell using percentages?

the percent should be relative to an absolute size, try this :

_x000D_
_x000D_
table {
  width:200px;
}

td {
  width:65%;
  border:1px solid black;
}
_x000D_
<table>
  <tr>
    <td>Testasdas 3123 1 dasd as da</td>
    <td>A long string blah blah blah</td>
  </tr>
</table>
    
_x000D_
_x000D_
_x000D_

Error Message: Type or namespace definition, or end-of-file expected

  1. Make sure you have System.Web referenced
  2. Get rid of the two } at the end.

C programming: Dereferencing pointer to incomplete type error

How did you actually define the structure? If

struct {
  char name[32];
  int  size;
  int  start;
  int  popularity;
} stasher_file;

is to be taken as type definition, it's missing a typedef. When written as above, you actually define a variable called stasher_file, whose type is some anonymous struct type.

Try

typedef struct { ... } stasher_file;

(or, as already mentioned by others):

struct stasher_file { ... };

The latter actually matches your use of the type. The first form would require that you remove the struct before variable declarations.

How to get a List<string> collection of values from app.config in WPF?

Thank for the question. But I have found my own solution to this problem. At first, I created a method

    public T GetSettingsWithDictionary<T>() where T:new()
    {
        IConfigurationRoot _configurationRoot = new ConfigurationBuilder()
        .AddXmlFile($"{Assembly.GetExecutingAssembly().Location}.config", false, true).Build();

        var instance = new T();
        foreach (var property in typeof(T).GetProperties())
        {
            if (property.PropertyType == typeof(Dictionary<string, string>))
            {
                property.SetValue(instance, _configurationRoot.GetSection(typeof(T).Name).Get<Dictionary<string, string>>());
                break;
            }

        }
        return instance;
    }

Then I used this method to produce an instance of a class

var connStrs = GetSettingsWithDictionary<AuthMongoConnectionStrings>();

I have the next declaration of class

public class AuthMongoConnectionStrings
{
    public Dictionary<string, string> ConnectionStrings { get; set; }
}

and I store my setting in App.config

<configuration>    
  <AuthMongoConnectionStrings
  First="first"
  Second="second"
  Third="33" />
</configuration> 

How can I convert a DOM element to a jQuery element?

So far best solution that I've made:

function convertHtmlToJQueryObject(html){
    var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
    return $(htmlDOMObject.documentElement);
}

Font is not available to the JVM with Jasper Reports

Try adding the line

net.sf.jasperreports.awt.ignore.missing.font=true

to your jasperreports.properties file.

Jasper stops finding one font

Oracle PL Sql Developer cannot find my tnsnames.ora file

I had the same problema, but as described in the manual.pdf, you have to:

You are using an Oracle Instant Client but have not set all required environment variables:

  • PATH: Needs to include the Instant Client directory where oci.dll is located
  • TNS_ADMIN: Needs to point to the directory where tnsnames.ora is located.
  • NLS_LANG: Defines the language, territory, and character set for the client.

Regards

How do the post increment (i++) and pre increment (++i) operators work in Java?

Presuming that you meant

int a=5; int i;

i=++a + ++a + a++;

System.out.println(i);

a=5;

i=a++ + ++a + ++a;

System.out.println(i);

a=5;

a=++a + ++a + a++;

System.out.println(a);

This evaluates to:

i = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)

so i is 6 + 7 + 7 = 20 and so 20 is printed.

i = (5, a is now 6) + (7, a is now 7) + (8, a is now 8)

so i is 5 + 7 + 8 = 20 and so 20 is printed again.

a = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)

and after all of the right hand side is evaluated (including setting a to 8) THEN a is set to 6 + 7 + 7 = 20 and so 20 is printed a final time.

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

I increase max memory to start node-chrome with -Xmx3g, and it's work for me

Functions are not valid as a React child. This may happen if you return a Component instead of from render

Adding to sagiv's answer, we should create the parent component in such a way that it can consist all children components rather than returning the child components in the way you were trying to return.

Try to intentiate the parent component and pass the props inside it so that all children can use it like below

const NewComponent = NewHOC(Movie);

Here NewHOC is the parent component and all its child are going to use movie as props.

But any way, you guyd6 have solved a problem for new react developers as this might be a problem that can come too and here is where they can find the solution for that.

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

Detect merged cells in VBA Excel with MergeArea

While working with selected cells as shown by @tbur can be useful, it's also not the only option available.

You can use Range() like so:

If Worksheets("Sheet1").Range("A1").MergeCells Then
  Do something
Else
  Do something else
End If

Or:

If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
  Do something
Else
  Do something else
End If

Alternately, you can use Cells():

If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
  Do something
Else
  Do something else
End If

When should you use constexpr capability in C++11?

All of the other answers are great, I just want to give a cool example of one thing you can do with constexpr that is amazing. See-Phit (https://github.com/rep-movsd/see-phit/blob/master/seephit.h) is a compile time HTML parser and template engine. This means you can put HTML in and get out a tree that is able to be manipulated. Having the parsing done at compile time can give you a bit of extra performance.

From the github page example:

#include <iostream>
#include "seephit.h"
using namespace std;



int main()
{
  constexpr auto parser =
    R"*(
    <span >
    <p  color="red" height='10' >{{name}} is a {{profession}} in {{city}}</p  >
    </span>
    )*"_html;

  spt::tree spt_tree(parser);

  spt::template_dict dct;
  dct["name"] = "Mary";
  dct["profession"] = "doctor";
  dct["city"] = "London";

  spt_tree.root.render(cerr, dct);
  cerr << endl;

  dct["city"] = "New York";
  dct["name"] = "John";
  dct["profession"] = "janitor";

  spt_tree.root.render(cerr, dct);
  cerr << endl;
}

Declare global variables in Visual Studio 2010 and VB.NET

small remark: I am using modules in webbased application (asp.net). I need to remember that everything I store in the variables on the module are seen by everyone in the application, read website. Not only in my session. If i try to add up a calculation in my session I need to make an array to filter the numbers for my session and for others. Modules is a great way to work but need concentration on how to use it.

To help against mistakes: classes are send to the

CarbageCollector

when the page is finished. My modules stay alive (as long as the application is not ended or restarted) and I can reuse the data in it. I use this to save data that sometimes is lost because of the sessionhandling by IIS.

IIS Form auth

and

IIS_session

are not in sync, and with my module I pull back data that went over de cliff.

Temporary tables in stored procedures

Maybe.

Temporary tables prefixed with one # (#example) are kept on a per session basis. So if your code calls the stored procedure again while another call is running (for example background threads) then the create call will fail because it's already there.

If you're really worried use a table variable instead

DECLARE @MyTempTable TABLE 
(
   someField int,
   someFieldMore nvarchar(50)
)

This will be specific to the "instance" of that stored procedure call.

Python regular expressions return true/false

One way to do this is just to test against the return value. Because you're getting <_sre.SRE_Match object at ...> it means that this will evaluate to true. When the regular expression isn't matched you'll the return value None, which evaluates to false.

import re

if re.search("c", "abcdef"):
    print "hi"

Produces hi as output.

C# int to enum conversion

You don't need the inheritance. You can do:

(Foo)1 

it will work ;)

jquery animate background position

I guess it might be because it is expecting a single value?

taken from the animate page on jQuery:

Animation Properties and Values

All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

Removing numbers from string

Would this work for your situation?

>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'

This makes use of a list comprehension, and what is happening here is similar to this structure:

no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
    if not i.isdigit():
        no_digits.append(i)

# Now join all elements of the list with '', 
# which puts all of the characters together.
result = ''.join(no_digits)

As @AshwiniChaudhary and @KirkStrauser point out, you actually do not need to use the brackets in the one-liner, making the piece inside the parentheses a generator expression (more efficient than a list comprehension). Even if this doesn't fit the requirements for your assignment, it is something you should read about eventually :) :

>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'

How can I iterate JSONObject to get individual items

You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
    Iterator<String> keys = json.keys();
    while(keys.hasNext()){
        String key = keys.next();
        String val = null;
        try{
             JSONObject value = json.getJSONObject(key);
             parse(value,out);
        }catch(Exception e){
            val = json.getString(key);
        }

        if(val != null){
            out.put(key,val);
        }
    }
    return out;
}

 public static void main(String[] args) throws JSONException {

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";

    JSONObject object = new JSONObject(json);

    JSONObject info = object.getJSONObject("ipinfo");

    Map<String,String> out = new HashMap<String, String>();

    parse(info,out);

    String latitude = out.get("latitude");
    String longitude = out.get("longitude");
    String city = out.get("city");
    String state = out.get("state");
    String country = out.get("country");
    String postal = out.get("postal_code");

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);

    System.out.println("ALL VALUE " + out);

}

Output:

    Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}

WebDriver: check if an element exists?

You could alternatively do:

driver.findElements( By.id("...") ).size() != 0

Which saves the nasty try/catch

p.s.

Or more precisely by @JanHrcek here

!driver.findElements(By.id("...")).isEmpty()

When should one use a spinlock instead of mutex?

Please also note that on certain environments and conditions (such as running on windows on dispatch level >= DISPATCH LEVEL), you cannot use mutex but rather spinlock. On unix - same thing.

Here is equivalent question on competitor stackexchange unix site: https://unix.stackexchange.com/questions/5107/why-are-spin-locks-good-choices-in-linux-kernel-design-instead-of-something-more

Info on dispatching on windows systems: http://download.microsoft.com/download/e/b/a/eba1050f-a31d-436b-9281-92cdfeae4b45/IRQL_thread.doc

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

Short description of the scoping rules?

The scoping rules for Python 2.x have been outlined already in other answers. The only thing I would add is that in Python 3.0, there is also the concept of a non-local scope (indicated by the 'nonlocal' keyword). This allows you to access outer scopes directly, and opens up the ability to do some neat tricks, including lexical closures (without ugly hacks involving mutable objects).

EDIT: Here's the PEP with more information on this.

Running EXE with parameters

To start the process with parameters, you can use following code:

string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);

To kill/exit the program again, you can use following code:

proc.CloseMainWindow(); 
proc.Close();

How to reverse a singly linked list using only two pointers?

I don't understand why there is need to return head as we are passing it as argument. We are passing head of the link list then we can update also. Below is simple solution.

#include<stdio.h>
#include<conio.h>

struct NODE
{
    struct NODE *next;
    int value;
};

typedef struct NODE node;

void reverse(node **head);
void add_end(node **head,int val);
void alloc(node **p);
void print_all(node *head);

void main()
{
    node *head;
    clrscr();
    head = NULL;
    add_end( &head, 1 );
    add_end( &head, 2 );
    add_end( &head, 3 );
    print_all( head );
    reverse( &head );
    print_all( head );
    getch();
}
void alloc(node **p)
{
    node *temp;
    temp = (node *) malloc( sizeof(node *) );
    temp->next = NULL;
    *p = temp;
}
void add_end(node **head,int val)
{
    node *temp,*new_node;
    alloc(&new_node);
    new_node->value = val;
    if( *head == NULL )
    {
        *head = new_node;
        return;
    }
    for(temp = *head;temp->next!=NULL;temp=temp->next);
    temp->next = new_node;
}
void print_all(node *head)
{
    node *temp;
    int index=0;
    printf ("\n\n");
    if (head == NULL)
    {
        printf (" List is Empty \n");
        return;
    }
    for (temp=head; temp != NULL; temp=temp->next,index++)
        printf (" %d ==> %d \n",index,temp->value);
}
void reverse(node **head)
{
    node *next,*new_head;
    new_head=NULL;
    while(*head != NULL)
    {
        next = (*head)->next;
        (*head)->next = new_head;
        new_head = (*head);
        (*head) = next;
    }
    (*head)=new_head;
}

What does href expression <a href="javascript:;"></a> do?

    1. Use that java script to Clear an HTML row Or Delete a row using the id set to a span and use JQuery to set a function to that span's click event.
    2. Dynamically set the div html to a string variable and replace {id} with a 1 or 2 etc. cell of a larger div table and rows

<div class="table-cell">
    <span id="clearRow{id}">
        <a href="javascript:" style-"color:#c32029; align:right; font-size:8pt;">Clear</a>
    </span>
</div>

<div class="table-cell">
   <span id="deleteRow{id}">
       <a href="javascript:" style-"color:#c32029; align:right; font-size:8pt;">Delete</a>
   </span>
</div>

//JQuery - Clear row
$("#clearRow" + idNum).click(function(){
    $("someIDOrWildcardSelector" + idNum).val("");
    $("someIDOrWildcardSelector" + idNum).val("");
    $("someIDOrWildcardSelector" + idNum).val("");
});

//JQuery to remove / delete an html row
$("#deleteRow" + idNum).click(function(){
    //depending upon levels of parent / child use 1 to many .parent().parent().parent()
    $(this).parent().remove();
});

How can I render a list select box (dropdown) with bootstrap?

Ben's code requires the parent div to have the form-group class (I was using btn-group), this is a slightly different version which just searches for the closest div and may even be a bit faster.

$(".dropdown-menu li a").click(function(){
    var selText = $(this).text();
    $(this).closest('div').find('button[data-toggle="dropdown"]').html(selText + ' <span class="caret"></span>');
});

Convert string to int array using LINQ

Actually correct one to one implementation is:

int n;
int[] ia = s1.Split(';').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();

How to check "hasRole" in Java Code with Spring Security?

You can implement a hasRole() method as below - (This is tested on spring security 3.0.x not sure about other versions.)

  protected final boolean hasRole(String role) {
    boolean hasRole = false;
    UserDetails userDetails = getUserDetails();
    if (userDetails != null) {
      Collection<GrantedAuthority> authorities = userDetails.getAuthorities();
      if (isRolePresent(authorities, role)) {
        hasRole = true;
      }
    } 
    return hasRole;
  }
  /**
   * Get info about currently logged in user
   * @return UserDetails if found in the context, null otherwise
   */
  protected UserDetails getUserDetails() {
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserDetails userDetails = null;
    if (principal instanceof UserDetails) {
      userDetails = (UserDetails) principal;
    }
    return userDetails;
  }
  /**
   * Check if a role is present in the authorities of current user
   * @param authorities all authorities assigned to current user
   * @param role required authority
   * @return true if role is present in list of authorities assigned to current user, false otherwise
   */
  private boolean isRolePresent(Collection<GrantedAuthority> authorities, String role) {
    boolean isRolePresent = false;
    for (GrantedAuthority grantedAuthority : authorities) {
      isRolePresent = grantedAuthority.getAuthority().equals(role);
      if (isRolePresent) break;
    }
    return isRolePresent;
  }

How do I make an HTML button not reload the page

You could add a click handler on the button with jQuery and do return false.

$("input[type='submit']").click(function() { return false; });

or

$("form").submit(function() { return false; });

TimePicker Dialog from clicking EditText

public void onClick1(View v) {
  DatePickerDialog dialog = new DatePickerDialog(this, this, 2013, 2, 18);
  dialog.show();
}

public void onDateSet1(DatePicker view, int year1, int month1, int day1) {
  e1.setText(day1 + "/" + (month1+1) + "/" + year1);
}

Tomcat is not running even though JAVA_HOME path is correct

To run Tomcat8 you need to have JRE_HOME defined in Env Variable.

JAVA_HOME alone will not do even if correctly set.

JRE_HOME = C:\Program Files\Java\jdk1.8.0_77\jre

You should select the JRE that is inside SDK, i.e. one with your JDK(SDK) installation. In other words your JAVA_HOME + \jre

When compiling JDK is needed to support JSP, to compile Servlets which are generated from *.jsp files. Otherwise to run JRE is needed. So when you develop you need JAVA_HOME and when you deploy you need JRE_HOME.

Read and write a text file in typescript

believe there should be a way in accessing file system.

Include node.d.ts using npm i @types/node. And then create a new tsconfig.json file (npx tsc --init) and create a .ts file as followed:

import fs from 'fs';
fs.readFileSync('foo.txt','utf8');

You can use other functions in fs as well : https://nodejs.org/api/fs.html

More

Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html

MySQL Trigger after update only if row has changed

Use the following query to see which rows have changes:

(select * from inserted) except (select * from deleted)

The results of this query should consist of all the new records that are different from the old ones.

Compare string with all values in list

for word in d:
    if d in paid[j]:
         do_something()

will try all the words in the list d and check if they can be found in the string paid[j].

This is not very efficient since paid[j] has to be scanned again for each word in d. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.

sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]

s1 = set(sentence.split())
s2 = set(d)

print (s1.intersection(s2))

Output:

{'come', 'easy'}

Create a hidden field in JavaScript

I've found this to work:

var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);

How to use EditText onTextChanged event when I press the number?

put the logic in

afterTextChanged(Editable s) {
    string str = s.toString()
    // use the string str
}

documentation on TextWatcher

Spring - @Transactional - What happens in background?

All existing answers are correct, but I feel cannot give just this complex topic.

For a comprehensive, practical explanation you might want to have a look at this Spring @Transactional In-Depth guide, which tries its best to cover transaction management in ~4000 simple words, with a lot of code examples.

rejected master -> master (non-fast-forward)

I had this problem on a development machine. The dev branch was pushing fine but the the master branch gave me (while git pushing when being on the dev branch):

! [rejected]        master -> master (non-fast-forward)

So I tried:

git checkout master
git pull

Which gave me:

You asked me to pull without telling me which branch you
want to merge with, and 'branch.master.merge' in
your configuration file does not tell me, either.

I found out the master branch was missing from .git/config and added:

[branch "master"]
    remote = origin
    merge = refs/heads/master

Afterwards git push also worked fine on the dev branch.

Docker compose port mapping

It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container.

https://unix.stackexchange.com/a/101906/38639 helped me get to the right answer.

First, you'll need to install the nc command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.

Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.

# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY cmd.sh /usr/local/bin/cmd.sh
RUN chmod +x /usr/local/bin/cmd.sh
CMD ["/usr/local/bin/cmd.sh"]

Finally, we'll need to set up port-forwarding in cmd.sh. I found that nc, even with the -l and -k options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.

# cmd.sh
#! /usr/bin/env bash

while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &

tail -f /dev/null # Or any other command that never exits

How to call a parent method from child class in javascript?

Here's a nice way for child objects to have access to parent properties and methods using JavaScript's prototype chain, and it's compatible with Internet Explorer. JavaScript searches the prototype chain for methods and we want the child’s prototype chain to looks like this:

Child instance -> Child’s prototype (with Child methods) -> Parent’s prototype (with Parent methods) -> Object prototype -> null

The child methods can also call shadowed parent methods, as shown at the three asterisks *** below.

Here’s how:

_x000D_
_x000D_
//Parent constructor_x000D_
function ParentConstructor(firstName){_x000D_
    //add parent properties:_x000D_
    this.parentProperty = firstName;_x000D_
}_x000D_
_x000D_
//add 2 Parent methods:_x000D_
ParentConstructor.prototype.parentMethod = function(argument){_x000D_
    console.log(_x000D_
            "Parent says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ParentConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Parent! argument=" + argument);_x000D_
};_x000D_
_x000D_
//Child constructor    _x000D_
function ChildConstructor(firstName, lastName){_x000D_
    //first add parent's properties_x000D_
    ParentConstructor.call(this, firstName);_x000D_
_x000D_
    //now add child's properties:_x000D_
    this.childProperty = lastName;_x000D_
}_x000D_
_x000D_
//insert Parent's methods into Child's prototype chain_x000D_
var rCopyParentProto = Object.create(ParentConstructor.prototype);_x000D_
rCopyParentProto.constructor = ChildConstructor;_x000D_
ChildConstructor.prototype = rCopyParentProto;_x000D_
_x000D_
//add 2 Child methods:_x000D_
ChildConstructor.prototype.childMethod = function(argument){_x000D_
    console.log(_x000D_
            "Child says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ChildConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Child! argument=" + argument);_x000D_
_x000D_
    // *** call Parent's version of common method_x000D_
    ParentConstructor.prototype.commonMethod(argument);_x000D_
};_x000D_
_x000D_
//create an instance of Child_x000D_
var child_1 = new ChildConstructor('Albert', 'Einstein');_x000D_
_x000D_
//call Child method_x000D_
child_1.childMethod('do child method');_x000D_
_x000D_
//call Parent method_x000D_
child_1.parentMethod('do parent method');_x000D_
_x000D_
//call common method_x000D_
child_1.commonMethod('do common method');
_x000D_
_x000D_
_x000D_

PHP page redirect

header( "Location: http://www.domain.com/user.php" );

But you can't first do an echo, and then redirect.

How to create a private class method?

ExiRe wrote:

Such behavior of ruby is really frustrating. I mean if you move to private section self.method then it is NOT private. But if you move it to class << self then it suddenly works. It is just disgusting.

Confusing it probably is, frustrating it may well be, but disgusting it is definitely not.

It makes perfect sense once you understand Ruby's object model and the corresponding method lookup flow, especially when taking into consideration that private is NOT an access/visibility modifier, but actually a method call (with the class as its recipient) as discussed here... there's no such thing as "a private section" in Ruby.

To define private instance methods, you call private on the instance's class to set the default visibility for subsequently defined methods to private... and hence it makes perfect sense to define private class methods by calling private on the class's class, ie. its metaclass.

Other mainstream, self-proclaimed OO languages may give you a less confusing syntax, but you definitely trade that off against a confusing and less consistent (inconsistent?) object model without the power of Ruby's metaprogramming facilities.

Deserialize JSON string to c# object

solution :

 public Response Get(string jsonData) {
     var json = JsonConvert.DeserializeObject<modelname>(jsonData);
     var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
     return data;
 }

model:

 public class modelname {
     public long parameter{ get; set; }
     public int parameter{ get; set; }
     public int parameter{ get; set; }
     public string parameter{ get; set; }
 }

How to check list A contains any value from list B?

I use this to count:

int cnt = 0;

foreach (var lA in listA)
{
    if (listB.Contains(lA))
    {
        cnt++;
    }
}

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

For those coming here to debug this error in Chrome 73, one possibility is because Chrome 73 onwards disallows cross-origin requests in content scripts.

More reading:

  1. https://www.chromestatus.com/feature/5629709824032768
  2. https://www.chromium.org/Home/chromium-security/extension-content-script-fetches

This affects many Chrome extension authors, who now need to scramble to fix the extensions because Chrome thinks "Our data shows that most extensions will not be affected by this change."

(it has nothing to do with your app code)

UPDATE: I fixed the CORs issue but I still see this error. I suspect it is Chrome's fault here.

What does the "map" method do in Ruby?

#each

#each runs a function for each element in an array. The following two code excerpts are equivalent:

x = 10
["zero", "one", "two"].each{|element|
    x++
    puts element
}
x = 10
array = ["zero", "one", "two"]

for i in 0..2
    x++
    puts array[i]
end

#map

#map applies a function to each element of an array, returning the resulting array. The following are equivalent:

array = ["zero", "one", "two"]
newArray = array.map{|element| element.capitalize()}
array = ["zero", "one", "two"]

newArray = []
array.each{|element|
    newArray << element.capitalize()
}

#map!

#map! is like #map, but modifies the array in place. The following are equivalent:

array = ["zero", "one", "two"]
array.map!{|element| element.capitalize()}
array = ["zero", "one", "two"]
array = array.map{|element| element.capitalize()}

JPA getSingleResult() or null

Spring has a utility method for this:

TypedQuery<Profile> query = em.createNamedQuery(namedQuery, Profile.class);
...
return org.springframework.dao.support.DataAccessUtils.singleResult(query.getResultList());

Undefined behavior and sequence points

I am guessing there is a fundamental reason for the change, it isn't merely cosmetic to make the old interpretation clearer: that reason is concurrency. Unspecified order of elaboration is merely selection of one of several possible serial orderings, this is quite different to before and after orderings, because if there is no specified ordering, concurrent evaluation is possible: not so with the old rules. For example in:

f (a,b)

previously either a then b, or, b then a. Now, a and b can be evaluated with instructions interleaved or even on different cores.

Matplotlib different size subplots

I used pyplot's axes object to manually adjust the sizes without using GridSpec:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02

rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]

fig = plt.figure()

cones = plt.axes(rect_cones)
box = plt.axes(rect_box)

cones.plot(x, y)

box.plot(y, x)

plt.show()

Confirmation before closing of tab/browser

If you want to ask based on condition:

var ask = true
window.onbeforeunload = function (e) {
    if(!ask) return null
    e = e || window.event;
    //old browsers
    if (e) {e.returnValue = 'Sure?';}
    //safari, chrome(chrome ignores text)
    return 'Sure?';
};

What is causing "Unable to allocate memory for pool" in PHP?

Monitor your Cached Files Size (you can use apc.php from apc pecl package) and increase apc.shm_size according to your needs.

This solves the problem.

CSS Float: Floating an image to the left of the text

Solution using display: flex (with responsive behavior): http://jsfiddle.net/dkulahin/w3472kct

HTML:

<div class="content">
    <img src="myimage.jpg" alt="" />
    <div class="details">
        <p>Lorem ipsum dolor sit amet...</p>
    </div>
</div>

CSS:

.content{
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
}
.content img {
    width: 150px;
}
.details {
    width: calc(100% - 150px);
}
@media only screen and (max-width: 480px) {
    .content {
        flex-direction: column;
    }
    .details {
        width: 100%;
    }
}

How can I get LINQ to return the object which has the max value for a given property?

You could use a captured variable.

Item result = items.FirstOrDefault();
items.ForEach(x =>
{
  if(result.ID < x.ID)
    result = x;
});

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

how to create a login page when username and password is equal in html

Doing password checks on client side is unsafe especially when the password is hard coded.

The safest way is password checking on server side, but even then the password should not be transmitted plain text.

Checking the password client side is possible in a "secure way":

  • The password needs to be hashed
  • The hashed password is used as part of a new url

Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).

Why do we use web.xml?

Generally speaking, this is the configuration file of web applications in java. It instructs the servlet container (tomcat for ex.) which classes to load, what parameters to set in the context, and how to intercept requests coming from browsers.

There you specify:

  • what servlets (and filters) you want to use and what URLs you want to map them to
  • listeners - classes that are notified when some events happen (context starts, session created, etc)
  • configuration parameters (context-params)
  • error pages, welcome files
  • security constraints

In servlet 3.0 many of the web.xml parts are optional. These configurations can be done via annotations (@WebServlet, @WebListener)

Numpy first occurrence of value greater than existing value

In [34]: a=np.arange(-10,10)

In [35]: a
Out[35]:
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])

In [36]: np.where(a>5)
Out[36]: (array([16, 17, 18, 19]),)

In [37]: np.where(a>5)[0][0]
Out[37]: 16

Writelines writes lines without newline, Just fills the file

The documentation for writelines() states:

writelines() does not add line separators

So you'll need to add them yourself. For example:

    line_list.append(new_line + "\n")

whenever you append a new item to line_list.

How to overcome the CORS issue in ReactJS

You can set up a express proxy server using http-proxy-middleware to bypass CORS:

const express = require('express');
const proxy = require('http-proxy-middleware');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();

app.use(express.static(__dirname));
app.use('/proxy', proxy({
    pathRewrite: {
       '^/proxy/': '/'
    },
    target: 'https://server.com',
    secure: false
}));

app.get('*', (req, res) => {
   res.sendFile(path.resolve(__dirname, 'index.html'));
});

app.listen(port);
console.log('Server started');

From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.

const URL = `/proxy/${PATH}`;
return axios.get(URL);

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

How to pass form input value to php function

You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>

This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc

validate natural input number with ngpattern

The problem is that your REGX pattern will only match the input "0-9".

To meet your requirement (0-9999999), you should rewrite your regx pattern:

ng-pattern="/^[0-9]{1,7}$/"

My example:

HTML:

<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="price" name="price_field" 
           ng-pattern="/^[0-9]{1,7}$/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <span ng-show="myForm.price_field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>
  </form>
</div>

JS:

function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");
  }
}

Here is a jsFiddle demo.

Pandas split DataFrame by column value

Using "groupby" and list comprehension:

Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.

DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]

accessing the separated DF like this:

ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:

ansI_chr=ans[i].chr 

Php - testing if a radio button is selected and get the value

Just simply use isset($_POST['radio']) so that whenever i click any of the radio button, the one that is clicked is set to the post.

 <form method="post" action="sample.php">
 select sex: 
 <input type="radio" name="radio" value="male">
 <input type="radio" name="radio" value="female">

 <input type="submit" value="submit">
 </form>

<?php

if (isset($_POST['radio'])){

    $Sex = $_POST['radio'];
 }
  ?>

set option "selected" attribute from dynamic created option

// Get <select> object
var sel = $('country');

// Loop through and look for value match, then break
for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }

// Select index 
sel.options.selectedIndex = i;

Begitu loh.

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

The syntax is:

=GOOGLEFINANCE(ticker, [attribute], [start_date], [num_days|end_date], [interval])

Sample usage:

=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
=GOOGLEFINANCE("GOOG","price",TODAY()-30,TODAY())
=GOOGLEFINANCE(A2,A3)
=117.80*Index(GOOGLEFINANCE("CURRENCY:EURGBP", "close", DATE(2014,1,1)), 2, 2)

For instance if you'd like to convert the rate on specific date, here is some more advanced example:

=IF($C2 = "GBP", "", Index(GoogleFinance(CONCATENATE("CURRENCY:", C2, "GBP"), "close", DATE(year($A2), month($A2), day($A2)), DATE(year($A2), month($A2), day($A2)+1), "DAILY"), 2))

where $A2 is your date (e.g. 01/01/2015) and C2 is your currency (e.g. EUR).

See more samples at Docs editors Help at Google.

How to sort pandas data frame using values from several columns?

Use of sort can result in warning message. See github discussion. So you might wanna use sort_values, docs here

Then your code can look like this:

df = df.sort_values(by=['c1','c2'], ascending=[False,True])

What is the best way to modify a list in a 'foreach' loop?

The collection used in foreach is immutable. This is very much by design.

As it says on MSDN:

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

The post in the link provided by Poko indicates that this is allowed in the new concurrent collections.

Any way to clear python's IDLE window?

>>> import os

>>>def cls():
...    os.system("clear")
...
>>>cls()

That does is perfectly. No '0' printed either.

Call a function from another file?

Rename the module to something other than 'file'.

Then also be sure when you are calling the function that:

1)if you are importing the entire module, you reiterate the module name when calling it:

import module
module.function_name()

or

import pizza
pizza.pizza_function()

2)or if you are importing specific functions, functions with an alias, or all functions using *, you don't reiterate the module name:

from pizza import pizza_function
pizza_function()

or

from pizza import pizza_function as pf
pf()

or

from pizza import *
pizza_function()

What is the difference between Forking and Cloning on GitHub?

In a nutshell, "fork" creates a copy of the project hosted on your own GitHub account.

"Clone" uses git software on your computer to download the source code and it's entire version history unto that computer

How to show/hide JPanels in a JFrame?

If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.

jpanel1.setVisible(false);

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html() 
// or
$('#telefon').text()

or

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

Handling optional parameters in javascript

Are you saying you can have calls like these: getData(id, parameters); getData(id, callback)?

In this case you can't obviously rely on position and you have to rely on analysing the type: getType() and then if necessary getTypeName()

Check if the parameter in question is an array or a function.

How to check if div element is empty

Using plain javascript

 var isEmpty = document.getElementById('cartContent').innerHTML === "";

And if you are using jquery it can be done like

 var isEmpty = $("#cartContent").html() === "";

ERROR in ./node_modules/css-loader?

try using

npm rebuild node-sass

Global variables in c#.net

You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.

Get Absolute URL from Relative path (refactored method)

This works fine too:

HttpContext.Current.Server.MapPath(relativePath)

Where relative path is something like "~/foo/file.jpg"

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

How to filter by string in JSONPath?

Drop the quotes:

List<Object> bugs = JsonPath.read(githubIssues, "$..labels[?(@.name==bug)]");

See also this Json Path Example page

Inserting values into tables Oracle SQL

You can insert into a table from a SELECT.

INSERT INTO
  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
  001,
  'John Doe',
  '1 River Walk, Green Street',
  (SELECT id FROM state WHERE name = 'New York'),
  (SELECT id FROM positions WHERE name = 'Sales Executive'),
  (SELECT id FROM manager WHERE name = 'Barry Green')
FROM
  dual

Or, similarly...

INSERT INTO
  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
  001,
  'John Doe',
  '1 River Walk, Green Street',
  state.id,
  positions.id,
  manager.id
FROM
  state
CROSS JOIN
  positions
CROSS JOIN
  manager
WHERE
      state.name     = 'New York'
  AND positions.name = 'Sales Executive'
  AND manager.name   = 'Barry Green'

Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.

Creating a UICollectionView programmatically

Header file:--

@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    UICollectionView *_collectionView;
}

Implementation File:--

- (void)viewDidLoad
{
     [super viewDidLoad];
     self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

     UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    _collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    [_collectionView setDataSource:self];
    [_collectionView setDelegate:self];

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    [_collectionView setBackgroundColor:[UIColor redColor]];

    [self.view addSubview:_collectionView];


    // Do any additional setup after loading the view, typically from a nib.
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 15;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor greenColor];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(50, 50);
}

Output---

enter image description here

Why docker container exits immediately

Why docker container exits immediately?

If you want to force the image to hang around (in order to debug something or examine state of the file system) you can override the entry point to change it to a shell:

docker run -it --entrypoint=/bin/bash myimagename

How to get span tag inside a div in jQuery and assign a text?

Try this

$("#message span").text("hello world!");

function Errormessage(txt) {
    var elem = $("#message");
    elem.fadeIn("slow");
    // find the span inside the div and assign a text
    elem.children("span").text("your text");

    elem.children("a.close-notify").click(function() {
        elem.fadeOut("slow");
    });
}

Accurate way to measure execution times of php scripts

Create file loadtime.php

<?php
class loadTime{
    private $time_start     =   0;
    private $time_end       =   0;
    private $time           =   0;
    public function __construct(){
        $this->time_start= microtime(true);
    }
    public function __destruct(){
        $this->time_end = microtime(true);
        $this->time = $this->time_end - $this->time_start;
        echo "Loaded in $this->time seconds\n";
    }
}

Than in the beggining of your script, after <?php write include 'loadtime.php'; $loadtime=new loadTime();

When page is loaded at the end there will be written "Loaded in x seconds"

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Another option is to update the Microsoft.AspnNet.Mvc NuGet package. Be careful, because NuGet update does not update the Web.Config. You should update all previous version numbers to updated number. For example if you update from asp.net MVC 4.0.0.0 to 5.0.0.0, then this should be replaced in the Web.Config:

    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

 <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

<pages
    validateRequest="false"
    pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
  <controls>
    <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
  </controls>
</pages>

How to output a comma delimited list in jinja python template?

you could also use the builtin "join" filter (http://jinja.pocoo.org/docs/templates/#join like this:

{{ users|join(', ') }}

"Fatal error: Cannot redeclare <function>"

I had strange behavor when my *.php.bak (which automaticly was created by notepad) was included in compilation. After I removed all *.php.bak from folder this error was gone. Maybe this will be helpful for someone.

How to get an Array with jQuery, multiple <input> with the same name

Firstly, you shouldn't have multiple elements with the same ID on a page - ID should be unique.

You could just remove the id attribute and and replace it with:

<input type='text' name='task'>

and to get an array of the values of task do

var taskArray = new Array();
$("input[name=task]").each(function() {
   taskArray.push($(this).val());
});

Making custom right-click context menus for my web-app

Simple One

  1. show context menu when right click anywhere in document
  2. avoid context menu hide when click inside context menu
  3. close context menu when press left mouse button

Note: dont use display:none instead use opacity to hide and show

_x000D_
_x000D_
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {      
            e.preventDefault();  
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';        
             menu.style.opacity = 1;
        });
       
  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
_x000D_
.context_menu{

width:70px;
background:lightgrey;
padding:5px;
 opacity :0;
}
.context_menu div{
margin:5px;
background:grey;

}
.context_menu div:hover{
margin:5px;
background:red;
   cursor:pointer;

}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
</div>
_x000D_
_x000D_
_x000D_

extra css

_x000D_
_x000D_
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {      
            e.preventDefault();  
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';        
             menu.style.opacity = 1;
        });
       
  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
_x000D_
.context_menu{

width:120px;
background:white;
border:1px solid lightgrey;

 opacity :0;
}
.context_menu div{
padding:5px;
padding-left:15px;
margin:5px 2px;
border-bottom:1px solid lightgrey;
}
.context_menu div:last-child {
border:none;
}
.context_menu div:hover{

background:lightgrey;
   cursor:pointer;

}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
<div>menu 3</div>
<div>menu 4</div>
</div>
_x000D_
_x000D_
_x000D_

How to read until end of file (EOF) using BufferedReader in Java?

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.

Is there a way of setting culture for a whole application? All current threads and new threads?

Here is the solution for c# MVC:

  1. First : Create a custom attribute and override method like this:

    public class CultureAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Retreive culture from GET
            string currentCulture = filterContext.HttpContext.Request.QueryString["culture"];
    
            // Also, you can retreive culture from Cookie like this :
            //string currentCulture = filterContext.HttpContext.Request.Cookies["cookie"].Value;
    
            // Set culture
            Thread.CurrentThread.CurrentCulture = new CultureInfo(currentCulture);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(currentCulture);
        }
    }
    
  2. Second : In App_Start, find FilterConfig.cs, add this attribute. (this works for WHOLE application)

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            // Add custom attribute here
            filters.Add(new CultureAttribute());
        }
    }    
    

That's it !

If you want to define culture for each controller/action in stead of whole application, you can use this attribute like this:

[Culture]
public class StudentsController : Controller
{
}

Or:

[Culture]
public ActionResult Index()
{
    return View();
}

Print execution time of a shell command

Don't forget that there is a difference between bash's builtin time (which should be called by default when you do time command) and /usr/bin/time (which should require you to call it by its full path).

The builtin time always prints to stderr, but /usr/bin/time will allow you to send time's output to a specific file, so you do not interfere with the executed command's stderr stream. Also, /usr/bin/time's format is configurable on the command line or by the environment variable TIME, whereas bash's builtin time format is only configured by the TIMEFORMAT environment variable.

$ time factor 1234567889234567891 # builtin
1234567889234567891: 142662263 8653780357

real    0m3.194s
user    0m1.596s
sys 0m0.004s
$ /usr/bin/time factor 1234567889234567891
1234567889234567891: 142662263 8653780357
1.54user 0.00system 0:02.69elapsed 57%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+215minor)pagefaults 0swaps
$ /usr/bin/time -o timed factor 1234567889234567891 # log to file `timed`
1234567889234567891: 142662263 8653780357
$ cat timed
1.56user 0.02system 0:02.49elapsed 63%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+217minor)pagefaults 0swaps

Load and execute external js file in node.js with access to local variables?

Expanding on @Shripad's and @Ivan's answer, I would recommend that you use Node.js's standard module.export functionality.

In your file for constants (e.g. constants.js), you'd write constants like this:

const CONST1 = 1;
module.exports.CONST1 = CONST1;

const CONST2 = 2;
module.exports.CONST2 = CONST2;

Then in the file in which you want to use those constants, write the following code:

const {CONST1 , CONST2} = require('./constants.js');

If you've never seen the const { ... } syntax before: that's destructuring assignment.

"Cannot GET /" with Connect on Node.js

The easiest way to serve static files is to use "harp". It can be found here. You can serve up your files from the location you want via node is:

var harp = require("harp")
harp.server(projectPath [,args] [,callback])

Hope this helps.

Create an Android GPS tracking application

Basically you need following things to make location detector android app

Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.

Using all these resources, you will be able to create an flawless android location detection app.

1. Location Listening

You will first need to listen for current location of user. You can use any of below libraries to quick start.

Google Play Location Samples

This library provide last known location, location updates

Location Manager

With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.

Live Location Sharing

Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.

2. Markers Library

Google Maps Android API utility library

  • Marker clustering — handles the display of a large number of points
  • Heat maps — display a large number of points as a heat map
  • IconGenerator — display text on your Markers
  • Poly decoding and encoding — compact encoding for paths, interoperability with Maps API web services
  • Spherical geometry — for example: computeDistance, computeHeading, computeArea
  • KML — displays KML data
  • GeoJSON — displays and styles GeoJSON data

3. Polyline Libraries

DrawRouteMaps

If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.

trail-android

Simple, smooth animation for route / polylines on google maps using projections. (WIP)

Google-Directions-Android

This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.

A map demo app for quick start with maps

How to retrieve data from sqlite database in android and display it in TextView

You are using getData() method as void.

You can not return values from void.

CSS: How to position two elements on top of each other, without specifying a height?

Of course, the problem is all about getting your height back. But how can you do that if you don't know the height ahead of time? Well, if you know what aspect ratio you want to give the container (and keep it responsive), you can get your height back by adding padding to another child of the container, expressed as a percentage.

You can even add a dummy div to the container and set something like padding-top: 56.25% to give the dummy element a height that is a proportion of the container's width. This will push out the container and give it an aspect ratio, in this case 16:9 (56.25%).

Padding and margin use the percentage of the width, that's really the trick here.

Authenticate Jenkins CI for Github private repository

Perhaps GitHub's support for deploy keys is what you're looking for? To quote that page:

When should I use a deploy key?

Simple, when you have a server that needs pull access to a single private repo. This key is attached directly to the repository instead of to a personal user account.

If that's what you're already trying and it doesn't work, you might want to update your question with more details of the URLs being used, the names and location of the key files, etc.


Now for the technical part: How to use your SSH key with Jenkins?

If you have, say, a jenkins unix user, you can store your deploy key in ~/.ssh/id_rsa. When Jenkins tries to clone the repo via ssh, it will try to use that key.

In some setups, you cannot run Jenkins as an own user account, and possibly also cannot use the default ssh key location ~/.ssh/id_rsa. In such cases, you can create a key in a different location, e.g. ~/.ssh/deploy_key, and configure ssh to use that with an entry in ~/.ssh/config:

Host github-deploy-myproject
    HostName       github.com
    User           git
    IdentityFile   ~/.ssh/deploy_key
    IdentitiesOnly yes

Because all you authenticate to all Github repositories using [email protected] and you don't want the above key to be used for all your connections to Github, we created a host alias github-deploy-myproject. Your clone URL now becomes

git clone github-deploy-myproject:myuser/myproject

and that is also what you put as repository URL into Jenkins.

(Note that you must not put ssh:// in front in order for this to work.)

What does character set and collation mean exactly?

I suggest to use utf8mb4_unicode_ci, which is based on the Unicode standard for sorting and comparison, which sorts accurately in a very wide range of languages.

JavaScript equivalent of PHP's in_array()

No, it doesn't have one. For this reason most popular libraries come with one in their utility packages. Check out jQuery's inArray and Prototype's Array.indexOf for examples.

jQuery's implementation of it is as simple as you might expect:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

If you are dealing with a sane amount of array elements the above will do the trick nicely.

EDIT: Whoops. I didn't even notice you wanted to see if an array was inside another. According to the PHP documentation this is the expected behavior of PHP's in_array:

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}

if (in_array('o', $a)) {
    echo "'o' was found\n";
}

// Output:
//  'ph' was found
//  'o' was found

The code posted by Chris and Alex does not follow this behavior. Alex's is the official version of Prototype's indexOf, and Chris's is more like PHP's array_intersect. This does what you want:

function arrayCompare(a1, a2) {
    if (a1.length != a2.length) return false;
    var length = a2.length;
    for (var i = 0; i < length; i++) {
        if (a1[i] !== a2[i]) return false;
    }
    return true;
}

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(typeof haystack[i] == 'object') {
            if(arrayCompare(haystack[i], needle)) return true;
        } else {
            if(haystack[i] == needle) return true;
        }
    }
    return false;
}

And this my test of the above on it:

var a = [['p','h'],['p','r'],'o'];
if(inArray(['p','h'], a)) {
    alert('ph was found');
}
if(inArray(['f','i'], a)) {
    alert('fi was found');
}
if(inArray('o', a)) {
    alert('o was found');
}  
// Results:
//   alerts 'ph' was found
//   alerts 'o' was found

Note that I intentionally did not extend the Array prototype as it is generally a bad idea to do so.

CSS: Position text in the middle of the page

Here's a method using display:flex:

_x000D_
_x000D_
.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: flex;_x000D_
  position: fixed;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>centered text!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

View on Codepen
Check Browser Compatability

Aggregate function in SQL WHERE-Clause

You can't use an aggregate directly in a WHERE clause; that's what HAVING clauses are for.

You can use a sub-query which contains an aggregate in the WHERE clause.

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

Passing base64 encoded strings in URL

@joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.

$str = 'Some String';

$encoded = urlencode( base64_encode( $str ) );
$decoded = base64_decode( urldecode( $encoded ) );

What are some good Python ORM solutions?

I usually use SQLAlchemy. It's pretty powerful and is probably the most mature python ORM.

If you're planning on using CherryPy, you might also look into dejavu as it's by Robert Brewer (the guy that is the current CherryPy project leader). I personally haven't used it, but I do know some people that love it.

SQLObject is a little bit easier to use ORM than SQLAlchemy, but it's not quite as powerful.

Personally, I wouldn't use the Django ORM unless I was planning on writing the entire project in Django, but that's just me.

How to get first object out from List<Object> using Linq

You can do

Component depCountry = lstComp
                       .Select(x => x.ComponentValue("Dep"))
                       .FirstOrDefault();

Alternatively if you are wanting this for the entire dictionary of values, you can even tie it back to the key

var newDictionary = dic.Select(x => new 
            {
               Key = x.Key,
               Value = x.Value.Select( y => 
                      {
                          depCountry = y.ComponentValue("Dep")
                      }).FirstOrDefault()
             }
             .Where(x => x.Value != null)
             .ToDictionary(x => x.Key, x => x.Value());

This will give you a new dictionary. You can access the values

var myTest = newDictionary[key1].depCountry     

PHP: date function to get month of the current date

$unixtime = strtotime($test);
echo date('m', $unixtime); //month
echo date('d', $unixtime); 
echo date('y', $unixtime );

How do I increase the scrollback buffer in a running screen session?

As Already mentioned we have two ways!

 Per screen (session) interactive setting

And it's done interactively! And take effect immediately!

CTRL + A followed by : And we type scrollback 1000000 And hit ENTER

You detach from the screen and come back! It will be always the same.

You open another new screen! And the value is reset again to default! So it's not a global setting!

 And the permanent default setting

Which is done by adding defscrollback 1000000 to .screenrc (in home)

defscrollback and not scrollback (def stand for default)

What you need to know is if the file is not created ! You create it !

> cd ~ && vim .screenrc

And you add defscrollback 1000000 to it!

Or in one command

> echo "defscrollback 1000000" >> .screenrc

(if not created already)

Taking effect

When you add the default to .screenrc! The already running screen at re-attach will not take effect! The .screenrc run at the screen creation! And it make sense! Just as with a normal console and shell launch!

And all the new created screens will have the set value!

Checking the screen effective buffer size

To check type CTRL + A followed by i

And The result will be as

enter image description here

Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)

Note too that when you change it interactively! The effect is immediate and take over the default value!

Scrolling

CTRL+ A followed by ESC (to enter the copy mode).

Then navigate with Up,Down or PgUp PgDown

And ESC again to quit that mode.

(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)

Now the buffer is bigger!

And that's sum it up for the important details!

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

My situation was a bit different.

  • JAVA_HOME was set properly to point to 1.7
  • Other Maven projects were working/building fine with 1.7 features.
  • PATH was set properly.
  • Everything was up-to-date.

Still my simple new Maven project was not working. What I noticed was the difference in the logs when I ran mvn clean install. For my older Maven projects, it showed

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ oldProject---

But for my new project it showed:

[INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ newProject ---

So, I looked at the POM.xml and noticed this thing in the old project's POM:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Basically, this plugin tells which compiler version to use for compilation. Just added it to the new project's POM.xml and things worked.

Hope it is useful to someone.

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

I only delete my old DB located in my localhost directly from wamp, Stop all services, Go to wamp/bin/mysql/mysql[version]/data and I found the DB with problemas, I delete it and start again wamp all services, create again your database and it is done, Now you can import your tables,

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

Came accross the same problem just now.

I have a class named HelloWorld, and I created a test class for it named HelloWorldTests, then I got the output Skipping JaCoCo execution due to missing execution data file.

I then tried to change my pom.xml to make it work, but the attempt failed.

Finally, I simply rename HelloWorldTests to HelloWorldTest, and it worked!

So I guess that, by default, jacoco only recognizes test class named like XxxTest, which indicates that it's the test class for Xxx. So simply rename your test classes to this format should work!