Programs & Examples On #Qtablewidget

QTableWidget is a Qt class providing an item-based table view with a default model.

append multiple values for one key in a dictionary

Here is an alternative way of doing this using the not in operator:

# define an empty dict
years_dict = dict()

for line in list:
    # here define what key is, for example,
    key = line[0]
    # check if key is already present in dict
    if key not in years_dict:
        years_dict[key] = []
    # append some value 
    years_dict[key].append(some.value)

The VMware Authorization Service is not running

type Services at search, then start Services

enter image description here

then start all VM services

enter image description here

How to append new data onto a new line

In Python >= 3.6 you can use new string literal feature:

with open('hst.txt', 'a') as fd:
    fd.write(f'\n{name}')

Please notice using 'with statment' will automatically close the file when 'fd' runs out of scope

Global Git ignore

If you use Unix system, you can solve your problem in two commands. Where the first initialize configs and the second alters file with a file to ignore.

$ git config --global core.excludesfile ~/.gitignore
$ echo '.idea' >> ~/.gitignore

Count the frequency that a value occurs in a dataframe column

I believe this should work fine for any DataFrame columns list.

def column_list(x):
    column_list_df = []
    for col_name in x.columns:
        y = col_name, len(x[col_name].unique())
        column_list_df.append(y)
return pd.DataFrame(column_list_df)

column_list_df.rename(columns={0: "Feature", 1: "Value_count"})

The function "column_list" checks the columns names and then checks the uniqueness of each column values.

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

Check if a string is a valid Windows directory (folder) path

Call Path.GetFullPath; it will throw exceptions if the path is invalid.

To disallow relative paths (such as Word), call Path.IsPathRooted.

How to recursively download a folder via FTP on Linux

Just to complement the answer given by Thibaut Barrère.

I used

wget -r -nH --cut-dirs=5 -nc ftp://user:pass@server//absolute/path/to/directory

Note the double slash after the server name. If you don't put an extra slash the path is relative to the home directory of user.

  • -nH avoids the creation of a directory named after the server name
  • -nc avoids creating a new file if it already exists on the destination (it is just skipped)
  • --cut-dirs=5 allows to take the content of /absolute/path/to/directory and to put it in the directory where you launch wget. The number 5 is used to filter out the 5 components of the path. The double slash means an extra component.

How to center a <p> element inside a <div> container?

on the p element, add 3 styling rules.

.myCenteredPElement{
    margin-left:  auto;
    margin-right: auto;
    text-align: center;
}

Finding the next available id in MySQL

you said:

my id coloumn is auto increment i have to get the id and convert it to another base.So i need to get the next id before insert cause converted code will be inserted too.

what you're asking for is very dangerous and will lead to a race condition. if your code is run twice at the same time by different users, they will both get 6 and their updates or inserts will step all over each other.

i suggest that you instead INSERT in to the table, get the auto_increment value using LAST_INSERT_ID(), and then UPDATE the row to set whatever value you have that depends on the auto_increment value.

Map a network drive to be used by a service

You could us the 'net use' command:

var p = System.Diagnostics.Process.Start("net.exe", "use K: \\\\Server\\path");
var isCompleted = p.WaitForExit(5000);

If that does not work in a service, try the Winapi and PInvoke WNetAddConnection2

Edit: Obviously I misunderstood you - you can not change the sourcecode of the service, right? In that case I would follow the suggestion by mdb, but with a little twist: Create your own service (lets call it mapping service) that maps the drive and add this mapping service to the dependencies for the first (the actual working) service. That way the working service will not start before the mapping service has started (and mapped the drive).

Convert to date format dd/mm/yyyy

<?php
$test1='2010-04-19 18:31:27';
echo date('d/m/Y',strtotime($test1));
?>

try this

How to read from standard input in the console?

Cleanly read in a couple prompted values:

// Create a single reader which can be called multiple times
reader := bufio.NewReader(os.Stdin)
// Prompt and read
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Print("Enter More text: ")
text2, _ := reader.ReadString('\n')
// Trim whitespace and print
fmt.Printf("Text1: \"%s\", Text2: \"%s\"\n",
    strings.TrimSpace(text), strings.TrimSpace(text2))

Here's a run:

Enter text: Jim
Enter More text: Susie
Text1: "Jim", Text2: "Susie"

Passing javascript variable to html textbox

<form name="input" action="some.php" method="post">
 <input type="text" name="user" id="mytext">
 <input type="submit" value="Submit">
</form>

<script>
  var w = someValue;
document.getElementById("mytext").value = w;

</script>

//php on some.php page

echo $_POST['user'];

Looping through a hash, or using an array in PowerShell

About looping through a hash:

$Q = @{"ONE"="1";"TWO"="2";"THREE"="3"}
$Q.GETENUMERATOR() | % { $_.VALUE }
1
3
2

$Q.GETENUMERATOR() | % { $_.key }
ONE
THREE
TWO

error: unknown type name ‘bool’

C90 does not support the boolean data type.

C99 does include it with this include:

#include <stdbool.h>

Check if AJAX response data is empty/blank/null/undefined/0

$.ajax({
    type:"POST",
    url: "<?php echo admin_url('admin-ajax.php'); ?>",
    data: associated_buildsorprojects_form,
    success:function(data){
        // do console.log(data);
        console.log(data);
        // you'll find that what exactly inside data 
        // I do not prefer alter(data); now because, it does not 
        // completes requirement all the time 
        // After that you can easily put if condition that you do not want like
        // if(data != '')
        // if(data == null)
        // or whatever you want 
    },
    error: function(errorThrown){
        alert(errorThrown);
        alert("There is an error with AJAX!");
    }               
});

Converting a char to ASCII?

Uhm, what's wrong with this:

#include <iostream>

using namespace std;

int main(int, char **)
{
    char c = 'A';

    int x = c; // Look ma! No cast!

    cout << "The character '" << c << "' has an ASCII code of " << x << endl;

    return 0;
}

Add a dependency in Maven

You'll have to do this in two steps:

1. Give your JAR a groupId, artifactId and version and add it to your repository.

If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:

mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile

You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ....

2. Update dependent projects to reference this JAR.

Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:

<dependencies>
    ...
    <dependency>
        <groupId>com.stackoverflow...</groupId>
        <artifactId>artifactId...</artifactId>
        <version>1.0</version>
    </dependency>
    ...
</dependencies>

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

I faced the same issue although i added [System.Web.Mvc.AllowHtml] to the concerning property as described in some answers.

In my case, i have an UnhandledExceptionFilter class that accesses the Request object before MVC validation takes place (and therefore AllowHtml has not effect) and this access raises a [HttpRequestValidationException] A potentially dangerous Request.Form value was detected from the client.

This means, accessing certain properties of a Request object implicitly fires validation (in my case its the Params property).

A solution to prevent validation is documented on MSDN

To disable request validation for a specific field in a request (for example, for an input element or query string value), call the Request.Unvalidated method when you get the item, as shown in the following example

Therefore, if you have code like this

var lParams = aRequestContext.HttpContext.Request.Params;
if (lParams.Count > 0)
{
  ...

change it to

var lUnvalidatedRequest = aRequestContext.HttpContext.Request.Unvalidated;

var lForm = lUnvalidatedRequest.Form;
if (lForm.Count > 0)
{
  ...

or just use the Form property which does not seem to fire validation

var lForm = aRequestContext.HttpContext.Request.Form;
if (lForm.Count > 0)
{
  ...

Raw SQL Query without DbSet - Entity Framework Core

I updated extension method from @AminRostami to return IAsyncEnumerable (so LINQ filtering can be applied) and it's mapping Model Column name of records returned from DB to models (Tested with EF Core 5):

Extension itself:

public static class QueryHelper
{
    private static string GetColumnName(this MemberInfo info)
    {
        List<ColumnAttribute> list = info.GetCustomAttributes<ColumnAttribute>().ToList();
        return list.Count > 0 ? list.Single().Name : info.Name;
    }
    /// <summary>
    /// Executes raw query with parameters and maps returned values to column property names of Model provided.
    /// Not all properties are required to be present in model (if not present - null)
    /// </summary>
    public static async IAsyncEnumerable<T> ExecuteQuery<T>(
        [NotNull] this DbContext db,
        [NotNull] string query,
        [NotNull] params SqlParameter[] parameters)
        where T : class, new()
    {
        await using DbCommand command = db.Database.GetDbConnection().CreateCommand();
        command.CommandText = query;
        command.CommandType = CommandType.Text;
        if (parameters != null)
        {
            foreach (SqlParameter parameter in parameters)
            {
                command.Parameters.Add(parameter);
            }
        }
        await db.Database.OpenConnectionAsync();
        await using DbDataReader reader = await command.ExecuteReaderAsync();
        List<PropertyInfo> lstColumns = new T().GetType()
            .GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
        while (await reader.ReadAsync())
        {
            T newObject = new();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                string name = reader.GetName(i);
                PropertyInfo prop = lstColumns.FirstOrDefault(a => a.GetColumnName().Equals(name));
                if (prop == null)
                {
                    continue;
                }
                object val = await reader.IsDBNullAsync(i) ? null : reader[i];
                prop.SetValue(newObject, val, null);
            }
            yield return newObject;
        }
    }
}

Model used (note that Column names are different than actual property names):

public class School
{
    [Key] [Column("SCHOOL_ID")] public int SchoolId { get; set; }

    [Column("CLOSE_DATE", TypeName = "datetime")]
    public DateTime? CloseDate { get; set; }

    [Column("SCHOOL_ACTIVE")] public bool? SchoolActive { get; set; }
}

Actual usage:

public async Task<School> ActivateSchool(int schoolId)
{
    // note that we're intentionally not returning "SCHOOL_ACTIVE" with select statement
    // this might be because of certain IF condition where we return some other data
    return await _context.ExecuteQuery<School>(
        "UPDATE SCHOOL SET SCHOOL_ACTIVE = 1 WHERE SCHOOL_ID = @SchoolId; SELECT SCHOOL_ID, CLOSE_DATE FROM SCHOOL",
        new SqlParameter("@SchoolId", schoolId)
    ).SingleAsync();
}

Spring JPA selecting specific columns

I guess the easy way may be is using QueryDSL, that comes with the Spring-Data.

Using to your question the answer can be

JPAQuery query = new JPAQuery(entityManager);
List<Tuple> result = query.from(projects).list(project.projectId, project.projectName);
for (Tuple row : result) {
 System.out.println("project ID " + row.get(project.projectId));
 System.out.println("project Name " + row.get(project.projectName)); 
}}

The entity manager can be Autowired and you always will work with object and clases without use *QL language.

As you can see in the link the last choice seems, almost for me, more elegant, that is, using DTO for store the result. Apply to your example that will be:

JPAQuery query = new JPAQuery(entityManager);
QProject project = QProject.project;
List<ProjectDTO> dtos = query.from(project).list(new QProjectDTO(project.projectId, project.projectName));

Defining ProjectDTO as:

class ProjectDTO {

 private long id;
 private String name;
 @QueryProjection
 public ProjectDTO(long projectId, String projectName){
   this.id = projectId;
   this.name = projectName;
 }
 public String getProjectId(){ ... }
 public String getProjectName(){....}
}

How do I send a POST request as a JSON?

You have to add header,or you will get http 400 error. The code works well on python2.6,centos5.4

code:

    import urllib2,json

    url = 'http://www.google.com/someservice'
    postdata = {'key':'value'}

    req = urllib2.Request(url)
    req.add_header('Content-Type','application/json')
    data = json.dumps(postdata)

    response = urllib2.urlopen(req,data)

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

Vertically center text in a 100% height div?

Try this one http://jsfiddle.net/Husamuddin/ByNa3/ it works fine with me,
css

.table {
    width:100%;
    height:100%;
    position:absolute;
    display:table;
}
.cell {
    display:table-cell;
    vertical-align:middle;
    width:100%;
    height:100%:
}

and the html

<div class="table">
    <div class="cell">Hello, I'm in the middle</div>
</div>

Count items in a folder with PowerShell

You can also use an alias

(ls).Count

Change hash without reload in jQuery

You can set your hash directly to URL too.

window.location.hash = "YourHash";

The result : http://url#YourHash

Check if date is in the past Javascript

var datep = $('#datepicker').val();

if(Date.parse(datep)-Date.parse(new Date())<0)
{
   // do something
}

How do I use jQuery to redirect?

I found out why this happening.

After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.

Thank you everyone for trying to solve this. :)

"401 Unauthorized" on a directory

You do not have permision to view this directory or page using the credentials that you supplied.

This happened despite the fact the user is already authenticated via Active Directory.

There can be many causes to Access Denied error, but if you think you’ve already configured everything correctly from your web application, there might be a little detail that’s forgotten. Make sure you give the proper permission to Authenticated Users to access your web application directory.

Here are the steps I took to solve this issue.

  1. Right-click on the directory where the web application is stored and select Properties and click on Security tab.

  2. Click on Click on Edit…, then Add… button. Type in Authenticated Users in the Enter the object names to select., then Add button. Type in Authenticated Users in the Enter the object names to select.

  3. Click OK and you should see Authenticated Users as one of the user names. Give proper permissions on the Permissions for Authenticated Users box on the lower end if they’re not checked already.

  4. Click OK twice to close the dialog box. It should take effect immediately, but if you want to be sure, you can restart IIS for your web application.

Refresh your browser and it should display the web page now.

Hope this helps!

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

How to redirect all HTTP requests to HTTPS

This is the proper method of redirecting HTTP to HTTPS using .htaccess according to GoDaddy.com. The first line of code is self-explanatory. The second line of code checks to see if HTTPS is off, and if so it redirects HTTP to HTTPS by running the third line of code, otherwise the third line of code is ignored.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

https://www.godaddy.com/help/redirect-http-to-https-automatically-8828

vue.js 'document.getElementById' shorthand

Theres no shorthand way in vue 2.

Jeff's method seems already deprecated in vue 2.

Heres another way u can achieve your goal.

_x000D_
_x000D_
 var app = new Vue({_x000D_
    el:'#app',_x000D_
    methods: {    _x000D_
        showMyDiv() {_x000D_
           console.log(this.$refs.myDiv);_x000D_
        }_x000D_
    }_x000D_
    _x000D_
   });
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
   <div id="myDiv" ref="myDiv"></div>_x000D_
   <button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to compare datetime with only date in SQL Server

If you are on SQL Server 2008 or later you can use the date datatype:

SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2014-02-07'

It should be noted that if date column is indexed then this will still utilise the index and is SARGable. This is a special case for dates and datetimes.

enter image description here

You can see that SQL Server actually turns this into a > and < clause:

enter image description here

I've just tried this on a large table, with a secondary index on the date column as per @kobik's comments and the index is still used, this is not the case for the examples that use BETWEEN or >= and <:

SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2016-07-05'

showing index usage with secondary index

Add new row to dataframe, at specific row-index, not appended?

The .before argument in dplyr::add_row can be used to specify the row.

dplyr::add_row(
  cars,
  speed = 0,
  dist = 0,
  .before = 3
)
#>    speed dist
#> 1      4    2
#> 2      4   10
#> 3      0    0
#> 4      7    4
#> 5      7   22
#> 6      8   16
#> ...

How to change UINavigationBar background color from the AppDelegate

To change the background color and not the tint the following piece of code will work:

[self.navigationController.navigationBar setBarTintColor:[UIColor greenColor]];
[self.navigationController.navigationBar setTranslucent:NO];

Assign an initial value to radio button as checked

I've put this answer on a similar question that was marked as a duplicate of this question. The answer has helped a decent amount of people so I thought I'd add it here too in just in case.

This doesn't exactly answer the question but for anyone using AngularJS trying to achieve this, the answer is slightly different. And actually the normal answer won't work (at least it didn't for me).

Your html will look pretty similar to the normal radio button:

<input type='radio' name='group' ng-model='mValue' value='first' />First
<input type='radio' name='group' ng-model='mValue' value='second' /> Second

In your controller you'll have declared the mValue that is associated with the radio buttons. To have one of these radio buttons preselected, assign the $scope variable associated with the group to the desired input's value:

$scope.mValue="second"

This makes the "second" radio button selected on loading the page.

How do you read CSS rule values with JavaScript?

Since the accepted answer from "nsdel" is only avilable with one stylesheet in a document this is the adapted full working solution:

    /**
     * Gets styles by a classname
     * 
     * @notice The className must be 1:1 the same as in the CSS
     * @param string className_
     */
    function getStyle(className_) {

        var styleSheets = window.document.styleSheets;
        var styleSheetsLength = styleSheets.length;
        for(var i = 0; i < styleSheetsLength; i++){
            var classes = styleSheets[i].rules || styleSheets[i].cssRules;
            if (!classes)
                continue;
            var classesLength = classes.length;
            for (var x = 0; x < classesLength; x++) {
                if (classes[x].selectorText == className_) {
                    var ret;
                    if(classes[x].cssText){
                        ret = classes[x].cssText;
                    } else {
                        ret = classes[x].style.cssText;
                    }
                    if(ret.indexOf(classes[x].selectorText) == -1){
                        ret = classes[x].selectorText + "{" + ret + "}";
                    }
                    return ret;
                }
            }
        }

    }

Notice: The selector must be the same as in the CSS.

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The error message explains it pretty well:

ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()

What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

(1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

(2) True, because at least one element is True;

(3) False, because not all elements are True;

and that's not even considering the complexity of the N-d case.

So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

and you might want to consider np.allclose if you're comparing arrays of floats:

>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True

How to get the month name in C#?

You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.

I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.

Here is an example of how to do it using extension methods:

using System;
using System.Globalization;

class Program
{
    static void Main()
    {

        Console.WriteLine(DateTime.Now.ToMonthName());
        Console.WriteLine(DateTime.Now.ToShortMonthName());
        Console.Read();
    }
}

static class DateTimeExtensions
{
    public static string ToMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
    }

    public static string ToShortMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
    }
}

Hope this helps!

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

How to iterate (keys, values) in JavaScript?

Try this:

var value;
for (var key in dictionary) {
    value = dictionary[key];
    // your code here...
}

How to make tesseract to recognize only numbers, when they are mixed with letters?

You can instruct tesseract to use only digits, and if that is not accurate enough then best chance of getting better results is to go trough training process: http://www.resolveradiologic.com/blog/2013/01/15/training-tesseract/

Get all unique values in a JavaScript array (remove duplicates)

If you want to only get the unique elements and remove the elements which repeats even once, you can do this:

_x000D_
_x000D_
let array = [2, 3, 4, 1, 2, 8, 1, 1, 2, 9, 3, 5, 3, 4, 8, 4];

function removeDuplicates(inputArray) {
  let output = [];
  let countObject = {};

  for (value of array) {
    countObject[value] = (countObject[value] || 0) + 1;
  }

  for (key in countObject) {
    if (countObject[key] === 1) {
      output.push(key);
    }
  }

  return output;
}

console.log(removeDuplicates(array));
_x000D_
_x000D_
_x000D_

Logging request/response messages when using HttpClient

Network tracing also available for next objects (see article on msdn)

  • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
  • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
  • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
  • System.Net.Cache Some private and internal methods in System.Net.Cache.
  • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
  • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

Put next lines of code to the configuration file

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

Can I inject a service into a directive in AngularJS?

Change your directive definition from app.module to app.directive. Apart from that everything looks fine. Btw, very rarely do you have to inject a service into a directive. If you are injecting a service ( which usually is a data source or model ) into your directive ( which is kind of part of a view ), you are creating a direct coupling between your view and model. You need to separate them out by wiring them together using a controller.

It does work fine. I am not sure what you are doing which is wrong. Here is a plunk of it working.

http://plnkr.co/edit/M8omDEjvPvBtrBHM84Am

How to correctly set Http Request Header in Angular 2

This should be easily resolved by importing headers from Angular:

import { Http, Headers } from "@angular/http";

Make a div fill the height of the remaining screen space

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<style type="text/css">
body
,html
{
    height: 100%;
    margin: 0;
    padding: 0;
    color: #FFF;
}

#header
{
    float: left;
    width: 100%;
    background: red;
}

#content
{
    height: 100%;
    overflow: auto;
    background: blue;
}

</style>
</head>
<body>

    <div id="content">
        <div id="header">
                Header
                <p>Header stuff</p>
        </div>
            Content
            <p>Content stuff</p>
    </div>

</body>
</html>

In all sane browsers, you can put the "header" div before the content, as a sibling, and the same CSS will work. However, IE7- does not interpret the height correctly if the float is 100% in that case, so the header needs to be IN the content, as above. The overflow: auto will cause double scroll bars on IE (which always has the viewport scrollbar visible, but disabled), but without it, the content will clip if it overflows.

How to hide a TemplateField column in a GridView

If appears to me that rows where Visible is set to false won't be accessible, that they are removed from the DOM rather than hidden, so I also used the Display: None approach. In my case, I wanted to have a hidden column that contained the key of the Row. To me, this declarative approach is a little cleaner than some of the other approaches that use code.

<style>
   .HiddenCol{display:none;}                
</style>


 <%--ROW ID--%>
      <asp:TemplateField HeaderText="Row ID">
       <HeaderStyle CssClass="HiddenCol" />
       <ItemTemplate>
       <asp:Label ID="lblROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:Label>
       </ItemTemplate>
       <ItemStyle HorizontalAlign="Right" CssClass="HiddenCol" />
       <EditItemTemplate>
       <asp:TextBox ID="txtROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:TextBox>
       </EditItemTemplate>
       <FooterStyle CssClass="HiddenCol" />
      </asp:TemplateField>

long long int vs. long int vs. int64_t in C++

So my question is: Is there a way to tell the compiler that a long long int is the also a int64_t, just like long int is?

This is a good question or problem, but I suspect the answer is NO.

Also, a long int may not be a long long int.


# if __WORDSIZE == 64
typedef long int  int64_t;
# else
__extension__
typedef long long int  int64_t;
# endif

I believe this is libc. I suspect you want to go deeper.

In both 32-bit compile with GCC (and with 32- and 64-bit MSVC), the output of the program will be:

int:           0
int64_t:       1
long int:      0
long long int: 1

32-bit Linux uses the ILP32 data model. Integers, longs and pointers are 32-bit. The 64-bit type is a long long.

Microsoft documents the ranges at Data Type Ranges. The say the long long is equivalent to __int64.

However, the program resulting from a 64-bit GCC compile will output:

int:           0
int64_t:       1
long int:      1
long long int: 0

64-bit Linux uses the LP64 data model. Longs are 64-bit and long long are 64-bit. As with 32-bit, Microsoft documents the ranges at Data Type Ranges and long long is still __int64.

There's a ILP64 data model where everything is 64-bit. You have to do some extra work to get a definition for your word32 type. Also see papers like 64-Bit Programming Models: Why LP64?


But this is horribly hackish and does not scale well (actual functions of substance, uint64_t, etc)...

Yeah, it gets even better. GCC mixes and matches declarations that are supposed to take 64 bit types, so its easy to get into trouble even though you follow a particular data model. For example, the following causes a compile error and tells you to use -fpermissive:

#if __LP64__
typedef unsigned long word64;
#else
typedef unsigned long long word64;
#endif

// intel definition of rdrand64_step (http://software.intel.com/en-us/node/523864)
// extern int _rdrand64_step(unsigned __int64 *random_val);

// Try it:
word64 val;
int res = rdrand64_step(&val);

It results in:

error: invalid conversion from `word64* {aka long unsigned int*}' to `long long unsigned int*'

So, ignore LP64 and change it to:

typedef unsigned long long word64;

Then, wander over to a 64-bit ARM IoT gadget that defines LP64 and use NEON:

error: invalid conversion from `word64* {aka long long unsigned int*}' to `uint64_t*'

How to compare binary files to check if they are the same?

I ended up using hexdump to convert the binary files to there hex representation and then opened them in meld / kompare / any other diff tool. Unlike you I was after the differences in the files.

hexdump tmp/Circle_24.png > tmp/hex1.txt
hexdump /tmp/Circle_24.png > tmp/hex2.txt

meld tmp/hex1.txt tmp/hex2.txt

Why is C so fast, and why aren't other languages as fast or faster?

With modern optimizing compilers, it's highly unlikely that a pure C program is going to be all that much faster than compiled .net code, if at all. With the productivity enhancement that frameworks like .net provide the developer, you can do things in a day that used to take weeks or months in regular C. Coupled with the cheap cost of hardware compared to a developer's salary, it's just WAY cheaper to write the stuff in a high-level language and throw hardware at any slowness.

The reason Jeff and Joel talk about C being the "real programmer" language is because there is no hand-holding in C. You must allocate your own memory, deallocate that memory, do your own bounds-checking, etc. There's no such thing as new object(); There's no garbage collection, classes, OOP, entity frameworks, LINQ, properties, attributes, fields, or anything like that. You have to know things like pointer arithmetic and how to dereference a pointer. And, for that matter, know and understand what a pointer is. You have to know what a stack frame is and what the instruction pointer is. You have to know the memory model of the CPU architecture you're working on. There is a lot of implicit understanding of the architecture of a microcomputer (usually the microcomputer you're working on) when programming in C that simply is not present nor necessary when programming in something like C# or Java. All of that information has been off-loaded to the compiler (or VM) programmer.

Assign keyboard shortcut to run procedure

For assigning a keyboard key to button on the sheet you can use this code, just copy this code to the sheet which contain the button.

Here Return specifies the key and get_detail is the procedure name.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.OnKey "{RETURN}", "get_detail"

End Sub

Now within this sheet whenever you press Enter button the assigned macro will be called.

How to change background and text colors in Sublime Text 3

For How do I change the overall colors (background and font)?

For MAC : goto Sublime text -> Preferences -> color scheme

sprintf like functionality in Python

To insert into a very long string it is nice to use names for the different arguments, instead of hoping they are in the right positions. This also makes it easier to replace multiple recurrences.

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'

Taken from Format examples, where all the other Format-related answers are also shown.

Share data between html pages

why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.

To store values for a session:

sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')

or more permanently:

localStorage.getItem('label')
localStorage.setItem('label', 'value')

So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..

Provide an image for WhatsApp link sharing

Since at this point this question is almost a support group for people who suffer with various reasons on why WhatsApp wouldn't load the image preview, here's what was the root cause for my case, hoping it may help someone eventually:

Make sure the meta tag og:image content link is using HTTPS

When I made my website available through https, I forgot to specifically change the meta tags from http to https. Every other social media preview handled the image regardless, except for WhatsApp.

Simply making it https fixed it for me.

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

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

Try this test:

any(substring in string for substring in substring_list)

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

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

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

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

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

How can I convert a date to GMT?

You can simply use the toUTCString (or toISOString) methods of the date object.

Example:

new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()

// Output:  "Fri, 20 Jan 2012 16:51:36 GMT"

If you prefer better control of the output format, consider using a library such as date-fns or moment.js.

Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have already been adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.

11:51:36 -0300  ==  14:51:36Z

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

This is another version which work in case you have some tasks to cleanup. Code will leave clean up process in their method.

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

)



func main() {

    _,done1:=doSomething1()
    _,done2:=doSomething2()

    //do main thread


    println("wait for finish")
    <-done1
    <-done2
    fmt.Print("clean up done, can exit safely")

}

func doSomething1() (error, chan bool) {
    //do something
    done:=make(chan bool)
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        //cleanup of something1
        done<-true
    }()
    return nil,done
}


func doSomething2() (error, chan bool) {
    //do something
    done:=make(chan bool)
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        //cleanup of something2
        done<-true
    }()
    return nil,done
}

in case you need to clean main function you need to capture signal in main thread using go func() as well.

exec failed because the name not a valid identifier?

As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below

e.g.

Exec N'Select bla..' 

the N defines string literal is unicode.

Set value for particular cell in pandas DataFrame with iloc

Extending Jianxun's answer, using set_value mehtod in pandas. It sets value for a column at given index.

From pandas documentations:

DataFrame.set_value(index, col, value)

To set value at particular index for a column, do:

df.set_value(index, 'COL_NAME', x)

Hope it helps.

String.equals versus ==

== operator compares the reference of an object in Java. You can use string's equals method .

String s = "Test";
if(s.equals("Test"))
{
    System.out.println("Equal");
}

Stack array using pop() and push()

Stack Implementation in Java

  class stack
  {  private int top;
     private int[] element;
      stack()
      {element=new int[10];
      top=-1;
      }
      void push(int item)
      {top++;
      if(top==9)
          System.out.println("Overflow");
      else
              {
               top++;
      element[top]=item;

      }

      void pop()
      {if(top==-1)
          System.out.println("Underflow");
      else  
      top--;
      }
      void display()
      {
          System.out.println("\nTop="+top+"\nElement="+element[top]);
      }

      public static void main(String args[])
      {
        stack s1=new stack();
        s1.push(10);
        s1.display();
        s1.push(20);
        s1.display();
        s1.push(30);
        s1.display();
        s1.pop();
        s1.display();
      }

  }

Output

Top=0 Element=10 Top=1 Element=20 Top=2 Element=30 Top=1 Element=20

working with negative numbers in python

Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions

#this is apparently a better way of getting multiple inputs at the same time than the 
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])

#standing variables
total = 0

if numb > 0:
    repeat = numb
else:
    repeat = -numb

#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
    total += numa


#check to make sure the output is accurate
if numb < 0:
    total = -total


print total

Thanks for all the help everyone.

Good Hash Function for Strings

You should probably use String.hashCode().

If you really want to implement hashCode yourself:

Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance -- Joshua Bloch, Effective Java

Using only the first five characters is a bad idea. Think about hierarchical names, such as URLs: they will all have the same hash code (because they all start with "http://", which means that they are stored under the same bucket in a hash map, exhibiting terrible performance.

Here's a war story paraphrased on the String hashCode from "Effective Java":

The String hash function implemented in all releases prior to 1.2 examined at most sixteen characters, evenly spaced throughout the string, starting with the first character. For large collections of hierarchical names, such as URLs, this hash function displayed terrible behavior.

How to check if a String is numeric in Java

// please check below code

public static boolean isDigitsOnly(CharSequence str) {
    final int len = str.length();
    for (int i = 0; i < len; i++) {
        if (!Character.isDigit(str.charAt(i))) {
            return false;
        }
    }
    return true;
}

Create a new line in Java's FileWriter

Try System.getProperty( "line.separator" )

   writer.write(System.getProperty( "line.separator" ));

Writing to a new file if it doesn't exist, and appending to a file if it does

Using the pathlib module (python's object-oriented filesystem paths)

Just for kicks, this is perhaps the latest pythonic version of the solution.

from pathlib import Path 

path = Path(f'{player}.txt')
path.touch()  # default exists_ok=True
with path.open('a') as highscore:
   highscore.write(f'Username:{player}')

How do I execute a file in Cygwin?

Apparently, gcc doesn't behave like the one described in The C Programming language, where it says that the command cc helloworld.c produces a file called a.out which can be run by typing a.out on the prompt.

A Unix hasn't behaved in that way by default (so you can just write the executable name without ./ at the front) in a long time. It's called a.exe, because else Windows won't execute it, as it gets file types from the extension.

How can I get the selected VALUE out of a QCombobox?

I did this

QDir path("/home/user/");
QStringList _dirs = path.entryList(QDir::Dirs);
std::cout << "_dirs_count = " << _dirs.count() << std::endl;
ui->cmbbox->addItem(Files);
ui->cmbbox->show();

You will see with this that the QStringList named _dirs is structured like an array whose members you can access via an index up to the value returned by _dirs.count()

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

Java - Relative path of a file in a java web application

Do you really need to load it from a file? If you place it along your classes (in WEB-INF/classes) you can get an InputStream to it using the class loader:

InputStream csv = 
   SomeClassInTheSamePackage.class.getResourceAsStream("filename.csv");

Are lists thread-safe?

I recently had this case where I needed to append to a list continuously in one thread, loop through the items and check if the item was ready, it was an AsyncResult in my case and remove it from the list only if it was ready. I could not find any examples that demonstrated my problem clearly Here is an example demonstrating adding to list in one thread continuously and removing from the same list in another thread continuously The flawed version runs easily on smaller numbers but keep the numbers big enough and run a few times and you will see the error

The FLAWED version

import threading
import time

# Change this number as you please, bigger numbers will get the error quickly
count = 1000
l = []

def add():
    for i in range(count):
        l.append(i)
        time.sleep(0.0001)

def remove():
    for i in range(count):
        l.remove(i)
        time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output when ERROR

Exception in thread Thread-63:
Traceback (most recent call last):
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "<ipython-input-30-ecfbac1c776f>", line 13, in remove
    l.remove(i)
ValueError: list.remove(x): x not in list

Version that uses locks

import threading
import time
count = 1000
l = []
lock = threading.RLock()
def add():
    with lock:
        for i in range(count):
            l.append(i)
            time.sleep(0.0001)

def remove():
    with lock:
        for i in range(count):
            l.remove(i)
            time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output

[] # Empty list

Conclusion

As mentioned in the earlier answers while the act of appending or popping elements from the list itself is thread safe, what is not thread safe is when you append in one thread and pop in another

Difference between two dates in Python

I tried a couple of codes, but end up using something as simple as (in Python 3):

from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])

If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.

If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):

df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date

And then run:

df['difference_in_days'] = abs(df['end_date'] - df['start_date'])

How do I define and use an ENUM in Objective-C?

With current projects you may want to use the NS_ENUM() or NS_OPTIONS() macros.

typedef NS_ENUM(NSUInteger, PlayerState) {
        PLAYER_OFF,
        PLAYER_PLAYING,
        PLAYER_PAUSED
    };

View HTTP headers in Google Chrome?

To view the request or response HTTP headers in Google Chrome, take the following steps :

  1. In Chrome, visit a URL(such as https://www.google.com), right click, select Inspect to open the developer tools.
    enter image description here
  2. Select Network tab.
  3. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.

enter image description here

Good Linux (Ubuntu) SVN client

See my question:

What is the best subversion client for Linux?

I also agree, GUI clients in linux suck.

I use subeclipse in Eclipse and RapidSVN in gnome.

how to know status of currently running jobs

You can query the table msdb.dbo.sysjobactivity to determine if the job is currently running.

Send message to specific client with socket.io and node.js

Socket.IO allows you to “namespace” your sockets, which essentially means assigning different endpoints or paths.

This might help: http://socket.io/docs/rooms-and-namespaces/

Python logging: use milliseconds in time format

If you are using arrow or if you don't mind using arrow. You can substitute python's time formatting for arrow's one.

import logging

from arrow.arrow import Arrow


class ArrowTimeFormatter(logging.Formatter):

    def formatTime(self, record, datefmt=None):
        arrow_time = Arrow.fromtimestamp(record.created)

        if datefmt:
            arrow_time = arrow_time.format(datefmt)

        return str(arrow_time)


logger = logging.getLogger(__name__)

default_handler = logging.StreamHandler()
default_handler.setFormatter(ArrowTimeFormatter(
    fmt='%(asctime)s',
    datefmt='YYYY-MM-DD HH:mm:ss.SSS'
))

logger.setLevel(logging.DEBUG)
logger.addHandler(default_handler)

Now you can use all of arrow's time formatting in datefmt attribute.

Use ffmpeg to add text subtitles

I tried using MP4Box for this task, but it couldn't handle the M4V I was dealing with. I had success embedding the SRT as soft subtitles with ffmpeg with the following command line:

ffmpeg -i input.m4v -i input.srt -vcodec copy -acodec copy -scodec copy -map 0:0 -map 0:1 -map 1:0 -y output.mkv

Like you I had to use an MKV output file - I wasn't able to create an M4V file.

Bootstrap row class contains margin-left and margin-right which creates problems

I was facing this same issue and initially, I removed the row's right and left -ve margin and it removed the horizontal scroll, but it wasn't good. Then after 45 minutes of inspecting and searching, I found out that I was using container-fluid and was removing the padding and its inner row had left and right negative margins. So I gave container-fluid it's padding back and everything went back to normal.

If you do need to remove container-fluid padding, don't just remove every row's left and right negative margin in your project instead introduce a class and use that on your desired container

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Add this link:

/usr/local/lib/*.so.*

The total is:

g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*

Python and JSON - TypeError list indices must be integers not str

First of all, you should be using json.loads, not json.dumps. loads converts JSON source text to a Python value, while dumps goes the other way.

After you fix that, based on the JSON snippet at the top of your question, readable_json will be a list, and so readable_json['firstName'] is meaningless. The correct way to get the 'firstName' field of every element of a list is to eliminate the playerstuff = readable_json['firstName'] line and change for i in playerstuff: to for i in readable_json:.

Difference between long and int data types

From this reference:

An int was originally intended to be the "natural" word size of the processor. Many modern processors can handle different word sizes with equal ease.

Also, this bit:

On many (but not all) C and C++ implementations, a long is larger than an int. Today's most popular desktop platforms, such as Windows and Linux, run primarily on 32 bit processors and most compilers for these platforms use a 32 bit int which has the same size and representation as a long.

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I had this error. Nothing worked for me until I opened the SQLServer log file in the "MSSQL10_50" Log folder. That clearly stated which file could not be overwritten. It turned out that the .mdf file was being written into the "MSSQL10" data folder. I made sure that folder had the same SQLServer user permissions as the "MSSQL10_50" equivalent folder. Then it all worked.

The issue here is that the error detail is logged but not reported, so check the logs.

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

Use Fail module.

  1. Use ignore_errors with every task that you need to ignore in case of errors.
  2. Set a flag (say, result = false) whenever there is a failure in any task execution
  3. At the end of the playbook, check if flag is set, and depending on that, fail the execution
- fail: msg="The execution has failed because of errors."
  when: flag == "failed"

Update:

Use register to store the result of a task like you have shown in your example. Then, use a task like this:

- name: Set flag
  set_fact: flag = failed
  when: "'FAILED' in command_result.stderr"

Best way to list files in Java, sorted by Date Modified?

In Java 8:

Arrays.sort(files, (a, b) -> Long.compare(a.lastModified(), b.lastModified()));

Detecting an "invalid date" Date instance in JavaScript

Would like to mention that the jQuery UI DatePicker widget has a very good date validator utility method that checks for format and validity (e.g., no 01/33/2013 dates allowed).

Even if you don't want to use the datepicker widget on your page as a UI element, you can always add its .js library to your page and then call the validator method, passing the value you want to validate into it. To make life even easier, it takes a string as input, not a JavaScript Date object.

See: http://api.jqueryui.com/datepicker/

It's not listed as a method, but it is there-- as a utility function. Search the page for "parsedate" and you'll find:

$.datepicker.parseDate( format, value, settings ) - Extract a date from a string value with a specified format.

Example usage:

var stringval = '01/03/2012';
var testdate;

try {
  testdate = $.datepicker.parseDate('mm/dd/yy', stringval);
             // Notice 'yy' indicates a 4-digit year value
} catch (e)
{
 alert(stringval + ' is not valid.  Format must be MM/DD/YYYY ' +
       'and the date value must be valid for the calendar.';
}

(More info re specifying date formats is found at http://api.jqueryui.com/datepicker/#utility-parseDate)

In the above example, you wouldn't see the alert message since '01/03/2012' is a calendar-valid date in the specified format. However if you made 'stringval' equal to '13/04/2013', for example, you would get the alert message, since the value '13/04/2013' is not calendar-valid.

If a passed-in string value is successfully parsed, the value of 'testdate' would be a Javascript Date object representing the passed-in string value. If not, it'd be undefined.

Emulator error: This AVD's configuration is missing a kernel file

If you know the kernel file is installed on your machine, then problem is getting emulator.exe to find it.

My fix was based on the post by user2789389. I could launch the AVD from the AVD Manager, but not from the command line. So, using AVD Manager, I selected the avd I wanted to run and clicked "Details". That showed me the path to the avd definition file. Within a folder of the same name, next to this .avd file, I found a config.ini file. In the ini, I found the following line:

image.sysdir.1=system-images\android-19\default\armeabi-v7a\

I looked in the folder C:\Users\XXXX\android-sdks\system-images\android-19, and found that the image.sysdir.1 path was invalid. I had to remove the "default" sub folder, thus changing it to the following:

image.sysdir.1=system-images\android-19\armeabi-v7a\

I saved the ini and tried again to launch the AVD. That fixed the problem!

How to use the onClick event for Hyperlink using C# code?

The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)

What you want is a server-side control, like the LinkButton:

<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>

This has an OnClick attribute that will call the method in your code behind.

Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
    userinfo = (UserInfo)Session["UserInfo"];

    if (userinfo.user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Really, it would be best to check that you actually have a user first.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

Check the properties of your projectm the platform target. Install the corresponding version of Crystal Reports:

To x86 > CRforVS_redist_install_32bit
To x64 > CRforVS_redist_install_64bit

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

Server Discovery And Monitoring engine is deprecated

This worked for me

For folks using MongoClient try this:

MongoClient.connect(connectionurl, 
  {useUnifiedTopology: true, useNewUrlParser: true},  callback() {

For mongoose:

mongoose.connect(connectionurl, 
         {useUnifiedTopology: true, useNewUrlParser: true}).then(()=>{

Remove other connectionOptions

How to check if element in groovy array/hash/collection/list?

If you really want your includes method on an ArrayList, just add it:

ArrayList.metaClass.includes = { i -> i in delegate }

mysql_config not found when installing mysqldb python interface

For Alpine Linux:

$ apk add mariadb-dev mariadb-client mariadb-libs

MariaDB is a drop-in replacement for MySQL and became the new standard as of Alpine 3.2. See https://bugs.alpinelinux.org/issues/4264

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

My solution is

fig = plt.figure()
fig.add_subplot(1, 2, 1)   #top and bottom left
fig.add_subplot(2, 2, 2)   #top right
fig.add_subplot(2, 2, 4)   #bottom right 
plt.show()

2x2 grid with 1 and 3 merge

Powershell remoting with ip-address as target

Try doing this:

Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

std::string to char*

This will also work

std::string s;
std::cout<<"Enter the String";
std::getline(std::cin, s);
char *a=new char[s.size()+1];
a[s.size()]=0;
memcpy(a,s.c_str(),s.size());
std::cout<<a;  

How do I remove the passphrase for the SSH key without having to create a new key?

To change or remove the passphrase, I often find it simplest to pass in only the p and f flags, then let the system prompt me to supply the passphrases:

ssh-keygen -p -f <name-of-private-key>

For instance:

ssh-keygen -p -f id_rsa

Enter an empty password if you want to remove the passphrase.

A sample run to remove or change a password looks something like this:

ssh-keygen -p -f id_rsa
Enter old passphrase: 
Key has comment 'bcuser@pl1909'
Enter new passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved with the new passphrase.

When adding a passphrase to a key that has no passphrase, the run looks something like this:

ssh-keygen -p -f id_rsa
Key has comment 'charlie@elf-path'
Enter new passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved with the new passphrase.

in_array multiple values

Intersect the targets with the haystack and make sure the intersection is precisely equal to the targets:

$haystack = array(...);

$target = array('foo', 'bar');

if(count(array_intersect($haystack, $target)) == count($target)){
    // all of $target is in $haystack
}

Note that you only need to verify the size of the resulting intersection is the same size as the array of target values to say that $haystack is a superset of $target.

To verify that at least one value in $target is also in $haystack, you can do this check:

 if(count(array_intersect($haystack, $target)) > 0){
     // at least one of $target is in $haystack
 }

Global variables in AngularJS

It's actually pretty easy. (If you're using Angular 2+ anyway.)

Simply add

declare var myGlobalVarName;

Somewhere in the top of your component file (such as after the "import" statements), and you'll be able to access "myGlobalVarName" anywhere inside your component.

Updating a JSON object using Javascript

For example I am using this technique in Basket functionality.

Let us add new Item to Basket.

var productArray=[];


$(document).on('click','[cartBtn]',function(e){
  e.preventDefault();
  $(this).html('<i class="fa fa-check"></i>Added to cart');
  console.log('Item added ');
  var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image'), "quantity":1, "discount":0, "total":$(this).attr('pr_price')};


  if(localStorage.getObj('product')!==null){
    productArray=localStorage.getObj('product');
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }
  else{
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }


  itemCountInCart(productArray.length);

});

After adding some item to basket - generates json array like this

[
    {
        "id": "95",
        "nameEn": "New Braslet",
        "price": "8776",
        "image": "1462012394815.jpeg",
        "quantity": 1,
        "discount": 0,
        "total": "8776"
    },
    {
        "id": "96",
        "nameEn": "new braslet",
        "price": "76",
        "image": "1462012431497.jpeg",
        "quantity": 1,
        "discount": 0,
        "total": "76"
    },
    {
        "id": "97",
        "nameEn": "khjk",
        "price": "87",
        "image": "1462012483421.jpeg",
        "quantity": 1,
        "discount": 0,
        "total": "87"
    }
]

For Removing some item from Basket.

$(document).on('click','[itemRemoveBtn]',function(){

var arrayFromLocal=localStorage.getObj('product');
findAndRemove(arrayFromLocal,"id",$(this).attr('basketproductid'));
localStorage.setObj('product', arrayFromLocal);
loadBasketFromLocalStorageAndRender();
});

//This function will remove element by specified property. In my case this is ID.
function findAndRemove(array, property, value) {
  array.forEach(function(result, index) {
    if(result[property] === value) {
      //Remove from array
      console.log('Removed from index is '+index+' result is '+JSON.stringify(result));
      array.splice(index, 1);

    }    
  });
}

And Finally the real answer of the question "Updating a JSON object using JS". In my example updating product quantity and total price on changing the "number" element value.

$(document).on('keyup mouseup','input[type=number]',function(){

  var arrayFromLocal=localStorage.getObj('product');
  setQuantityAndTotalPrice(arrayFromLocal,$(this).attr('updateItemid'),$(this).val());
  localStorage.setObj('product', arrayFromLocal);
  loadBasketFromLocalStorageAndRender();
});

function setQuantityAndTotalPrice(array,id,quantity) {

  array.forEach(function(result, index) {
    if(result.id === id) {
      result.quantity=quantity;
      result.total=(quantity*result.price);
    }    
  });

}

Changing precision of numeric column in Oracle

By setting the scale, you decrease the precision. Try NUMBER(16,2).

Using Mockito with multiple calls to the same method with the same arguments

How about

when( method-call ).thenReturn( value1, value2, value3 );

You can put as many arguments as you like in the brackets of thenReturn, provided they're all the correct type. The first value will be returned the first time the method is called, then the second answer, and so on. The last value will be returned repeatedly once all the other values are used up.

Fastest way to check if a string matches a regexp in ruby?

Starting with Ruby 2.4.0, you may use RegExp#match?:

pattern.match?(string)

Regexp#match? is explicitly listed as a performance enhancement in the release notes for 2.4.0, as it avoids object allocations performed by other methods such as Regexp#match and =~:

Regexp#match?
Added Regexp#match?, which executes a regexp match without creating a back reference object and changing $~ to reduce object allocation.

How do I clone into a non-empty directory?

Warning - this could potentially overwrite files.

git init     
git remote add origin PATH/TO/REPO     
git fetch     
git checkout -t origin/master -f

Modified from @cmcginty's answer - without the -f it didn't work for me

Xcode doesn't see my iOS device but iTunes does

Xcode 10.2.1 was not recognizing my ipad mini. I unplugged and rebooted the mini and it became visible.

Merging 2 branches together in GIT

If you want to merge changes in SubBranch to MainBranch

  1. you should be on MainBranch git checkout MainBranch
  2. then run merge command git merge SubBranch

How to measure time taken between lines of code in python?

You can try this as well:

from time import perf_counter

t0 = perf_counter()

...

t1 = perf_counter()
time_taken = t1 - t0

How do you fadeIn and animate at the same time?

For people still looking a couple of years later, things have changed a bit. You can now use the queue for .fadeIn() as well so that it will work like this:

$('.tooltip').fadeIn({queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

This has the benefit of working on display: none elements so you don't need the extra two lines of code.

Error message "Forbidden You don't have permission to access / on this server"

This article Creating virtual hosts on Apache 2.2 helps me (point 9) permissions to the top virtual hosts directory.

I simply add this lines to my vhosts.conf file:

<Directory I:/projects/webserver>
    Order Deny,Allow
    Allow from all
</Directory>

Firebase FCM notifications click_action payload

I'm looking this Firebase is , development from google cloud messaging push notification fundamental so we can use the gcm tutorial,function and implementation in firebase , i using funtion of gcm push notification function to solve this click_action problem i use gcm function **

'notificationclick'

** try this save url click_action in variable url this is in server-worker.js

var url =  "";

messaging.setBackgroundMessageHandler(function(payload) {

  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  url = payload.data.click_action;

  const notificationTitle = payload.data.title;
  const notificationOptions = {
    body: payload.data.body , 
    icon: 'firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
      notificationOptions);

});


   //i got this in google cloud messaging push notification


self.addEventListener('notificationclick', function (event) {
  event.notification.close();

  var clickResponsePromise = Promise.resolve();
    clickResponsePromise = clients.openWindow(url);

  event.waitUntil(Promise.all([clickResponsePromise, self.analytics.trackEvent('notification-click')]));
});

time data does not match format

To compare date time, you can try this. Datetime format can be changed

from datetime import datetime

>>> a = datetime.strptime("10/12/2013", "%m/%d/%Y")
>>> b = datetime.strptime("10/15/2013", "%m/%d/%Y")
>>> a>b
False

Should I make HTML Anchors with 'name' or 'id'?

I have a web page consisting of a number of vertically stacked div containers, identical in format and differing only in serial number. I wanted to hide the name anchor at the top of each div, so the most economical solution turned out to be including the anchor as an id within the opening div tag, i.e,

<div id="[serial number]" class="topic_wrapper">

Convert a date format in PHP

Use this function to convert from any format to any format

function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
    $date_aux = date_create_from_format($from_format, $date);
    return date_format($date_aux,$to_format);
}

error 1265. Data truncated for column when trying to load data from txt file

I have met this problem with a column that has ENUM values('0','1').
When I was trying to save a new record, I was assigning value 0 for the ENUM variable.

For the solution: I have changed ENUM variable value from 0 to 1, and 1 to 2.

Visual Studio: Relative Assembly References Paths

Yes, just create a directory in your solution like lib/, and then add your dll to that directory in the filesystem and add it in the project (Add->Existing Item->etc). Then add the reference based on your project.

I have done this several times under svn and under cvs.

LINQ Using Max() to select a single row

You can also do:

(from u in table
orderby u.Status descending
select u).Take(1);

how to set auto increment column with sql developer

If you want to make your PK auto increment, you need to set the ID column property for that primary key.

  1. Right click on the table and select "Edit".
  2. In "Edit" Table window, select "columns", and then select your PK column.
  3. Go to ID Column tab and select Column Sequence as Type. This will create a trigger and a sequence, and associate the sequence to primary key.

See the picture below for better understanding.

enter image description here

// My source is: http://techatplay.wordpress.com/2013/11/22/oracle-sql-developer-create-auto-incrementing-primary-key/

How to display an unordered list in two columns?

Here's a possible solution:

Snippet:

_x000D_
_x000D_
ul {_x000D_
  width: 760px;_x000D_
  margin-bottom: 20px;_x000D_
  overflow: hidden;_x000D_
  border-top: 1px solid #ccc;_x000D_
}_x000D_
li {_x000D_
  line-height: 1.5em;_x000D_
  border-bottom: 1px solid #ccc;_x000D_
  float: left;_x000D_
  display: inline;_x000D_
}_x000D_
#double li {_x000D_
  width: 50%;_x000D_
}
_x000D_
<ul id="double">_x000D_
  <li>first</li>_x000D_
  <li>second</li>_x000D_
  <li>third</li>_x000D_
  <li>fourth</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

And it is done.
For 3 columns use li width as 33%, for 4 columns use 25% and so on.

Why does the order in which libraries are linked sometimes cause errors in GCC?

If you add -Wl,--start-group to the linker flags it does not care which order they're in or if there are circular dependencies.

On Qt this means adding:

QMAKE_LFLAGS += -Wl,--start-group

Saves loads of time messing about and it doesn't seem to slow down linking much (which takes far less time than compilation anyway).

Explicitly set column value to null SQL Developer

It is clear that most people who haven't used SQL Server Enterprise Manager don't understand the question (i.e. Justin Cave).

I came upon this post when I wanted to know the same thing.

Using SQL Server, when you are editing your data through the MS SQL Server GUI Tools, you can use a KEYBOARD SHORTCUT to insert a NULL rather than having just an EMPTY CELL, as they aren't the same thing. An empty cell can have a space in it, rather than being NULL, even if it is technically empty. The difference is when you intentionally WANT to put a NULL in a cell rather than a SPACE or to empty it and NOT using a SQL statement to do so.

So, the question really is, how do I put a NULL value in the cell INSTEAD of a space to empty the cell?

I think the answer is, that the way the Oracle Developer GUI works, is as Laniel indicated above, And THAT should be marked as the answer to this question.

Oracle Developer seems to default to NULL when you empty a cell the way the op is describing it.

Additionally, you can force Oracle Developer to change how your null cells look by changing the color of the background color to further demonstrate when a cell holds a null:

Tools->Preferences->Advanced->Display Null Using Background Color

or even the VALUE it shows when it's null:

Tools->Preferences->Advanced->Display Null Value As

Hope that helps in your transition.

Jquery: how to sleep or delay?

If you can't use the delay method as Robert Harvey suggested, you can use setTimeout.

Eg.

setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one

Writing Python lists to columns in csv

change them to rows

rows = zip(list1,list2,list3,list4,list5)

then just

import csv

with open(newfilePath, "w") as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)

GIT commit as different user without email / or only email

The minimal required author format, as hinted to in this SO answer, is

Name <email>

In your case, this means you want to write

git commit --author="Name <email>" -m "whatever"

Per Willem D'Haeseleer's comment, if you don't have an email address, you can use <>:

git commit --author="Name <>" -m "whatever"

As written on the git commit man page that you linked to, if you supply anything less than that, it's used as a search token to search through previous commits, looking for other commits by that author.

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

How to check Elasticsearch cluster health?

PROBLEM :-

Sometimes, Localhost may not get resolved. So it tends to return an output as seen below :

# curl -XGET localhost:9200/_cluster/health?pretty

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cluster/health?">http://localhost:9200/_cluster/health?</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>

<p>The system returned: <i>(111) Connection refused</i></p>

<p>The remote host or network may be down.  Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&amp;body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A07%3A36%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cluster%2Fhealth%3Fpretty%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>

<br>   
<hr> 
<div id="footer">Generated Mon, 17 Dec 2018 08:07:36 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>

# curl -XGET localhost:9200/_cat/indices

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cat/indices">http://localhost:9200/_cat/indices</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>

<p>The system returned: <i>(111) Connection refused</i></p>

<p>The remote host or network may be down.  Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&amp;body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A10%3A09%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cat%2Findices%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>

<br>   
<hr> 
<div id="footer">Generated Mon, 17 Dec 2018 08:10:09 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>

SOLUTION :-

Guess, this error is most probably returned by Local Squid deployed in the server.

So, it worked fine and good after replacing localhost by the local_ip in which the ElasticSearch has been deployed.

How to scanf only integer and repeat reading if the user enters non-numeric characters?

You could create a function that reads an integer between 1 and 23 or returns 0 if non-int

e.g.

int getInt()
{
  int n = 0;
  char buffer[128];
  fgets(buffer,sizeof(buffer),stdin);
  n = atoi(buffer); 
  return ( n > 23 || n < 1 ) ? 0 : n;
}

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

How to hash a password

UPDATE: THIS ANSWER IS SERIOUSLY OUTDATED. Please use the recommendations from the https://stackoverflow.com/a/10402129/251311 instead.

You can either use

var md5 = new MD5CryptoServiceProvider();
var md5data = md5.ComputeHash(data);

or

var sha1 = new SHA1CryptoServiceProvider();
var sha1data = sha1.ComputeHash(data);

To get data as byte array you could use

var data = Encoding.ASCII.GetBytes(password);

and to get back string from md5data or sha1data

var hashedPassword = ASCIIEncoding.GetString(md5data);

What is the size limit of a post request?

It is up to the http server to decide if there is a limit. The product I work on allows the admin to configure the limit.

Binary Data in JSON String. Something better than Base64

Just to add another option that we low level dinosaur programmers use...

An old school method that's been around since three years after the dawn of time would be the Intel HEX format. It was established in 1973 and the UNIX epoch started on January 1, 1970.

  • Is it more efficient? No.
  • Is it a well established standard? Yes.
  • Is it human readable like JSON? Yes-ish and a lot more readable than most any binary solution.

The json would look like:

{
    "data": [
    ":10010000214601360121470136007EFE09D2190140",
    ":100110002146017E17C20001FF5F16002148011928",
    ":10012000194E79234623965778239EDA3F01B2CAA7",
    ":100130003F0156702B5E712B722B732146013421C7",
    ":00000001FF"
    ]
}

How to get full file path from file name?

private const string BulkSetPriceFile = "test.txt";
...
var fullname = Path.GetFullPath(BulkSetPriceFile);

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Display PNG image as response to jQuery AJAX request

Method 1

You should not make an ajax call, just put the src of the img element as the url of the image.

This would be useful if you use GET instead of POST

<script type="text/javascript" > 

  $(document).ready( function() { 
      $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
  } );

</script>

Method 2

If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

as example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />

To encode to base64:

Map implementation with duplicate keys

 1, Map<String, List<String>> map = new HashMap<>();

this verbose solution has multiple drawbacks and is prone to errors. It implies that we need to instantiate a Collection for every value, check for its presence before adding or removing a value, delete it manually when no values are left, etcetera.

2, org.apache.commons.collections4.MultiMap interface
3, com.google.common.collect.Multimap interface 

java-map-duplicate-keys

How to insert TIMESTAMP into my MySQL table?

The DEFAULT value of a column in MySql is used only if it isn't provided a value for that column. So if you

INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', '', '$comments')

You are not using the DEFAULT value for the column date, but you are providing an empty string, so you get an error, because you can't store an empty string in a DATETIME column. The same thing apply if you use NULL, because again NULL is a value. However, if you remove the column from the list of the column you are inserting, MySql will use the DEFAULT value specified for that column (or the data type default one)

How to move div vertically down using CSS

if div.title is a div then put this:

left: 0;
bottom: 0;

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

Select distinct values from a list using LINQ in C#

Try,

var newList = 
(
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}
).Distinct();

Matlab: Running an m-file from command-line

A command like this runs the m-file successfully:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m'); exit;"

How to sort a list of lists by a specific index of the inner list?

Like this:

import operator
l = [...]
sorted_list = sorted(l, key=operator.itemgetter(desired_item_index))

Error: Argument is not a function, got undefined

If you are in a submodule, don't forget to declare the module in main app. ie :

<scrip>
angular.module('mainApp', ['subModule1', 'subModule2']);

angular.module('subModule1')
   .controller('MyController', ['$scope', function($scope) {
      $scope.moduleName = 'subModule1';
   }]);
</script>
...
<div ng-app="mainApp">
   <div ng-controller="MyController">
   <span ng-bind="moduleName"></span>
</div>

If you don't declare subModule1 in mainApp, you will got a "[ng:areq] Argument "MyController" is not a function, got undefined.

How can I get the executing assembly version?

I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.

Sourced from a combination of places:

https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx

React Checkbox not sending onChange

It's better not to use refs in such cases. Use:

<input
    type="checkbox"
    checked={this.state.active}
    onClick={this.handleClick}
/>

There are some options:

checked vs defaultChecked

The former would respond to both state changes and clicks. The latter would ignore state changes.

onClick vs onChange

The former would always trigger on clicks. The latter would not trigger on clicks if checked attribute is present on input element.

How do I count cells that are between two numbers in Excel?

Example-

For cells containing the values between 21-31, the formula is:

=COUNTIF(M$7:M$83,">21")-COUNTIF(M$7:M$83,">31")

Git: can't undo local changes (error: path ... is unmerged)

This worked perfectly for me:

$ git reset -- foo/bar.txt
$ git checkout foo/bar.txt

Java ByteBuffer to String

private String convertFrom(String lines, String from, String to) {
    ByteBuffer bb = ByteBuffer.wrap(lines.getBytes());
    CharBuffer cb = Charset.forName(to).decode(bb);
    return new String(Charset.forName(from).encode(cb).array());
};
public Doit(){
    String concatenatedLines = convertFrom(concatenatedLines, "CP1252", "UTF-8");
};

Using <style> tags in the <body> with other HTML

Not valid HTML, anyway pretty much every browser seems to consider just the second instance.

Tested under the last versions of FF and Google Chrome under Fedora, and FF, Opera, IE, and Chrome under XP.

Automated Python to Java translation

It may not be an easy problem. Determining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding).

fe_sendauth: no password supplied

I just put --password flag into my command and after hitting Enter it asked me for password, which I supplied.

Load a WPF BitmapImage from a System.Drawing.Bitmap

The easiest thing is if you can make the WPF bitmap from a file directly.

Otherwise you will have to use System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap.

How to display default text "--Select Team --" in combo box on pageload in WPF?

Only set the IsEditable attribute to true

<ComboBox Name="comboBox1"            
          Text="--Select Team--"
          IsEditable="true"  <---- that's all!
          IsReadOnly="true"/>

How should I have explained the difference between an Interface and an Abstract class?

Nothing is perfect in this world. They may have been expecting more of a practical approach.

But after your explanation you could add these lines with a slightly different approach.

  1. Interfaces are rules (rules because you must give an implementation to them that you can't ignore or avoid, so that they are imposed like rules) which works as a common understanding document among various teams in software development.

  2. Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules (means given signature of methods).

  3. Abstract classes may contain abstract declarations, concrete implementations, or both.

  4. Abstract declarations are like rules to be followed and concrete implementations are like guidelines (you can use it as it is or you can ignore it by overriding and giving your own implementation to it).

  5. Moreover which methods with same signature may change the behaviour in different context are provided as interface declarations as rules to implement accordingly in different contexts.

Edit: Java 8 facilitates to define default and static methods in interface.

public interface SomeInterfaceOne {

    void usualAbstractMethod(String inputString);

    default void defaultMethod(String inputString){
        System.out.println("Inside SomeInterfaceOne defaultMethod::"+inputString);
    }
}

Now when a class will implement SomeInterface, it is not mandatory to provide implementation for default methods of interface.

If we have another interface with following methods:

public interface SomeInterfaceTwo {

    void usualAbstractMethod(String inputString);

    default void defaultMethod(String inputString){
        System.out.println("Inside SomeInterfaceTwo defaultMethod::"+inputString);
    }

}

Java doesn’t allow extending multiple classes because it results in the “Diamond Problem” where compiler is not able to decide which superclass method to use. With the default methods, the diamond problem will arise for interfaces too. Because if a class is implementing both

SomeInterfaceOne and SomeInterfaceTwo

and doesn’t implement the common default method, compiler can’t decide which one to chose. To avoid this problem, in java 8 it is mandatory to implement common default methods of different interfaces. If any class is implementing both the above interfaces, it has to provide implementation for defaultMethod() method otherwise compiler will throw compile time error.

WCF named pipe minimal example

I just found this excellent little tutorial. broken link (Cached version)

I also followed Microsoft's tutorial which is nice, but I only needed pipes as well.

As you can see, you don't need configuration files and all that messy stuff.

By the way, he uses both HTTP and pipes. Just remove all code lines related to HTTP, and you'll get a pure pipe example.

How to check if a symlink exists

If you are testing for file existence you want -e not -L. -L tests for a symlink.

How to check if all inputs are not empty with jQuery

var isValid = true;
$("#tabledata").find("#tablebody").find("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
}
else{
isValid = true;
}
}); 
console.log(isValid);

Android Text over image

There are many ways. You use RelativeLayout or AbsoluteLayout.

With relative, you can have the image align with parent on the left side for example and also have the text align to the parent left too... then you can use margins and padding and gravity on the text view to get it lined where you want over the image.

Getting the difference between two sets

If you use Guava (former Google Collections) library there is a solution:

SetView<Number> difference = com.google.common.collect.Sets.difference(test2, test1);

The returned SetView is a Set, it is a live representation you can either make immutable or copy to another set. test1 and test2 are left intact.

Angular - How to apply [ngStyle] conditions

<ion-col size="12">
  <ion-card class="box-shadow ion-text-center background-size"
  *ngIf="data != null"
  [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">

  </ion-card>

When to use IList and when to use List

There's an important thing that people always seem to overlook:

You can pass a plain array to something which accepts an IList<T> parameter, and then you can call IList.Add() and will receive a runtime exception:

Unhandled Exception: System.NotSupportedException: Collection was of a fixed size.

For example, consider the following code:

private void test(IList<int> list)
{
    list.Add(1);
}

If you call that as follows, you will get a runtime exception:

int[] array = new int[0];
test(array);

This happens because using plain arrays with IList<T> violates the Liskov substitution principle.

For this reason, if you are calling IList<T>.Add() you may want to consider requiring a List<T> instead of an IList<T>.

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

A quick workaround for this is to use numpy.core.defchararray. I also faced the same warning message and was able to resolve it using above module.

import numpy.core.defchararray as npd
resultdataset = npd.equal(dataset1, dataset2)

ADB Driver and Windows 8.1

I had the following problem:
I had a Android phone without drivers, and it could not be recognized by the Windows 8.1. Neither as phone, neither as USB storage device.

I searched Device manager.
I opened Device manager, I right click on Android Phone->Android Composite Interface.
I selected "Update Driver Software"
I choose "Browse My Computer for Driver Software"
Then I choose "Let me pick from a list of devices"
I selected "USB Composite Device"

A new USB device is added to the list, and I can connect to my phone using adb and Android SDK.

Also I can use the phone as storage device.
Good luck

CSS display:table-row does not expand when width is set to 100%

You can nest table-cell directly within table. You muslt have a table. Starting eith table-row does not work. Try it with this HTML:

<html>
  <head>
    <style type="text/css">
.table {
  display: table;
  width: 100%;
}
.tr {
  display: table-row;
  width: 100%;
}
.td {
  display: table-cell;
}
    </style>
  </head>
  <body>

    <div class="table">
      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>
    </div>

      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>

    <div class="table">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
    </div>

  </body>
</html>

How can I drop a table if there is a foreign key constraint in SQL Server?

Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;

MySQL – Temporarily disable Foreign Key Checks or Constraints

Merge unequal dataframes and replace missing rows with 0

Take a look at the help page for merge. The all parameter lets you specify different types of merges. Here we want to set all = TRUE. This will make merge return NA for the values that don't match, which we can update to 0 with is.na():

zz <- merge(df1, df2, all = TRUE)
zz[is.na(zz)] <- 0

> zz
  x y
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0

Updated many years later to address follow up question

You need to identify the variable names in the second data table that you aren't merging on - I use setdiff() for this. Check out the following:

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e', NA))
df2 = data.frame(x=c('a', 'b', 'c'),y1 = c(0,1,0), y2 = c(0,1,0))

#merge as before
df3 <- merge(df1, df2, all = TRUE)
#columns in df2 not in df1
unique_df2_names <- setdiff(names(df2), names(df1))
df3[unique_df2_names][is.na(df3[, unique_df2_names])] <- 0 

Created on 2019-01-03 by the reprex package (v0.2.1)

How can I find out if an .EXE has Command-Line Options?

The easiest way would be to use use ProcessExplorer but it would still require some searching.

Make sure your exe is running and open ProcessExplorer. In ProcessExplorer find the name of your binary file and double click it to show properties. Click the Strings tab. Search down the list of string found in the binary file. Most strings will be garbage so they can be ignored. Search for anything that might possibly resemble a command line switch. Test this switch from the command line and see if it does anything.

Note that it might be your binary simply has no command line switches.

For reference here is the above steps applied to the Chrome executable. The command line switches accepted by Chrome can be seen in the list:

Process explorer analyzing Chrome.exe

Jackson with JSON: Unrecognized field, not marked as ignorable

You can use

ObjectMapper objectMapper = getObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

It will ignore all the properties that are not declared.

How to use count and group by at the same select statement

Ten non-deleted answers; most do not do what the user asked for. Most Answers mis-read the question as thinking that there are 58 users in each town instead of 58 in total. Even the few that are correct are not optimal.

mysql> flush status;
Query OK, 0 rows affected (0.00 sec)

SELECT  province, total_cities
    FROM       ( SELECT  DISTINCT province  FROM  canada ) AS provinces
    CROSS JOIN ( SELECT  COUNT(*) total_cities  FROM  canada ) AS tot;
+---------------------------+--------------+
| province                  | total_cities |
+---------------------------+--------------+
| Alberta                   |         5484 |
| British Columbia          |         5484 |
| Manitoba                  |         5484 |
| New Brunswick             |         5484 |
| Newfoundland and Labrador |         5484 |
| Northwest Territories     |         5484 |
| Nova Scotia               |         5484 |
| Nunavut                   |         5484 |
| Ontario                   |         5484 |
| Prince Edward Island      |         5484 |
| Quebec                    |         5484 |
| Saskatchewan              |         5484 |
| Yukon                     |         5484 |
+---------------------------+--------------+
13 rows in set (0.01 sec)

SHOW session status LIKE 'Handler%';

+----------------------------+-------+
| Variable_name              | Value |
+----------------------------+-------+
| Handler_commit             | 1     |
| Handler_delete             | 0     |
| Handler_discover           | 0     |
| Handler_external_lock      | 4     |
| Handler_mrr_init           | 0     |
| Handler_prepare            | 0     |
| Handler_read_first         | 3     |
| Handler_read_key           | 16    |
| Handler_read_last          | 1     |
| Handler_read_next          | 5484  |  -- One table scan to get COUNT(*)
| Handler_read_prev          | 0     |
| Handler_read_rnd           | 0     |
| Handler_read_rnd_next      | 15    |
| Handler_rollback           | 0     |
| Handler_savepoint          | 0     |
| Handler_savepoint_rollback | 0     |
| Handler_update             | 0     |
| Handler_write              | 14    |  -- leapfrog through index to find provinces  
+----------------------------+-------+

In the OP's context:

SELECT  town, total_users
    FROM       ( SELECT  DISTINCT town  FROM  canada ) AS towns
    CROSS JOIN ( SELECT  COUNT(*) total_users  FROM  canada ) AS tot;

Since there is only one row from tot, the CROSS JOIN is not as voluminous as it might otherwise be.

The usual pattern is COUNT(*) instead of COUNT(town). The latter implies checking town for being not null, which is unnecessary in this context.

Vue is not defined

jsBin demo

  1. You missed the order, first goes:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script>

and then:

<script>
    var demo = new Vue({
        el: '#demo',
        data: {
            message: 'Hello Vue.js!'
        }
    });
</script>
  1. And type="JavaScript" should be type="text/javascript" (or rather nothing at all)

Prevent a webpage from navigating away using JavaScript

If you are catching a browser back/forward button and don't want to navigate away, you can use:

window.addEventListener('popstate', function() {
    if (window.location.origin !== 'http://example.com') {
        // Do something if not your domain
    } else if (window.location.href === 'http://example.com/sign-in/step-1') {
        window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
    } else if (window.location.href === 'http://example.com/sign-in/step-2') {
        window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
    } else {
        // Let it do its thing
    }
});

Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.

JavaScript closure inside loops – simple practical example

This question really shows the history of JavaScript! Now we can avoid block scoping with arrow functions and handle loops directly from DOM nodes using Object methods.

_x000D_
_x000D_
const funcs = [1, 2, 3].map(i => () => console.log(i));_x000D_
funcs.map(fn => fn())
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
const buttons = document.getElementsByTagName("button");_x000D_
Object_x000D_
  .keys(buttons)_x000D_
  .map(i => buttons[i].addEventListener('click', () => console.log(i)));
_x000D_
<button>0</button><br>_x000D_
<button>1</button><br>_x000D_
<button>2</button>
_x000D_
_x000D_
_x000D_

Reading a JSP variable from JavaScript

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

How do you UDP multicast in Python?

To make the client code (from tolomea) work on Solaris you need to pass the ttl value for the IP_MULTICAST_TTL socket option as an unsigned char. Otherwise you will get an error. This worked for me on Solaris 10 and 11:

import socket
import struct

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
ttl = struct.pack('B', 2)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))

Get the Last Inserted Id Using Laravel Eloquent

You can use $this constructor variable to achieve "Last Inserted Id Using Laravel Eloquent" (without adding any extra column) in current function or controller.

public function store(Request $request){
    $request->validate([
        'title' => 'required|max:255',
        'desc' => 'required|max:5000'
    ]);

    $this->project = Project::create([
        'name' => $request->title,
        'description' => $request->desc,
    ]);

    dd($this->project->id);  //This is your current/latest project id
    $request->session()->flash('project_added','Project added successfully.');
    return redirect()->back();

}

Reset C int array to zero : the fastest way?

This question, although rather old, needs some benchmarks, as it asks for not the most idiomatic way, or the way that can be written in the fewest number of lines, but the fastest way. And it is silly to answer that question without some actual testing. So I compared four solutions, memset vs. std::fill vs. ZERO of AnT's answer vs a solution I made using AVX intrinsics.

Note that this solution is not generic, it only works on data of 32 or 64 bits. Please comment if this code is doing something incorrect.

#include<immintrin.h>
#define intrin_ZERO(a,n){\
size_t x = 0;\
const size_t inc = 32 / sizeof(*(a));/*size of 256 bit register over size of variable*/\
for (;x < n-inc;x+=inc)\
    _mm256_storeu_ps((float *)((a)+x),_mm256_setzero_ps());\
if(4 == sizeof(*(a))){\
    switch(n-x){\
    case 3:\
        (a)[x] = 0;x++;\
    case 2:\
        _mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
    case 1:\
        (a)[x] = 0;\
        break;\
    case 0:\
        break;\
    };\
}\
else if(8 == sizeof(*(a))){\
switch(n-x){\
    case 7:\
        (a)[x] = 0;x++;\
    case 6:\
        (a)[x] = 0;x++;\
    case 5:\
        (a)[x] = 0;x++;\
    case 4:\
        _mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
    case 3:\
        (a)[x] = 0;x++;\
    case 2:\
        ((long long *)(a))[x] = 0;break;\
    case 1:\
        (a)[x] = 0;\
        break;\
    case 0:\
        break;\
};\
}\
}

I will not claim that this is the fastest method, since I am not a low level optimization expert. Rather it is an example of a correct architecture dependent implementation that is faster than memset.

Now, onto the results. I calculated performance for size 100 int and long long arrays, both statically and dynamically allocated, but with the exception of msvc, which did a dead code elimination on static arrays, the results were extremely comparable, so I will show only dynamic array performance. Time markings are ms for 1 million iterations, using time.h's low precision clock function.

clang 3.8 (Using the clang-cl frontend, optimization flags= /OX /arch:AVX /Oi /Ot)

int:
memset:      99
fill:        97
ZERO:        98
intrin_ZERO: 90

long long:
memset:      285
fill:        286
ZERO:        285
intrin_ZERO: 188

gcc 5.1.0 (optimization flags: -O3 -march=native -mtune=native -mavx):

int:
memset:      268
fill:        268
ZERO:        268
intrin_ZERO: 91
long long:
memset:      402
fill:        399
ZERO:        400
intrin_ZERO: 185

msvc 2015 (optimization flags: /OX /arch:AVX /Oi /Ot):

int
memset:      196
fill:        613
ZERO:        221
intrin_ZERO: 95
long long:
memset:      273
fill:        559
ZERO:        376
intrin_ZERO: 188

There is a lot interesting going on here: llvm killing gcc, MSVC's typical spotty optimizations (it does an impressive dead code elimination on static arrays and then has awful performance for fill). Although my implementation is significantly faster, this may only be because it recognizes that bit clearing has much less overhead than any other setting operation.

Clang's implementation merits more looking at, as it is significantly faster. Some additional testing shows that its memset is in fact specialized for zero--non zero memsets for 400 byte array are much slower (~220ms) and are comparable to gcc's. However, the nonzero memsetting with an 800 byte array makes no speed difference, which is probably why in that case, their memset has worse performance than my implementation--the specialization is only for small arrays, and the cuttoff is right around 800 bytes. Also note that gcc 'fill' and 'ZERO' are not optimizing to memset (looking at generated code), gcc is simply generating code with identical performance characteristics.

Conclusion: memset is not really optimized for this task as well as people would pretend it is (otherwise gcc and msvc and llvm's memset would have the same performance). If performance matters then memset should not be a final solution, especially for these awkward medium sized arrays, because it is not specialized for bit clearing, and it is not hand optimized any better than the compiler can do on its own.

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

We've solved this by replacing some nasty code in our base html file.

Before:

 meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1"

After:

And the solution came by replacing it with this magical line:

 meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"

Mockito How to mock and assert a thrown exception?

If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito:

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void testExceptionMessage() throws Exception {
    expectedException.expect(AnyException.class);
    expectedException.expectMessage("The expected message");

    given(foo.bar()).willThrow(new AnyException("The expected message"));
}

how to determine size of tablespace oracle 11g

One of the way is Using below sql queries

--Size of All Table Space

--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM   USER_FREE_SPACE GROUP BY TABLESPACE_NAME

--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)",  FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM  USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);

How can I count the number of elements with same class?

With jQuery you can use

$('#main-div .specific-class').length

otherwise in VanillaJS (from IE8 included) you may use

document.querySelectorAll('#main-div .specific-class').length;

How to add icons to React Native app

You can import react-native-elements and use the font-awesome icons to your react native app

Install

npm install --save react-native-elements

then import that where you want to use icons

import { Icon } from 'react-native-elements'

Use it like

render() {
   return(
    <Icon
      reverse
      name='ios-american-football'
      type='ionicon'
      color='#517fa4'
    />
 );
}

iPhone 6 and 6 Plus Media Queries

For iPhone 5,

@media screen and (device-aspect-ratio: 40/71)

for iPhone 6,7,8

@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : portrait)

for iPhone 6+,7+,8+

@media screen and (-webkit-device-pixel-ratio: 3) and (min-device-width: 414px)

Working fine for me as of now.

Jquery Value match Regex

Change it to this:

var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

This is a regular expression literal that is passed the i flag which means to be case insensitive.

Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.

Match groups in Python

You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:

import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)


for statement in ("I love Mary", 
                  "Ich liebe Margot", 
                  "Je t'aime Marie", 
                  "Te amo Maria"):

    m = REMatcher(statement)

    if m.match(r"I love (\w+)"): 
        print "He loves",m.group(1) 

    elif m.match(r"Ich liebe (\w+)"):
        print "Er liebt",m.group(1) 

    elif m.match(r"Je t'aime (\w+)"):
        print "Il aime",m.group(1) 

    else: 
        print "???"

Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:

import re

for statement in ("I love Mary",
                  "Ich liebe Margot",
                  "Je t'aime Marie",
                  "Te amo Maria"):

    if m := re.match(r"I love (\w+)", statement):
        print("He loves", m.group(1))

    elif m := re.match(r"Ich liebe (\w+)", statement):
        print("Er liebt", m.group(1))

    elif m := re.match(r"Je t'aime (\w+)", statement):
        print("Il aime", m.group(1))

    else:
        print()

Bootstrap Align Image with text

You have two choices, either correct your markup so that it uses correct elements and utilizes the Bootstrap grid system:

_x000D_
_x000D_
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
     <h1>About Me</h1>_x000D_
    <div class="row">_x000D_
        <div class="col-md-4">_x000D_
            <div class="imgAbt">_x000D_
                <img width="220" height="220" src="img/me.jpg" />_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-md-8">_x000D_
            <p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or, if you wish the text to closely wrap the image, change your markup to:

_x000D_
_x000D_
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
    <h1>About Me</h1>_x000D_
    <div class="row">_x000D_
        <div class="col-md-12">_x000D_
            <img style='float:left;width:200px;height:200px; margin-right:10px;' src="img/me.jpg" />_x000D_
            <p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
        </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How to easily map c++ enums to strings

I have spent more time researching this topic that I'd like to admit. Luckily there are great open source solutions in the wild.

These are two great approaches, even if not well known enough (yet),

wise_enum

  • Standalone smart enum library for C++11/14/17. It supports all of the standard functionality that you would expect from a smart enum class in C++.
  • Limitations: requires at least C++11.

Better Enums

  • Reflective compile-time enum library with clean syntax, in a single header file, and without dependencies.
  • Limitations: based on macros, can't be used inside a class.

How do I use valgrind to find memory leaks?

How to Run Valgrind

Not to insult the OP, but for those who come to this question and are still new to Linux—you might have to install Valgrind on your system.

sudo apt install valgrind  # Ubuntu, Debian, etc.
sudo yum install valgrind  # RHEL, CentOS, Fedora, etc.

Valgrind is readily usable for C/C++ code, but can even be used for other languages when configured properly (see this for Python).

To run Valgrind, pass the executable as an argument (along with any parameters to the program).

valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1

The flags are, in short:

  • --leak-check=full: "each individual leak will be shown in detail"
  • --show-leak-kinds=all: Show all of "definite, indirect, possible, reachable" leak kinds in the "full" report.
  • --track-origins=yes: Favor useful output over speed. This tracks the origins of uninitialized values, which could be very useful for memory errors. Consider turning off if Valgrind is unacceptably slow.
  • --verbose: Can tell you about unusual behavior of your program. Repeat for more verbosity.
  • --log-file: Write to a file. Useful when output exceeds terminal space.

Finally, you would like to see a Valgrind report that looks like this:

HEAP SUMMARY:
    in use at exit: 0 bytes in 0 blocks
  total heap usage: 636 allocs, 636 frees, 25,393 bytes allocated

All heap blocks were freed -- no leaks are possible

ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I have a leak, but WHERE?

So, you have a memory leak, and Valgrind isn't saying anything meaningful. Perhaps, something like this:

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (in /home/Peri461/Documents/executable)

Let's take a look at the C code I wrote too:

#include <stdlib.h>

int main() {
    char* string = malloc(5 * sizeof(char)); //LEAK: not freed!
    return 0;
}

Well, there were 5 bytes lost. How did it happen? The error report just says main and malloc. In a larger program, that would be seriously troublesome to hunt down. This is because of how the executable was compiled. We can actually get line-by-line details on what went wrong. Recompile your program with a debug flag (I'm using gcc here):

gcc -o executable -std=c11 -Wall main.c         # suppose it was this at first
gcc -o executable -std=c11 -Wall -ggdb3 main.c  # add -ggdb3 to it

Now with this debug build, Valgrind points to the exact line of code allocating the memory that got leaked! (The wording is important: it might not be exactly where your leak is, but what got leaked. The trace helps you find where.)

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (main.c:4)

Techniques for Debugging Memory Leaks & Errors

  • Make use of www.cplusplus.com! It has great documentation on C/C++ functions.
  • General advice for memory leaks:
    • Make sure your dynamically allocated memory does in fact get freed.
    • Don't allocate memory and forget to assign the pointer.
    • Don't overwrite a pointer with a new one unless the old memory is freed.
  • General advice for memory errors:
    • Access and write to addresses and indices you're sure belong to you. Memory errors are different from leaks; they're often just IndexOutOfBoundsException type problems.
    • Don't access or write to memory after freeing it.
  • Sometimes your leaks/errors can be linked to one another, much like an IDE discovering that you haven't typed a closing bracket yet. Resolving one issue can resolve others, so look for one that looks a good culprit and apply some of these ideas:

    • List out the functions in your code that depend on/are dependent on the "offending" code that has the memory error. Follow the program's execution (maybe even in gdb perhaps), and look for precondition/postcondition errors. The idea is to trace your program's execution while focusing on the lifetime of allocated memory.
    • Try commenting out the "offending" block of code (within reason, so your code still compiles). If the Valgrind error goes away, you've found where it is.
  • If all else fails, try looking it up. Valgrind has documentation too!

A Look at Common Leaks and Errors

Watch your pointers

60 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C2BB78: realloc (vg_replace_malloc.c:785)
   by 0x4005E4: resizeArray (main.c:12)
   by 0x40062E: main (main.c:19)

And the code:

#include <stdlib.h>
#include <stdint.h>

struct _List {
    int32_t* data;
    int32_t length;
};
typedef struct _List List;

List* resizeArray(List* array) {
    int32_t* dPtr = array->data;
    dPtr = realloc(dPtr, 15 * sizeof(int32_t)); //doesn't update array->data
    return array;
}

int main() {
    List* array = calloc(1, sizeof(List));
    array->data = calloc(10, sizeof(int32_t));
    array = resizeArray(array);

    free(array->data);
    free(array);
    return 0;
}

As a teaching assistant, I've seen this mistake often. The student makes use of a local variable and forgets to update the original pointer. The error here is noticing that realloc can actually move the allocated memory somewhere else and change the pointer's location. We then leave resizeArray without telling array->data where the array was moved to.

Invalid write

1 errors in context 1 of 1:
Invalid write of size 1
   at 0x4005CA: main (main.c:10)
 Address 0x51f905a is 0 bytes after a block of size 26 alloc'd
   at 0x4C2B975: calloc (vg_replace_malloc.c:711)
   by 0x400593: main (main.c:5)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* alphabet = calloc(26, sizeof(char));

    for(uint8_t i = 0; i < 26; i++) {
        *(alphabet + i) = 'A' + i;
    }
    *(alphabet + 26) = '\0'; //null-terminate the string?

    free(alphabet);
    return 0;
}

Notice that Valgrind points us to the commented line of code above. The array of size 26 is indexed [0,25] which is why *(alphabet + 26) is an invalid write—it's out of bounds. An invalid write is a common result of off-by-one errors. Look at the left side of your assignment operation.

Invalid read

1 errors in context 1 of 1:
Invalid read of size 1
   at 0x400602: main (main.c:9)
 Address 0x51f90ba is 0 bytes after a block of size 26 alloc'd
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x4005E1: main (main.c:6)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* destination = calloc(27, sizeof(char));
    char* source = malloc(26 * sizeof(char));

    for(uint8_t i = 0; i < 27; i++) {
        *(destination + i) = *(source + i); //Look at the last iteration.
    }

    free(destination);
    free(source);
    return 0;
}

Valgrind points us to the commented line above. Look at the last iteration here, which is
*(destination + 26) = *(source + 26);. However, *(source + 26) is out of bounds again, similarly to the invalid write. Invalid reads are also a common result of off-by-one errors. Look at the right side of your assignment operation.


The Open Source (U/Dys)topia

How do I know when the leak is mine? How do I find my leak when I'm using someone else's code? I found a leak that isn't mine; should I do something? All are legitimate questions. First, 2 real-world examples that show 2 classes of common encounters.

Jansson: a JSON library

#include <jansson.h>
#include <stdio.h>

int main() {
    char* string = "{ \"key\": \"value\" }";

    json_error_t error;
    json_t* root = json_loads(string, 0, &error); //obtaining a pointer
    json_t* value = json_object_get(root, "key"); //obtaining a pointer
    printf("\"%s\" is the value field.\n", json_string_value(value)); //use value

    json_decref(value); //Do I free this pointer?
    json_decref(root);  //What about this one? Does the order matter?
    return 0;
}

This is a simple program: it reads a JSON string and parses it. In the making, we use library calls to do the parsing for us. Jansson makes the necessary allocations dynamically since JSON can contain nested structures of itself. However, this doesn't mean we decref or "free" the memory given to us from every function. In fact, this code I wrote above throws both an "Invalid read" and an "Invalid write". Those errors go away when you take out the decref line for value.

Why? The variable value is considered a "borrowed reference" in the Jansson API. Jansson keeps track of its memory for you, and you simply have to decref JSON structures independent of each other. The lesson here: read the documentation. Really. It's sometimes hard to understand, but they're telling you why these things happen. Instead, we have existing questions about this memory error.

SDL: a graphics and gaming library

#include "SDL2/SDL.h"

int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }

    SDL_Quit();
    return 0;
}

What's wrong with this code? It consistently leaks ~212 KiB of memory for me. Take a moment to think about it. We turn SDL on and then off. Answer? There is nothing wrong.

That might sound bizarre at first. Truth be told, graphics are messy and sometimes you have to accept some leaks as being part of the standard library. The lesson here: you need not quell every memory leak. Sometimes you just need to suppress the leaks because they're known issues you can't do anything about. (This is not my permission to ignore your own leaks!)

Answers unto the void

How do I know when the leak is mine?
It is. (99% sure, anyway)

How do I find my leak when I'm using someone else's code?
Chances are someone else already found it. Try Google! If that fails, use the skills I gave you above. If that fails and you mostly see API calls and little of your own stack trace, see the next question.

I found a leak that isn't mine; should I do something?
Yes! Most APIs have ways to report bugs and issues. Use them! Help give back to the tools you're using in your project!


Further Reading

Thanks for staying with me this long. I hope you've learned something, as I tried to tend to the broad spectrum of people arriving at this answer. Some things I hope you've asked along the way: How does C's memory allocator work? What actually is a memory leak and a memory error? How are they different from segfaults? How does Valgrind work? If you had any of these, please do feed your curiousity:

Upload artifacts to Nexus, without Maven

If you need a convenient command line interface or python API, look at repositorytools

Using it, you can upload artifact to nexus with command

artifact upload foo-1.2.3.ext releases com.fooware

To make it work, you will also need to set some environment variables

export REPOSITORY_URL=https://repo.example.com
export REPOSITORY_USER=admin
export REPOSITORY_PASSWORD=mysecretpassword

Why do python lists have pop() but not push()

Probably because the original version of Python (CPython) was written in C, not C++.

The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.

Importing images from a directory (Python) to list or dictionary

from PIL import Image
import os, os.path

imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
    ext = os.path.splitext(f)[1]
    if ext.lower() not in valid_images:
        continue
    imgs.append(Image.open(os.path.join(path,f)))