Programs & Examples On #Struct.pack

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

Convert list of ASCII codes to string (byte array) in Python

For Python 2.6 and later if you are dealing with bytes then a bytearray is the most obvious choice:

>>> str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))
'\x11\x18y\x01\x0c\xde"L'

To me this is even more direct than Alex Martelli's answer - still no string manipulation or len call but now you don't even need to import anything!

How to convert an int to a hex string?

This worked best for me

"0x%02X" % 5  # => 0x05
"0x%02X" % 17 # => 0x11

Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011

Is JavaScript guaranteed to be single-threaded?

Yes, although Internet Explorer 9 will compile your Javascript on a separate thread in preparation for execution on the main thread. This doesn't change anything for you as a programmer, though.

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

Generate a range of dates using SQL

 SELECT (sysdate-365 + (LEVEL -1)) AS DATES
 FROM DUAL connect by level <=( sysdate-(sysdate-365))

if a 'from' and a 'to' date is replaced in place of sysdate and sysdate-365, the output will be a range of dates between the from and to date.

SQL Query to add a new column after an existing column in SQL Server 2005

ALTER won't do it because column order does not matter for storage or querying

If SQL Server, you'd have to use the SSMS Table Designer to arrange your columns, which can then generate a script which drops and recreates the table

Edit Jun 2013

Cross link to my answer here: Performance / Space implications when ordering SQL Server columns?

Styles.Render in MVC4

As defined in App_start.BundleConfig, it's just calling

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

Nothing happens even if you remove that section.

How to detect if URL has changed after hash in JavaScript

Look at the jQuery unload function. It handles all the things.

https://api.jquery.com/unload/

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

$(window).unload(
    function(event) {
        alert("navigating");
    }
);

Read file As String

public static String readFileToString(String filePath) {
    InputStream in = Test.class.getResourceAsStream(filePath);//filePath="/com/myproject/Sample.xml"
    try {
        return IOUtils.toString(in, StandardCharsets.UTF_8);
    } catch (IOException e) {
        logger.error("Failed to read the xml : ", e);
    }
    return null;
}

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

The following method may work:

git rebase HEAD master
git checkout master

This will rebase your current HEAD changes on top of the master. Then you can switch the branch.


Alternative way is to checkout the branch first:

git checkout master

Then Git should display SHA1 of your detached commits, then you can cherry pick them, e.g.

git cherry-pick YOURSHA1

Or you can also merge the latest one:

git merge YOURSHA1

To see all of your commits from different branches (to make sure you've them), run: git reflog.

How can I start PostgreSQL server on Mac OS X?

The cleanest way by far to start/stop/restart PostgreSQL if you have installed it through brew is to simply unload and/or load the launchd configuration file that comes with the installation:

launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

The first line will stop PostgreSQL and the second line will start it. There isn't any need to specify any data directories, etc. since everything is in that file.

How to convert any date format to yyyy-MM-dd

Convert your string to DateTime and then use DateTime.ToString("yyyy-MM-dd");

DateTime temp = DateTime.ParseExact(sourceDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = temp.ToString("yyyy-MM-dd");

Eclipse: Set maximum line length for auto formatting?

for XML line width, update preferences > XML > XML Files > Editor > Line width

Is there a simple way to delete a list element by value?

If your elements are distinct, then a simple set difference will do.

c = [1,2,3,4,'x',8,6,7,'x',9,'x']
z = list(set(c) - set(['x']))
print z
[1, 2, 3, 4, 6, 7, 8, 9]

How to diff a commit with its parent?

Use:

git diff 15dc8^!

as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):

Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."


Also, you can use git show COMMIT to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How to make a div with a circular shape?

Demo

css

div {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background: red;
}

html

<div></div>

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

Looks like a resources related error. I would start there.

I got this ("Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details") first time related to pictures. Resize solved it. Or another time just repaired the links to resources.

sqlite database default time value 'now'

It is syntax error because you did not write parenthesis

if you write

Select datetime('now') then it will give you utc time but if you this write it query then you must add parenthesis before this so (datetime('now')) for UTC Time. for local time same Select datetime('now','localtime') for query

(datetime('now','localtime'))

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

Moving uncommitted changes to a new branch

Just create a new branch:

git checkout -b newBranch

And if you do git status you'll see that the state of the code hasn't changed and you can commit it to the new branch.

Query to check index on a table

Created a stored procedure to list indexes for a table in database in SQL Server

create procedure _ListIndexes(@tableName nvarchar(200))
as
begin
/*
exec _ListIndexes '<YOUR TABLE NAME>'
*/
SELECT DB_NAME(DB_ID()) as DBName,SCH.name + '.' + TBL.name AS TableName,IDX.name as IndexName, IDX.type_desc AS IndexType,COL.Name as ColumnName,IC.*
    FROM sys.tables AS TBL 
         INNER JOIN sys.schemas AS SCH ON TBL.schema_id = SCH.schema_id 
         INNER JOIN sys.indexes AS IDX ON TBL.object_id = IDX.object_id 
         INNER JOIN sys.index_columns IC ON  IDX.object_id = IC.object_id and IDX.index_id = IC.index_id 
         INNER JOIN sys.columns COL ON ic.object_id = COL.object_id and IC.column_id = COL.column_id 
        where TBL.name = @tableName
    ORDER BY TableName,IDX.name

end

How do I find out my python path using python?

Works in windows 10, essentially identical to vanuan's answer, but cleaner (taken from somewhere, can't remember where..):

import sys
for p in sys.path:
    print(p)

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

I had a error when i was installing many plugins So the error 100 showed including the location of the last plugin that i installed C:\wamp\www\mysite\wp-content\plugins\"..." so i deleted this plugin folder on the C: drive then everything was back to normal.I think i have to limit the amount of plug-in i install or have activated .good luck i hope it helps

How to move a file?

os.rename(), shutil.move(), or os.replace()

All employ the same syntax:

import os
import shutil

os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

Note that you must include the file name (file.foo) in both the source and destination arguments. If it is changed, the file will be renamed as well as moved.

Note also that in the first two cases the directory in which the new file is being created must already exist. On Windows, a file with that name must not exist or an exception will be raised, but os.replace() will silently replace a file even in that occurrence.

As has been noted in comments on other answers, shutil.move simply calls os.rename in most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file.

jquery datatables default sort

Here is the actual code that does it...

$(document).ready(function()
{
  var oTable = $('#myTable').dataTable();

  // Sort immediately with column 2 (at position 1 in the array (base 0). More could be sorted with additional array elements
  oTable.fnSort( [ [1,'asc'] ] );

  // And to sort another column descending (at position 2 in the array (base 0).
  oTable.fnSort( [ [2,'desc'] ] );
} );

To not have the column highlighted, modify the CSS like so:

table.dataTable tr.odd td.sorting_1 { background-color: transparent; }
table.dataTable tr.even td.sorting_1 { background-color: transparent; }

How to work with complex numbers in C?

For convenience, one may include tgmath.h library for the type generate macros. It creates the same function name as the double version for all type of variable. For example, For example, it defines a sqrt() macro that expands to the sqrtf() , sqrt() , or sqrtl() function, depending on the type of argument provided.

So one don't need to remember the corresponding function name for different type of variables!

#include <stdio.h>
#include <tgmath.h>//for the type generate macros. 
#include <complex.h>//for easier declare complex variables and complex unit I

int main(void)
{
    double complex z1=1./4.*M_PI+1./4.*M_PI*I;//M_PI is just pi=3.1415...
    double complex z2, z3, z4, z5; 

    z2=exp(z1);
    z3=sin(z1);
    z4=sqrt(z1);
    z5=log(z1);

    printf("exp(z1)=%lf + %lf I\n", creal(z2),cimag(z2));
    printf("sin(z1)=%lf + %lf I\n", creal(z3),cimag(z3));
    printf("sqrt(z1)=%lf + %lf I\n", creal(z4),cimag(z4));
    printf("log(z1)=%lf + %lf I\n", creal(z5),cimag(z5));

    return 0;
}

What is "git remote add ..." and "git push origin master"?

Git remote add origin:

It centralises your source code to the other projects.It is developed based on Linux, complete open source and make your code useful to the other git users.we call it as reference

Pushes your code into git repository using remote url of the git hub.

window.location (JS) vs header() (PHP) for redirection

The result is same for all options. Redirect.

<meta> in HTML:

  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Don't need JavaScript enabled.
  • Don't need PHP.

window.location in JS:

  • Javascript enabled needed.
  • Don't need PHP.
  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Redirect can be dependent on any conditions if (1 === 1) { window.location.href = 'http://example.com'; }.

header('Location:') in PHP:

  • Don't need JavaScript enabled.
  • PHP needed.
  • Redirect will be executed first, user never see what is after. header() must be the first command in php script, before output any other. If you try output some before header, will receive an Warning: Cannot modify header information - headers already sent

Display number with leading zeros

Or another solution.

"{:0>2}".format(number)

__init__() got an unexpected keyword argument 'user'

LivingRoom.objects.create() calls LivingRoom.__init__() - as you might have noticed if you had read the traceback - passing it the same arguments. To make a long story short, a Django models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields. The correct way to provide default values for fields is in the field constructor using the default keyword as explained in the FineManual.

possible EventEmitter memory leak detected

Put this in the first line of your server.js (or whatever contains your main Node.js app):

require('events').EventEmitter.prototype._maxListeners = 0;

and the error goes away :)

Changing the image source using jQuery

Short but exact

$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );

_x000D_
_x000D_
let pic=[
  "https://picsum.photos/id/237/40/40", // arbitrary - eg: "img1_on.gif",
  "https://picsum.photos/id/238/40/40", // arbitrary - eg: "img2_on.gif"
];

$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>
_x000D_
_x000D_
_x000D_

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

How to set margin of ImageView using code, not xml

create layout dynamically and set its parameter as setmargin() will not work directly on an imageView

ImageView im;
im = (ImageView) findViewById(R.id.your_image_in_XML_by_id);
 RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(im.getLayoutParams());
                        layout.setMargins(counter*27, 0, 0, 0);//left,right,top,bottom
                        im.setLayoutParams(layout);
                        im.setImageResource(R.drawable.yourimage)

LINQ - Left Join, Group By, and Count

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.ParentId into grouped
select new { ParentId = grouped.Key, Count = grouped.Count(t=>t.ChildId != null) }

Getting the ID of the element that fired an event

Though it is mentioned in other posts, I wanted to spell this out:

$(event.target).id is undefined

$(event.target)[0].id gives the id attribute.

event.target.id also gives the id attribute.

this.id gives the id attribute.

and

$(this).id is undefined.

The differences, of course, is between jQuery objects and DOM objects. "id" is a DOM property so you have to be on the DOM element object to use it.

(It tripped me up, so it probably tripped up someone else)

Facebook OAuth "The domain of this URL isn't included in the app's domain"

This same Facebook error happened to me in the Production environment. The reason was I had 2 apps registered with Facebook (Local, Production) but I hardcoded the Local app ID into the source code and forgot to switch it out for the Production app ID before deployment.

Best practice dictates you shouldn't have the app ID hardcoded into the source code but if you do, do not mismatch your various Facebook app IDs like I mistakenly did.

select dept names who have more than 2 employees whose salary is greater than 1000

My main advice would be to steer clear of the HAVING clause (see below):

WITH HighEarners AS
     ( SELECT EmpId, DeptId
         FROM EMPLOYEE
        WHERE Salary > 1000 ), 
     DeptmentHighEarnerTallies AS 
     ( SELECT DeptId, COUNT(*) AS HighEarnerTally
         FROM HighEarners
        GROUP 
           BY DeptId )
SELECT DeptName
  FROM DEPARTMENT NATURAL JOIN DeptmentHighEarnerTallies
 WHERE HighEarnerTally > 2;

The very early SQL implementations lacked derived tables and HAVING was a workaround for one of its most obvious drawbacks (how to select on the result of a set function from the SELECT clause). Once derived tables had become a thing, the need for HAVING went away. Sadly, HAVING itself didn't go away (and never will) because nothing is ever removed from standard SQL. There is no need to learn HAVING and I encourage fledgling coders to avoid using this historical hangover.

Having services in React application

I am in the same boot like you. In the case you mention, I would implement the input validation UI component as a React component.

I agree the implementation of the validation logic itself should (must) not be coupled. Therefore I would put it into a separate JS module.

That is, for logic that should not be coupled use a JS module/class in separate file, and use require/import to de-couple the component from the "service".

This allows for dependency injection and unit testing of the two independently.

Changing background color of ListView items on Android

Following way very slowly in the running

mAgendaListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//view.setBackgroundColor(Color.RED);

for(int i=0; i<parent.getChildCount(); i++)
{
     if(i == position)
     {
               parent.getChildAt(i).setBackgroundColor(Color.BLUE);
     }
     else
     {
               parent.getChildAt(i).setBackgroundColor(Color.BLACK);
     }

 }

Replaced by the following

int pos = 0;
int save = -1;
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
            //Always set the item clicked blue background
            view.setBackgroundColor(Color.BLUE);

            if (pos == 0) {
                if (save != -1) {
                    parent.getChildAt(save).setBackgroundColor(Color.BLACK);
                }
                save = position;
                pos++;
                Log.d("Pos = 0", "Running");

            } else {
                parent.getChildAt(save).setBackgroundColor(Color.BLACK);
                save = position;
                pos = 0;
                Log.d("Pos # 0", "Running");
            }

Concatenate a vector of strings/character

Here is a little utility function that collapses a named or unnamed list of values to a single string for easier printing. It will also print the code line itself. It's from my list examples in R page.

Generate some lists named or unnamed:

# Define Lists
ls_num <- list(1,2,3)
ls_str <- list('1','2','3')
ls_num_str <- list(1,2,'3')

# Named Lists
ar_st_names <- c('e1','e2','e3')
ls_num_str_named <- ls_num_str
names(ls_num_str_named) <- ar_st_names

# Add Element to Named List
ls_num_str_named$e4 <- 'this is added'

Here is the a function that will convert named or unnamed list to string:

ffi_lst2str <- function(ls_list, st_desc, bl_print=TRUE) {

  # string desc
  if(missing(st_desc)){
    st_desc <- deparse(substitute(ls_list))
  }

  # create string
  st_string_from_list = paste0(paste0(st_desc, ':'), 
                               paste(names(ls_list), ls_list, sep="=", collapse=";" ))

  if (bl_print){
    print(st_string_from_list)
  }
}

Testing the function with the lists created prior:

> ffi_lst2str(ls_num)
[1] "ls_num:=1;=2;=3"
> ffi_lst2str(ls_str)
[1] "ls_str:=1;=2;=3"
> ffi_lst2str(ls_num_str)
[1] "ls_num_str:=1;=2;=3"
> ffi_lst2str(ls_num_str_named)
[1] "ls_num_str_named:e1=1;e2=2;e3=3;e4=this is added"

Testing the function with subset of list elements:

> ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
[1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"
> ffi_lst2str(ls_num[2:3])
[1] "ls_num[2:3]:=2;=3"
> ffi_lst2str(ls_str[2:3])
[1] "ls_str[2:3]:=2;=3"
> ffi_lst2str(ls_num_str[2:4])
[1] "ls_num_str[2:4]:=2;=3;=NULL"
> ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
[1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"

Custom Date Format for Bootstrap-DatePicker

var type={
      format:"DD, d MM, yy"
};
$('.classname').datepicker(type.format);

Deny all, allow only one IP through htaccess

I wasn't able to use the 403 method because I wanted the maintenance page and page images in a sub folder on my server, so used the following approach to redirect to a 'maintenance page' for everyone but a single IP*

RewriteEngine on
RewriteCond %{REMOTE_ADDR} !**.**.**.*
RewriteRule !^maintenance/ http://www.website.co.uk/maintenance/ [R=302,L]

Source: Creating a holding page to hide your WordPress blog

how to zip a folder itself using java

Java 6 +

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zip {

    private static final FileFilter FOLDER_FILTER = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    };

    private static final FileFilter FILE_FILTER = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isFile();
        }
    };


    private static void compress(File file, ZipOutputStream outputStream, String path) throws IOException {

        if (file.isDirectory()) {
            File[] subFiles = file.listFiles(FILE_FILTER);
            if (subFiles != null) {
                for (File subFile : subFiles) {
                    compress(subFile, outputStream, new File(path, subFile.getName()).getAbsolutePath());
                }
            }
            File[] subDirs = file.listFiles(FOLDER_FILTER);
            if (subDirs != null) {
                for (File subDir : subDirs) {
                    compress(subDir, outputStream, new File(path, subDir.getName()).getAbsolutePath());
                }
            }
        } else if (file.exists()) {
            outputStream.putNextEntry(new ZipEntry(path));
            FileInputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) >= 0) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.closeEntry();
        }
    }

    public static void compress(String dirPath, String zipFilePath) throws IOException {
        File file = new File(dirPath);
        final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFilePath));
        compress(file, outputStream, "/");
        outputStream.close();
    }

}

Triggering a checkbox value changed event in DataGridView

cellEndEditTimer.Start();

this line makes the datagridview update the list of checked boxes

Thank you.

Reload an iframe with jQuery

Reload an iframe with jQuery

make a link inside the iframe lets say with id = "reload" then use following code

$('#reload').click(function() {
    document.location.reload();
});

and you are good to go with all browsers.

Reload an iframe with HTML (no Java Script req.)

It have more simpler solution: which works without javaScript in (FF, Webkit)

just make an anchor inSide your iframe

   <a href="#" target="_SELF">Refresh Comments</a>

When you click this anchor it just refresh your iframe

But if you have parameter send to your iframe then do it as following.

  <a id="comnt-limit" href="?id=<?= $page_id?>" target="_SELF">Refresh Comments</a>

do not need any page url because -> target="_SELF" do it for you

HTML5 form validation pattern alphanumeric with spaces?

It's quite an old question, but in case it could be useful for anyone, starting from a combination of good responses found here, I've ended using this pattern:

pattern="([^\s][A-z0-9À-ž\s]+)"

It will require at least two characters, making sure it does not start with an empty space but allowing spaces between words, and also allowing special characters such as a, ó, ä, ö.

How can I run PowerShell with the .NET 4 runtime?

Just run powershell.exe with COMPLUS_version environment variable set to v4.0.30319. For example, from cmd.exe or .bat-file:

set COMPLUS_version=v4.0.30319
powershell -file c:\scripts\test.ps1

How to create an empty file with Ansible?

Changed if file not exists. Create empty file.

- name: create fake 'nologin' shell
  file:
    path: /etc/nologin
    state: touch
  register: p
  changed_when: p.diff.before.state == "absent"

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

I would try Scott's CLR function first but add a WHERE clause to reduce the number of records updated.

UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber) 
WHERE phonenumber like '%[^0-9]%'

If you know that the great majority of your records have non-numeric characters it might not help though.

C# List<> Sort by x then y

The trick is to implement a stable sort. I've created a Widget class that can contain your test data:

public class Widget : IComparable
{
    int x;
    int y;
    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public Widget(int argx, int argy)
    {
        x = argx;
        y = argy;
    }

    public int CompareTo(object obj)
    {
        int result = 1;
        if (obj != null && obj is Widget)
        {
            Widget w = obj as Widget;
            result = this.X.CompareTo(w.X);
        }
        return result;
    }

    static public int Compare(Widget x, Widget y)
    {
        int result = 1;
        if (x != null && y != null)                
        {                
            result = x.CompareTo(y);
        }
        return result;
    }
}

I implemented IComparable, so it can be unstably sorted by List.Sort().

However, I also implemented the static method Compare, which can be passed as a delegate to a search method.

I borrowed this insertion sort method from C# 411:

 public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)
        {           
            int count = list.Count;
            for (int j = 1; j < count; j++)
            {
                T key = list[j];

                int i = j - 1;
                for (; i >= 0 && comparison(list[i], key) > 0; i--)
                {
                    list[i + 1] = list[i];
                }
                list[i + 1] = key;
            }
    }

You would put this in the sort helpers class that you mentioned in your question.

Now, to use it:

    static void Main(string[] args)
    {
        List<Widget> widgets = new List<Widget>();

        widgets.Add(new Widget(0, 1));
        widgets.Add(new Widget(1, 1));
        widgets.Add(new Widget(0, 2));
        widgets.Add(new Widget(1, 2));

        InsertionSort<Widget>(widgets, Widget.Compare);

        foreach (Widget w in widgets)
        {
            Console.WriteLine(w.X + ":" + w.Y);
        }
    }

And it outputs:

0:1
0:2
1:1
1:2
Press any key to continue . . .

This could probably be cleaned up with some anonymous delegates, but I'll leave that up to you.

EDIT: And NoBugz demonstrates the power of anonymous methods...so, consider mine more oldschool :P

Finding the average of a list

I want to add just another approach

import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)

CSS: background-color only inside the margin

If your margin is set on the body, then setting the background color of the html tag should color the margin area

html { background-color: black; }
body { margin:50px; background-color: white; }

http://jsfiddle.net/m3zzb/

Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

TypeScript - Append HTML to container element in Angular 2

You could do something like this:

htmlComponent.ts

htmlVariable: string = "<b>Some html.</b>"; //this is html in TypeScript code that you need to display

htmlComponent.html

<div [innerHtml]="htmlVariable"></div> //this is how you display html code from TypeScript in your html

How to call a RESTful web service from Android?

Recently discovered that a third party library - Square Retrofit can do the job very well.


Defining REST endpoint

public interface GitHubService {
   @GET("/users/{user}/repos")
   List<Repo> listRepos(@Path("user") String user,Callback<List<User>> cb);
}

Getting the concrete service

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .build();
GitHubService service = restAdapter.create(GitHubService.class);

Calling the REST endpoint

List<Repo> repos = service.listRepos("octocat",new Callback<List<User>>() { 
    @Override
    public void failure(final RetrofitError error) {
        android.util.Log.i("example", "Error, body: " + error.getBody().toString());
    }
    @Override
    public void success(List<User> users, Response response) {
        // Do something with the List of Users object returned
        // you may populate your adapter here
    }
});

The library handles the json serialization and deserailization for you. You may customize the serialization and deserialization too.

Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .registerTypeAdapter(Date.class, new DateTypeAdapter())
    .create();

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .setConverter(new GsonConverter(gson))
    .build();

Connection failed: SQLState: '01000' SQL Server Error: 10061

To create a new Data source to SQL Server, do the following steps:

  1. In host computer/server go to Sql server management studio --> open Security Section on left hand --> right click on Login, select New Login and then create a new account for your database which you want to connect to.

  2. Check the TCP/IP Protocol is Enable. go to All programs --> Microsoft SQL server 2008 --> Configuration Tools --> open Sql server configuration manager. On the left hand select client protocols (based on your operating system 32/64 bit). On the right hand, check TCP/IP Protocol be Enabled.

  3. In Remote computer/server, open Data source administrator. Control panel --> Administrative tools --> Data sources (ODBC).

  4. In User DSN or System DSN , click Add button and select Sql Server driver and then press Finish.

  5. Enter Name.

  6. Enter Server, note that: if you want to enter host computer address, you should enter that`s IP address without "\\". eg. 192.168.1.5 and press Next.

  7. Select With SQL Server authentication using a login ID and password entered by the user.

  8. At the bellow enter your login ID and password which you created on first step. and then click Next.

  9. If shown Database is your database, click Next and then Finish.

Run a JAR file from the command line and specify classpath

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

What to do about Eclipse's "No repository found containing: ..." error messages?

On Juno (Build id: 20130225-0426), exporting update sites from 'Available software Sites", fixing the trailing "/" in the exported xml as described above, removing all sites and importing the fixed xml worked for me. Described here

How can I inspect element in an Android browser?

Chrome on Android makes it possible to use the Chrome developer tools on the desktop to inspect the HTML that was loaded from the Chrome application on the Android device.

See: https://developers.google.com/chrome-developer-tools/docs/remote-debugging

Android Stop Emulator from Command Line

Why not just do

adb reboot bootloader

Measure the time it takes to execute a t-sql query

Click on Statistics icon to display and then run the query to get the timings and to know how efficient your query is

Passing an array as parameter in JavaScript

It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]?

Sum values from multiple rows using vlookup or index/match functions

You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.

Adding two numbers concatenates them instead of calculating the sum

Use parseInt(...) but make sure you specify a radix value; otherwise you will run into several bugs (if the string begins with "0", the radix is octal/8 etc.).

var x = parseInt(stringValueX, 10);
var y = parseInt(stringValueY, 10);

alert(x + y);

Hope this helps!

How do you access a website running on localhost from iPhone browser

Find your system's IP address and on what port you are running the website.

Say your IP address is 121.300.00.250 and your port is 8080.

[Port number: see your web browser while running the page eg: localhost:8080/... then the port number is 8080]

Now in your mobile go to 121.300.00.250:8080/.. and you'll find your website.

IMPORTANT: You have to make sure that your server (e.g Apache Tomcat) is in started condition

Why do package names often begin with "com"

  • com => domain
  • something => company name
  • something => Main package name

For example: com.paresh.mainpackage

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html

How can you remove all documents from a collection with Mongoose?

.remove() is deprecated. instead we can use deleteMany

DateTime.deleteMany({}, callback).

What is the iOS 6 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

iPad:

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)

How to create a self-signed certificate with OpenSSL

Modern browsers now throw a security error for otherwise well-formed self-signed certificates if they are missing a SAN (Subject Alternate Name). OpenSSL does not provide a command-line way to specify this, so many developers' tutorials and bookmarks are suddenly outdated.

The quickest way to get running again is a short, stand-alone conf file:

  1. Create an OpenSSL config file (example: req.cnf)

    [req]
    distinguished_name = req_distinguished_name
    x509_extensions = v3_req
    prompt = no
    [req_distinguished_name]
    C = US
    ST = VA
    L = SomeCity
    O = MyCompany
    OU = MyDivision
    CN = www.company.com
    [v3_req]
    keyUsage = critical, digitalSignature, keyAgreement
    extendedKeyUsage = serverAuth
    subjectAltName = @alt_names
    [alt_names]
    DNS.1 = www.company.com
    DNS.2 = company.com
    DNS.3 = company.net
    
  2. Create the certificate referencing this config file

    openssl req -x509 -nodes -days 730 -newkey rsa:2048 \
     -keyout cert.key -out cert.pem -config req.cnf -sha256
    

Example config from https://support.citrix.com/article/CTX135602

Invert colors of an image in CSS or JavaScript

For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.

How do I check the difference, in seconds, between two dates?

We have function total_seconds() with Python 2.7 Please see below code for python 2.6

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)

Read a variable in bash with a default value

name=Ricardo
echo "Please enter your name: $name \c"
read newname
[ -n "$newname" ] && name=$newname

Set the default; print it; read a new value; if there is a new value, use it in place of the default. There is (or was) some variations between shells and systems on how to suppress a newline at the end of a prompt. The '\c' notation seems to work on MacOS X 10.6.3 with a 3.x bash, and works on most variants of Unix derived from System V, using Bourne or Korn shells.

Also note that the user would probably not realize what is going on behind the scenes; their new data would be entered after the name already on the screen. It might be better to format it:

echo "Please enter your name ($name): \c"

How do you add an action to a button programmatically in xcode

Try this:

Swift 4

myButton.addTarget(self,
                   action: #selector(myAction),
                   for: .touchUpInside)

Objective-C

[myButton addTarget:self 
             action:@selector(myAction) 
   forControlEvents:UIControlEventTouchUpInside];

You can find a rich source of information in Apple's Documentation. Have a look at the UIButton's documentation, it will reveal that UIButton is a descendant of UIControl, which implements the method to add targets.

--

You'll need to pay attention to whether add colon or not after myAction in action:@selector(myAction)

Here's the reference.

Select n random rows from SQL Server table

It appears newid() can't be used in where clause, so this solution requires an inner query:

SELECT *
FROM (
    SELECT *, ABS(CHECKSUM(NEWID())) AS Rnd
    FROM MyTable
) vw
WHERE Rnd % 100 < 10        --10%

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

What is the best workaround for the WCF client `using` block issue?

A wrapper like this would work:

public class ServiceClientWrapper<ServiceType> : IDisposable
{
    private ServiceType _channel;
    public ServiceType Channel
    {
        get { return _channel; }
    }

    private static ChannelFactory<ServiceType> _channelFactory;

    public ServiceClientWrapper()
    {
        if(_channelFactory == null)
             // Given that the endpoint name is the same as FullName of contract.
            _channelFactory = new ChannelFactory<ServiceType>(typeof(T).FullName);
        _channel = _channelFactory.CreateChannel();
        ((IChannel)_channel).Open();
    }

    public void Dispose()
    {
        try
        {
            ((IChannel)_channel).Close();
        }
        catch (Exception e)
        {
            ((IChannel)_channel).Abort();
            // TODO: Insert logging
        }
    }
}

That should enable you to write code like:

ResponseType response = null;
using(var clientWrapper = new ServiceClientWrapper<IService>())
{
    var request = ...
    response = clientWrapper.Channel.MyServiceCall(request);
}
// Use your response object.

The wrapper could of course catch more exceptions if that is required, but the principle remains the same.

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

Can't connect to MySQL server on 'localhost' (10061)

I had difficulty accessing MySQL while connecting via a localhost connection on the standard port 3306, which worked fine when I installed and configured it for prior classes I had taken in MySQL and Java. I was getting errors like "error 2003" and "Cannot connect to MySql server on localhost (10061)". I tried connecting from both MySQL Workbench (5.2.35 CE) and Netbeans (7.2). I am using Windows 7 64 bit professional.

I tried typing in services.msc in the start menu search box, which opened the services dialog box to show all the services installed in windows. I scrolled down to MySQL and started this service. Subsequent attempts to connect to MySQL from MySQL WorkBench and from the command prompt succeeded.

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way

intval::text

and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

PKIX path building failed: unable to find valid certification path to requested target

This error can also happen if the server only sends its leaf certificate and does not send all the chain certificates needed to build the trust chain to the root CA. Unfortunately this is a common misconfiguration of servers.

Most browsers work around this problem if they already know the missing chain certificate from earlier visits or maybe download the missing certificate if the leaf certificate contains a URL for CA issuers in Authority Information Access (AIA). But this behavior is usually restricted to desktop browsers and other tools simply fail because they cannot build the trust chain.

You can make the JRE to automatically download the intermediate certificate by setting com.sun.security.enableAIAcaIssuers to true

To verify if the server is sending all the chain certificates you can enter the host in the following SSL certificate validation tool https://www.digicert.com/help/

Check play state of AVPlayer

A more reliable alternative to NSNotification is to add yourself as observer to player's rate property.

[self.player addObserver:self
              forKeyPath:@"rate"
                 options:NSKeyValueObservingOptionNew
                 context:NULL];

Then check if the new value for observed rate is zero, which means that playback has stopped for some reason, like reaching the end or stalling because of empty buffer.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"rate"]) {
        float rate = [change[NSKeyValueChangeNewKey] floatValue];
        if (rate == 0.0) {
            // Playback stopped
        } else if (rate == 1.0) {
            // Normal playback
        } else if (rate == -1.0) {
            // Reverse playback
        }
    }
}

For rate == 0.0 case, to know what exactly caused the playback to stop, you can do the following checks:

if (self.player.error != nil) {
    // Playback failed
}
if (CMTimeGetSeconds(self.player.currentTime) >=
    CMTimeGetSeconds(self.player.currentItem.duration)) {
    // Playback reached end
} else if (!self.player.currentItem.playbackLikelyToKeepUp) {
    // Not ready to play, wait until enough data is loaded
}

And don't forget to make your player stop when it reaches the end:

self.player.actionAtItemEnd = AVPlayerActionAtItemEndPause;

Java: how to represent graphs?

A simple representation written by 'Robert Sedgwick' and 'Kevin Wayne' is available at http://algs4.cs.princeton.edu/41graph/Graph.java.html

Explanation copied from the above page.

The Graph class represents an undirected graph of vertices named 0 through V - 1.

It supports the following two primary operations: add an edge to the graph, iterate over all of the vertices adjacent to a vertex. It also provides methods for returning the number of vertices V and the number of edges E. Parallel edges and self-loops are permitted. By convention, a self-loop v-v appears in the adjacency list of v twice and contributes two to the degree of v.

This implementation uses an adjacency-lists representation, which is a vertex-indexed array of Bag objects. All operations take constant time (in the worst case) except iterating over the vertices adjacent to a given vertex, which takes time proportional to the number of such vertices.

Force to open "Save As..." popup open at text link click for PDF in HTML

Generally it happens, because some browsers settings or plug-ins directly open PDF in the same window like a simple web page.

The following might help you. I have done it in PHP a few years back. But currently I'm not working on that platform.

<?php
    if (isset($_GET['file'])) {
        $file = $_GET['file'];
        if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
            header('Content-type: application/pdf');
            header("Content-Disposition: attachment; filename=\"$file\"");
            readfile($file);
        }
    }
    else {
        header("HTTP/1.0 404 Not Found");
        echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
    }
?>

Save the above as download.php.

Save this little snippet as a PHP file somewhere on your server and you can use it to make a file download in the browser, rather than display directly. If you want to serve files other than PDF, remove or edit line 5.

You can use it like so:

Add the following link to your HTML file.

<a href="download.php?file=my_pdf_file.pdf">Download the cool PDF.</a>

Reference from: This blog

Can someone explain the dollar sign in Javascript?

Here is a good short video explanation: https://www.youtube.com/watch?v=Acm-MD_6934

According to Ecma International Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1). The Unicode identifier grammar is based on both normative and informative character categories specified by the Unicode Standard. The characters in the specified categories in version 3.0 of the Unicode standard must be treated as in those categories by all conforming ECMAScript implementations.this standard specifies specific character additions:

The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.

Further reading can be found on: http://www.ecma-international.org/ecma-262/5.1/#sec-7.6

Ecma International is an industry association founded in 1961 and dedicated to the standardization of Information and Communication Technology (ICT) and Consumer Electronics (CE).

How to unzip gz file using Python

import gzip
import shutil
with gzip.open('file.txt.gz', 'rb') as f_in:
    with open('file.txt', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

How to Import .bson file format on mongodb

I have used this:

mongorestore -d databasename -c file.bson fullpath/file.bson

1.copy the file path and file name from properties (try to put all bson files in different folder), 2.use this again and again with changing file name only.

How to load image (and other assets) in Angular an project?

Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.

Sample example

<img [src]="'assets/img/klogo.png'" alt="image">

Git merge is not possible because I have unmerged files

It might be the Unmerged paths that cause

error: Merging is not possible because you have unmerged files.

If so, try:

git status

if it says

You have unmerged paths.

do as suggested: either resolve conflicts and then commit or abort the merge entirely with

git merge --abort

You might also see files listed under Unmerged paths, which you can resolve by doing

git rm <file>

Two's Complement in Python

Here's a version to convert each value in a hex string to it's two's complement version.


In [5159]: twoscomplement('f0079debdd9abe0fdb8adca9dbc89a807b707f')                                                                                                 
Out[5159]: '10097325337652013586346735487680959091'


def twoscomplement(hm): 
   twoscomplement='' 
   for x in range(0,len(hm)): 
       value = int(hm[x],16) 
       if value % 2 == 1: 
         twoscomplement+=hex(value ^ 14)[2:] 
       else: 
         twoscomplement+=hex(((value-1)^15)&0xf)[2:] 
   return twoscomplement            

Bootstrap Alert Auto Close

I found this to be a better solution

$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
    $(".alert-dismissible").alert('close');
});

How to wait 5 seconds with jQuery?

Built in javascript setTimeout.

setTimeout(
  function() 
  {
    //do something special
  }, 5000);

UPDATE: you want to wait since when the page has finished loading, so put that code inside your $(document).ready(...); script.

UPDATE 2: jquery 1.4.0 introduced the .delay method. Check it out. Note that .delay only works with the jQuery effects queues.

Best way to create unique token in Rails?

I think token should be handled just like password. As such, they should be encrypted in DB.

I'n doing something like this to generate a unique new token for a model:

key = ActiveSupport::KeyGenerator
                .new(Devise.secret_key)
                .generate_key("put some random or the name of the key")

loop do
  raw = SecureRandom.urlsafe_base64(nil, false)
  enc = OpenSSL::HMAC.hexdigest('SHA256', key, raw)

  break [raw, enc] unless Model.exist?(token: enc)
end

throwing exceptions out of a destructor

I currently follow the policy (that so many are saying) that classes shouldn't actively throw exceptions from their destructors but should instead provide a public "close" method to perform the operation that could fail...

...but I do believe destructors for container-type classes, like a vector, should not mask exceptions thrown from classes they contain. In this case, I actually use a "free/close" method that calls itself recursively. Yes, I said recursively. There's a method to this madness. Exception propagation relies on there being a stack: If a single exception occurs, then both the remaining destructors will still run and the pending exception will propagate once the routine returns, which is great. If multiple exceptions occur, then (depending on the compiler) either that first exception will propagate or the program will terminate, which is okay. If so many exceptions occur that the recursion overflows the stack then something is seriously wrong, and someone's going to find out about it, which is also okay. Personally, I err on the side of errors blowing up rather than being hidden, secret, and insidious.

The point is that the container remains neutral, and it's up to the contained classes to decide whether they behave or misbehave with regard to throwing exceptions from their destructors.

Free XML Formatting tool

You could also try http://xmltoolbox.appspot.com/ it is an online xml formatter. You just paste your xml into a large text area field and press "format xml" then it pretty prints the xml in the text area so its easy to read or copy.

There is also a nice little filter feature that allows you to see all of a certain element.

Hope you will enjoy the tool

jQuery .live() vs .on() method for adding a click event after loading dynamic html

$(document).on('click', '.selector', function() { /* do stuff */ });

EDIT: I'm providing a bit more information on how this works, because... words. With this example, you are placing a listener on the entire document.

When you click on any element(s) matching .selector, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation() method -- which would top the bubbling of an event to parent elements.

Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.

This is smart for a few reasons, including performance and memory utilization (in large scale applications)

EDIT:

Obviously, the closest parent element you can listen on is better, and you can use any element in place of document as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.

Android camera android.hardware.Camera deprecated

Answers provided here as which camera api to use are wrong. Or better to say they are insufficient.

Some phones (for example Samsung Galaxy S6) could be above api level 21 but still may not support Camera2 api.

CameraCharacteristics mCameraCharacteristics = mCameraManager.getCameraCharacteristics(mCameraId);
Integer level = mCameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
if (level == null || level == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
    return false;
}

CameraManager class in Camera2Api has a method to read camera characteristics. You should check if hardware wise device is supporting Camera2 Api or not.

But there are more issues to handle if you really want to make it work for a serious application: Like, auto-flash option may not work for some devices or battery level of the phone might create a RuntimeException on Camera or phone could return an invalid camera id and etc.

So best approach is to have a fallback mechanism as for some reason Camera2 fails to start you can try Camera1 and if this fails as well you can make a call to Android to open default Camera for you.

ENOENT, no such file or directory

Tilde expansion is a shell thing. Write the proper pathname (probably /home/yourusername/Desktop/etcetcetc) or use
process.env.HOME + '/Desktop/blahblahblah'

Skip Git commit hooks

Maybe (from git commit man page):

git commit --no-verify

-n  
--no-verify

This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).

As commented by Blaise, -n can have a different role for certain commands.
For instance, git push -n is actually a dry-run push.
Only git push --no-verify would skip the hook.


Note: Git 2.14.x/2.15 improves the --no-verify behavior:

See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster -- in commit c3e034f, 23 Aug 2017)

commit: skip discarding the index if there is no pre-commit hook

"git commit" used to discard the index and re-read from the filesystem just in case the pre-commit hook has updated it in the middle; this has been optimized out when we know we do not run the pre-commit hook.


Davi Lima points out in the comments the git cherry-pick does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue, after a merge conflict resolution.

Listing all the folders subfolders and files in a directory using php

In case you want to use directoryIterator

Following function is a re-implementation of @Shef answer with directoryIterator

function listFolderFiles($dir)
{
    echo '<ol>';
    foreach (new DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
            echo '<li>' . $fileInfo->getFilename();
            if ($fileInfo->isDir()) {
                listFolderFiles($fileInfo->getPathname());
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}
listFolderFiles('Main Dir');

How can I use xargs to copy files that have spaces and quotes in their names?

If you are using Bash, you can convert stdout to an array of lines by mapfile:

find . | grep "FooBar" | (mapfile -t; cp "${MAPFILE[@]}" ~/foobar)

The benefits are:

  • It's built-in, so it's faster.
  • Execute the command with all file names in one time, so it's faster.
  • You can append other arguments to the file names. For cp, you can also:

    find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +
    

    however, some commands don't have such feature.

The disadvantages:

  • Maybe not scale well if there are too many file names. (The limit? I don't know, but I had tested with 10 MB list file which includes 10000+ file names with no problem, under Debian)

Well... who knows if Bash is available on OS X?

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

LINQ: Select where object does not contain items from list

In general, you're looking for the "Except" extension.

var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);

In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int> of IDs)

PHP Fatal error: Call to undefined function json_decode()

The same issue with 7.1

apt-get install php7.1-json sudo nano /etc/php/7.1/mods-available/json.ini

  • Add json.so to the new file
  • Add the appropriate sym link under conf.d
  • Restart apache2 service (if needed)

Checking if a collection is empty in Java: which is the best method?

You should absolutely use isEmpty(). Computing the size() of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there's no optimization for size() which can't also make isEmpty() faster, whereas the reverse is not the case.

For example, suppose you had a linked list structure which didn't cache the size (whereas LinkedList<E> does). Then size() would become an O(N) operation, whereas isEmpty() would still be O(1).

Additionally of course, using isEmpty() states what you're actually interested in more clearly.

Reading *.wav files in Python

Here's a Python 3 solution using the built in wave module [1], that works for n channels, and 8,16,24... bits.

import sys
import wave

def read_wav(path):
    with wave.open(path, "rb") as wav:
        nchannels, sampwidth, framerate, nframes, _, _ = wav.getparams()
        print(wav.getparams(), "\nBits per sample =", sampwidth * 8)

        signed = sampwidth > 1  # 8 bit wavs are unsigned
        byteorder = sys.byteorder  # wave module uses sys.byteorder for bytes

        values = []  # e.g. for stereo, values[i] = [left_val, right_val]
        for _ in range(nframes):
            frame = wav.readframes(1)  # read next frame
            channel_vals = []  # mono has 1 channel, stereo 2, etc.
            for channel in range(nchannels):
                as_bytes = frame[channel * sampwidth: (channel + 1) * sampwidth]
                as_int = int.from_bytes(as_bytes, byteorder, signed=signed)
                channel_vals.append(as_int)
            values.append(channel_vals)

    return values, framerate

You can turn the result into a NumPy array.

import numpy as np

data, rate = read_wav(path)
data = np.array(data)

Note, I've tried to make it readable rather than fast. I found reading all the data at once was almost 2x faster. E.g.

with wave.open(path, "rb") as wav:
    nchannels, sampwidth, framerate, nframes, _, _ = wav.getparams()
    all_bytes = wav.readframes(-1)

framewidth = sampwidth * nchannels
frames = (all_bytes[i * framewidth: (i + 1) * framewidth]
            for i in range(nframes))

for frame in frames:
    ...

Although python-soundfile is roughly 2 orders of magnitude faster (hard to approach this speed with pure CPython).

[1] https://docs.python.org/3/library/wave.html

C#: Dynamic runtime cast

The opensource framework Dynamitey has a static method that does late binding using DLR including cast conversion among others.

dynamic Cast(object obj, Type castTo){
    return Dynamic.InvokeConvert(obj, castTo, explict:true);
}

The advantage of this over a Cast<T> called using reflection, is that this will also work for any IDynamicMetaObjectProvider that has dynamic conversion operators, ie. TryConvert on DynamicObject.

How do you run a crontab in Cygwin on Windows?

You have two options:

  1. Install cron as a windows service, using cygrunsrv:

    cygrunsrv -I cron -p /usr/sbin/cron -a -n
    
    net start cron
    

    Note, in (very) old versions of cron you need to use -D instead of -n

  2. The 'non .exe' files are probably bash scripts, so you can run them via the windows scheduler by invoking bash to run the script, e.g.:

    C:\cygwin\bin\bash.exe -l -c "./full-path/to/script.sh"
    

SQL: How do I SELECT only the rows with a unique value on certain column?

I'm a fan of NOT EXISTS

SELECT DISTINCT contract, activity FROM table t1
WHERE NOT EXISTS (
  SELECT * FROM table t2
  WHERE t2.contract = t1.contract AND t2.activity != t1.activity
)

In-memory size of a Python structure

When you use the dir([object]) built-in function, you can get the __sizeof__ of the built-in function.

>>> a = -1
>>> a.__sizeof__()
24

Extracting text OpenCV

You can try this method that is developed by Chucai Yi and Yingli Tian.

They also share a software (which is based on Opencv-1.0 and it should run under Windows platform.) that you can use (though no source code available). It will generate all the text bounding boxes (shown in color shadows) in the image. By applying to your sample images, you will get the following results:

Note: to make the result more robust, you can further merge adjacent boxes together.


Update: If your ultimate goal is to recognize the texts in the image, you can further check out gttext, which is an OCR free software and Ground Truthing tool for Color Images with Text. Source code is also available.

With this, you can get recognized texts like:

How to determine whether an object has a given property in JavaScript

Underscore.js or Lodash

if (_.has(x, "y")) ...

:)

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

rolling back to node v10.17.0 fixed the problem to me.

You can use nvm to do so:

https://github.com/nvm-sh/nvm

> nvm install 10.17.0
> nvm use 10.17.0
> node -v
10.17.0

Firebase: how to generate a unique numeric ID for key?

As the docs say, this can be achieved just by using set instead if push.

As the docs say, it is not recommended (due to possible overwrite by other user at the "same" time).

But in some cases it's helpful to have control over the feed's content including keys.

As an example of webapp in js, 193 being your id generated elsewhere, simply:

 firebase.initializeApp(firebaseConfig);
  var data={
      "name":"Prague"
  };
  firebase.database().ref().child('areas').child("193").set(data);

This will overwrite any area labeled 193 or create one if it's not existing yet.

Facebook Open Graph not clearing cache

If you have many pages and don't want to refresh them manually - you can do it automatically.

Lets say you have user profile page with photo:

$url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$user_profile;
$user_photo = 'http://'.$_SERVER['HTTP_HOST'].'/'.$user_photo;

<meta property="og:url" content="<?php echo $url; ?>"/>
<meta property="og:image" content="<?php echo $user_photo; ?>"

Just add this to your page:

// with jQuery
$.post(
    'https://graph.facebook.com',
    {
        id: '<?php echo $url; ?>',
        scrape: true
    },
    function(response){
        console.log(response);
    }
);

// with "vanilla" javascript
var fbxhr = new XMLHttpRequest();
fbxhr.open("POST", "https://graph.facebook.com", true);
fbxhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
fbxhr.send("id=<?php echo $url; ?>&scrape=true");

This will refresh Facebook cache. If you use the jQuery solution, have a look at "response" in console.log - you will find there "updated_time" field and other useful information.

How to start MySQL server on windows xp

use the command "mysql -u root -p" in the bin folder path. and give the MY SQL password which you have set earlier.

How to activate JMX on my JVM for access with jconsole?

I had this exact issue, and created a GitHub project for testing and figuring out the correct settings.

It contains a working Dockerfile with supporting scripts, and a simple docker-compose.yml for quick testing.

How can I copy a file on Unix using C?

There is a way to do this, without resorting to the system call, you need to incorporate a wrapper something like this:

#include <sys/sendfile.h>
#include <fcntl.h>
#include <unistd.h>

/* 
** http://www.unixguide.net/unix/programming/2.5.shtml 
** About locking mechanism...
*/

int copy_file(const char *source, const char *dest){
   int fdSource = open(source, O_RDWR);

   /* Caf's comment about race condition... */
   if (fdSource > 0){
     if (lockf(fdSource, F_LOCK, 0) == -1) return 0; /* FAILURE */
   }else return 0; /* FAILURE */

   /* Now the fdSource is locked */

   int fdDest = open(dest, O_CREAT);
   off_t lCount;
   struct stat sourceStat;
   if (fdSource > 0 && fdDest > 0){
      if (!stat(source, &sourceStat)){
          int len = sendfile(fdDest, fdSource, &lCount, sourceStat.st_size);
          if (len > 0 && len == sourceStat.st_size){
               close(fdDest);
               close(fdSource);

               /* Sanity Check for Lock, if this is locked -1 is returned! */
               if (lockf(fdSource, F_TEST, 0) == 0){
                   if (lockf(fdSource, F_ULOCK, 0) == -1){
                      /* WHOOPS! WTF! FAILURE TO UNLOCK! */
                   }else{
                      return 1; /* Success */
                   }
               }else{
                   /* WHOOPS! WTF! TEST LOCK IS -1 WTF! */
                   return 0; /* FAILURE */
               }
          }
      }
   }
   return 0; /* Failure */
}

The above sample (error checking is omitted!) employs open, close and sendfile.

Edit: As caf has pointed out a race condition can occur between the open and stat so I thought I'd make this a bit more robust...Keep in mind that the locking mechanism varies from platform to platform...under Linux, this locking mechanism with lockf would suffice. If you want to make this portable, use the #ifdef macros to distinguish between different platforms/compilers...Thanks caf for spotting this...There is a link to a site that yielded "universal locking routines" here.

What does void* mean and how to use it?

The function takes a pointer to an arbitrary type and returns one such.

Explicit vs implicit SQL joins

The first answer you gave uses what is known as ANSI join syntax, the other is valid and will work in any relational database.

I agree with grom that you should use ANSI join syntax. As they said, the main reason is for clarity. Rather than having a where clause with lots of predicates, some of which join tables and others restricting the rows returned with the ANSI join syntax you are making it blindingly clear which conditions are being used to join your tables and which are being used to restrict the results.

Read/Write 'Extended' file properties (C#)

GetDetailsOf() Method - Retrieves details about an item in a folder. For example, its size, type, or the time of its last modification. File Properties may vary based on the Windows-OS version.

List<string> arrHeaders = new List<string>();

 Shell shell = new ShellClass();
 Folder rFolder = shell.NameSpace(_rootPath);
 FolderItem rFiles = rFolder.ParseName(filename);

 for (int i = 0; i < short.MaxValue; i++)
 {
      string value = rFolder.GetDetailsOf(rFiles, i).Trim();
      arrHeaders.Add(value);
 }

Why use $_SERVER['PHP_SELF'] instead of ""

Using an empty string is perfectly fine and actually much safer than simply using $_SERVER['PHP_SELF'].

When using $_SERVER['PHP_SELF'] it is very easy to inject malicious data by simply appending /<script>... after the whatever.php part of the URL so you should not use this method and stop using any PHP tutorial that suggests it.

MySQL create stored procedure syntax with delimiter

Here is the sample MYSQL Stored Procedure with delimiter and how to call..

DELIMITER $$

DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_user_login`(
  IN loc_username VARCHAR(255),
  IN loc_password VARCHAR(255)
)
BEGIN

  SELECT user_id,
         user_name,
         user_emailid,
         user_profileimage,
         last_update
    FROM tbl_user
   WHERE user_name = loc_username
     AND password = loc_password
     AND status = 1;

END $$

DELIMITER ;

and call by, mysql_connection specification and

$loginCheck="call sp_user_login('".$username."','".$password."');";

it will return the result from the procedure.

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

Laravel 5.1 - Checking a Database Connection

Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!

// Test database connection
try {
    DB::connection()->getPdo();
} catch (\Exception $e) {
    die("Could not connect to the database.  Please check your configuration. error:" . $e );
}

Soft hyphen in HTML (<wbr> vs. &shy;)

This is a crossbrowser solution that I was looking at a little while ago that runs on the client and using jQuery:

(function($) { 
  $.fn.breakWords = function() { 
    this.each(function() { 
      if(this.nodeType !== 1) { return; } 

      if(this.currentStyle && typeof this.currentStyle.wordBreak === 'string') { 
        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 
        this.runtimeStyle.wordBreak = 'break-all'; 
      } 
      else if(document.createTreeWalker) { 

        //Faster Trim in Javascript, Flagrant Badassery 
        //http://blog.stevenlevithan.com/archives/faster-trim-javascript 

        var trim = function(str) { 
          str = str.replace(/^\s\s*/, ''); 
          var ws = /\s/, 
          i = str.length; 
          while (ws.test(str.charAt(--i))); 
          return str.slice(0, i + 1); 
        }; 

        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 

        //For Opera, Safari, and Firefox 
        var dWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT, null, false); 
        var node,s,c = String.fromCharCode('8203'); 
        while (dWalker.nextNode()) { 
          node = dWalker.currentNode; 
          //we need to trim String otherwise Firefox will display 
          //incorect text-indent with space characters 
          s = trim( node.nodeValue ).split('').join(c); 
          node.nodeValue = s; 
        } 
      } 
    }); 

    return this; 
  }; 
})(jQuery); 

EF Core add-migration Build Failed

I got the same error. There were no errors during the build proccess. I closed the Visual Studio and it worked.

How to fix error with xml2-config not found when installing PHP from sources?

Ubuntu, Debian:

sudo apt install libxml2-dev

Centos:

sudo yum install libxml2-devel

Why do we need middleware for async flow in Redux?

You don't.

But... you should use redux-saga :)

Dan Abramov's answer is right about redux-thunk but I will talk a bit more about redux-saga that is quite similar but more powerful.

Imperative VS declarative

  • DOM: jQuery is imperative / React is declarative
  • Monads: IO is imperative / Free is declarative
  • Redux effects: redux-thunk is imperative / redux-saga is declarative

When you have a thunk in your hands, like an IO monad or a promise, you can't easily know what it will do once you execute. The only way to test a thunk is to execute it, and mock the dispatcher (or the whole outside world if it interacts with more stuff...).

If you are using mocks, then you are not doing functional programming.

Seen through the lens of side-effects, mocks are a flag that your code is impure, and in the functional programmer's eye, proof that something is wrong. Instead of downloading a library to help us check the iceberg is intact, we should be sailing around it. A hardcore TDD/Java guy once asked me how you do mocking in Clojure. The answer is, we usually don't. We usually see it as a sign we need to refactor our code.

Source

The sagas (as they got implemented in redux-saga) are declarative and like the Free monad or React components, they are much easier to test without any mock.

See also this article:

in modern FP, we shouldn’t write programs — we should write descriptions of programs, which we can then introspect, transform, and interpret at will.

(Actually, Redux-saga is like a hybrid: the flow is imperative but the effects are declarative)

Confusion: actions/events/commands...

There is a lot of confusion in the frontend world on how some backend concepts like CQRS / EventSourcing and Flux / Redux may be related, mostly because in Flux we use the term "action" which can sometimes represent both imperative code (LOAD_USER) and events (USER_LOADED). I believe that like event-sourcing, you should only dispatch events.

Using sagas in practice

Imagine an app with a link to a user profile. The idiomatic way to handle this with each middleware would be:

redux-thunk

<div onClick={e => dispatch(actions.loadUserProfile(123)}>Robert</div>

function loadUserProfile(userId) {
  return dispatch => fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'USER_PROFILE_LOADED', data }),
      err => dispatch({ type: 'USER_PROFILE_LOAD_FAILED', err })
    );
}

redux-saga

<div onClick={e => dispatch({ type: 'USER_NAME_CLICKED', payload: 123 })}>Robert</div>


function* loadUserProfileOnNameClick() {
  yield* takeLatest("USER_NAME_CLICKED", fetchUser);
}

function* fetchUser(action) {
  try {
    const userProfile = yield fetch(`http://data.com/${action.payload.userId }`)
    yield put({ type: 'USER_PROFILE_LOADED', userProfile })
  } 
  catch(err) {
    yield put({ type: 'USER_PROFILE_LOAD_FAILED', err })
  }
}

This saga translates to:

every time a username gets clicked, fetch the user profile and then dispatch an event with the loaded profile.

As you can see, there are some advantages of redux-saga.

The usage of takeLatest permits to express that you are only interested to get the data of the last username clicked (handle concurrency problems in case the user click very fast on a lot of usernames). This kind of stuff is hard with thunks. You could have used takeEvery if you don't want this behavior.

You keep action creators pure. Note it's still useful to keep actionCreators (in sagas put and components dispatch), as it might help you to add action validation (assertions/flow/typescript) in the future.

Your code becomes much more testable as the effects are declarative

You don't need anymore to trigger rpc-like calls like actions.loadUser(). Your UI just needs to dispatch what HAS HAPPENED. We only fire events (always in the past tense!) and not actions anymore. This means that you can create decoupled "ducks" or Bounded Contexts and that the saga can act as the coupling point between these modular components.

This means that your views are more easy to manage because they don't need anymore to contain that translation layer between what has happened and what should happen as an effect

For example imagine an infinite scroll view. CONTAINER_SCROLLED can lead to NEXT_PAGE_LOADED, but is it really the responsibility of the scrollable container to decide whether or not we should load another page? Then he has to be aware of more complicated stuff like whether or not the last page was loaded successfully or if there is already a page that tries to load, or if there is no more items left to load? I don't think so: for maximum reusability the scrollable container should just describe that it has been scrolled. The loading of a page is a "business effect" of that scroll

Some might argue that generators can inherently hide state outside of redux store with local variables, but if you start to orchestrate complex things inside thunks by starting timers etc you would have the same problem anyway. And there's a select effect that now permits to get some state from your Redux store.

Sagas can be time-traveled and also enables complex flow logging and dev-tools that are currently being worked on. Here is some simple async flow logging that is already implemented:

saga flow logging

Decoupling

Sagas are not only replacing redux thunks. They come from backend / distributed systems / event-sourcing.

It is a very common misconception that sagas are just here to replace your redux thunks with better testability. Actually this is just an implementation detail of redux-saga. Using declarative effects is better than thunks for testability, but the saga pattern can be implemented on top of imperative or declarative code.

In the first place, the saga is a piece of software that permits to coordinate long running transactions (eventual consistency), and transactions across different bounded contexts (domain driven design jargon).

To simplify this for frontend world, imagine there is widget1 and widget2. When some button on widget1 is clicked, then it should have an effect on widget2. Instead of coupling the 2 widgets together (ie widget1 dispatch an action that targets widget2), widget1 only dispatch that its button was clicked. Then the saga listen for this button click and then update widget2 by dispaching a new event that widget2 is aware of.

This adds a level of indirection that is unnecessary for simple apps, but make it more easy to scale complex applications. You can now publish widget1 and widget2 to different npm repositories so that they never have to know about each others, without having them to share a global registry of actions. The 2 widgets are now bounded contexts that can live separately. They do not need each others to be consistent and can be reused in other apps as well. The saga is the coupling point between the two widgets that coordinate them in a meaningful way for your business.

Some nice articles on how to structure your Redux app, on which you can use Redux-saga for decoupling reasons:

A concrete usecase: notification system

I want my components to be able to trigger the display of in-app notifications. But I don't want my components to be highly coupled to the notification system that has its own business rules (max 3 notifications displayed at the same time, notification queueing, 4 seconds display-time etc...).

I don't want my JSX components to decide when a notification will show/hide. I just give it the ability to request a notification, and leave the complex rules inside the saga. This kind of stuff is quite hard to implement with thunks or promises.

notifications

I've described here how this can be done with saga

Why is it called a Saga?

The term saga comes from the backend world. I initially introduced Yassine (the author of Redux-saga) to that term in a long discussion.

Initially, that term was introduced with a paper, the saga pattern was supposed to be used to handle eventual consistency in distributed transactions, but its usage has been extended to a broader definition by backend developers so that it now also covers the "process manager" pattern (somehow the original saga pattern is a specialized form of process manager).

Today, the term "saga" is confusing as it can describe 2 different things. As it is used in redux-saga, it does not describe a way to handle distributed transactions but rather a way to coordinate actions in your app. redux-saga could also have been called redux-process-manager.

See also:

Alternatives

If you don't like the idea of using generators but you are interested by the saga pattern and its decoupling properties, you can also achieve the same with redux-observable which uses the name epic to describe the exact same pattern, but with RxJS. If you're already familiar with Rx, you'll feel right at home.

const loadUserProfileOnNameClickEpic = action$ =>
  action$.ofType('USER_NAME_CLICKED')
    .switchMap(action =>
      Observable.ajax(`http://data.com/${action.payload.userId}`)
        .map(userProfile => ({
          type: 'USER_PROFILE_LOADED',
          userProfile
        }))
        .catch(err => Observable.of({
          type: 'USER_PROFILE_LOAD_FAILED',
          err
        }))
    );

Some redux-saga useful resources

2017 advises

  • Don't overuse Redux-saga just for the sake of using it. Testable API calls only are not worth it.
  • Don't remove thunks from your project for most simple cases.
  • Don't hesitate to dispatch thunks in yield put(someActionThunk) if it makes sense.

If you are frightened of using Redux-saga (or Redux-observable) but just need the decoupling pattern, check redux-dispatch-subscribe: it permits to listen to dispatches and trigger new dispatches in listener.

const unsubscribe = store.addDispatchListener(action => {
  if (action.type === 'ping') {
    store.dispatch({ type: 'pong' });
  }
});

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1
print(len(num))

Instead of use ths,

data = [1,2,3,4]
print(len(data))

Converting NumPy array into Python List structure?

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)

node.js, socket.io with SSL

Depending on your needs, you could allow both secure and unsecure connections and still only use one Socket.io instance.

You simply have to instanciate two servers, one for HTTP and one for HTTPS, then attach those servers to the Socket.io instance.

Server side :

// needed to read certificates from disk
const fs          = require( "fs"    );

// Servers with and without SSL
const http        = require( "http"  )
const https       = require( "https" );
const httpPort    = 3333;
const httpsPort   = 3334;
const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )
});
httpServer.listen( httpPort, function() {
    console.log(  `Listening HTTP on ${httpPort}` );
});
httpsServer.listen( httpsPort, function() {
    console.log(  `Listening HTTPS on ${httpsPort}` );
});

// Socket.io
const ioServer = require( "socket.io" );
const io       = new ioServer();
io.attach( httpServer  );
io.attach( httpsServer );

io.on( "connection", function( socket ) {

    console.log( "user connected" );
    // ... your code

});

Client side :

var url    = "//example.com:" + ( window.location.protocol == "https:" ? "3334" : "3333" );
var socket = io( url, {
    // set to false only if you use self-signed certificate !
    "rejectUnauthorized": true
});
socket.on( "connect", function( e ) {
    console.log( "connect", e );
});

If your NodeJS server is different from your Web server, you will maybe need to set some CORS headers. So in the server side, replace:

const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )
});

With:

const CORS_fn = (req, res) => {
    res.setHeader( "Access-Control-Allow-Origin"     , "*"    );
    res.setHeader( "Access-Control-Allow-Credentials", "true" );
    res.setHeader( "Access-Control-Allow-Methods"    , "*"    );
    res.setHeader( "Access-Control-Allow-Headers"    , "*"    );
    if ( req.method === "OPTIONS" ) {
        res.writeHead(200);
        res.end();
        return;
    }
};
const httpServer  = http.createServer( CORS_fn );
const httpsServer = https.createServer({
        "key" : fs.readFileSync( "yourcert.key" ),
        "cert": fs.readFileSync( "yourcert.crt" ),
        "ca"  : fs.readFileSync( "yourca.crt"   )
}, CORS_fn );

And of course add/remove headers and set the values of the headers according to your needs.

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

Convert a PHP object to an associative array

To convert an object into array just cast it explicitly:

$name_of_array = (array) $name_of_object;

Iterate through 2 dimensional array

 //This is The easiest I can Imagine . 
 // You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns 
for(int rows=0;rows<array.length;rows++){
    for(int columns=0;columns <array[rows].length;columns++){
        System.out.print(array[rows][columns] + "\t" );}
    System.out.println();}

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use this in your my.ini under

[mysqldump]
    user=root
    password=anything

jQuery: Best practice to populate drop down?

here is an example i did on change i get children of the first select in second select

jQuery(document).ready(function($) {
$('.your_select').change(function() {
    $.ajaxSetup({
        headers:{'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')}
    });

    $.ajax({
        type:'POST',
        url: 'Link',
        data:{
          'id': $(this).val()
        },
        success:function(r){
          $.each(r, function(res) {
                console.log(r[res].Nom);
                 $('.select_to_populate').append($("<option />").val(r[res].id).text(r[res].Nom));
            });
        },error:function(r) {
          alert('Error');
        }
    });
});

});enter code here

What does AngularJS do better than jQuery?

Data-Binding

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

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

DOM Manipulation

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

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

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

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

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

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

Implementation with jQuery

live demo here (click).

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

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

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

Implementation with Angular

live demo here (click).

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

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

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

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

General differences.

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

Angular and jQuery can't reasonably be compared.

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

Why use a framework?

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

Here are some things that modern frameworks are providing:

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

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

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

Angular (revisited).

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

DOM reference.

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

<clock></clock>

Done.

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

MVW Architecure / Modules / Dependency Injection

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

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

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

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

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

In our case it was an empty AndroidManifest.xml.

While upgrading Eclispe we ran into the usual trouble, and AndroidManifest.xml must have been checked into SVN by the build script after being clobbered.

Found it by compiling from inside Eclipse, instead of from the command line.

How to specify the default error page in web.xml?

You can also specify <error-page> for exceptions using <exception-type>, eg below:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorpages/exception.html</location>
</error-page>

Or map a error code using <error-code>:

<error-page>
    <error-code>404</error-code>
    <location>/errorpages/404error.html</location>
</error-page>

Encrypt and decrypt a password in Java

You can use java.security.MessageDigest with SHA as your algorithm choice.

For reference,

Try available example here

What is the difference between a Relational and Non-Relational Database?

Hmm, not quite sure what your question is.

In the title you ask about Databases (DB), whereas in the body of your text you ask about Database Management Systems (DBMS). The two are completely different and require different answers.

A DBMS is a tool that allows you to access a DB.

Other than the data itself, a DB is the concept of how that data is structured.

So just like you can program with Oriented Object methodology with a non-OO powered compiler, or vice-versa, so can you set-up a relational database without an RDBMS or use an RDBMS to store non-relational data.

I'll focus on what Relational Database (RDB) means and leave the discussion about what systems do to others.

A relational database (the concept) is a data structure that allows you to link information from different 'tables', or different types of data buckets. A data bucket must contain what is called a key or index (that allows to uniquely identify any atomic chunk of data within the bucket). Other data buckets may refer to that key so as to create a link between their data atoms and the atom pointed to by the key.

A non-relational database just stores data without explicit and structured mechanisms to link data from different buckets to one another.

As to implementing such a scheme, if you have a paper file with an index and in a different paper file you refer to the index to get at the relevant information, then you have implemented a relational database, albeit quite a simple one. So you see that you do not even need a computer (of course it can become tedious very quickly without one to help), similarly you do not need an RDBMS, though arguably an RDBMS is the right tool for the job. That said there are variations as to what the different tools out there can do so choosing the right tool for the job may not be all that straightforward.

I hope this is layman terms enough and is helpful to your understanding.

Android - drawable with rounded corners at the top only

You may need read this https://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

and below there is a Note.

Note Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero ("0dp") where you don't want rounded corners.

Git, How to reset origin/master to a commit?

origin/xxx branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).

What you need to do to update the remote is to force push your local changes to master:

git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master

"implements Runnable" vs "extends Thread" in Java

Yes: implements Runnable is the preferred way to do it, IMO. You're not really specialising the thread's behaviour. You're just giving it something to run. That means composition is the philosophically "purer" way to go.

In practical terms, it means you can implement Runnable and extend from another class as well... and you can also implement Runnable via a lambda expression as of Java 8.

When to use SELECT ... FOR UPDATE?

Short answers:

Q1: Yes.

Q2: Doesn't matter which you use.

Long answer:

A select ... for update will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.

Another way of looking at it, it is as if the following two statements are executed atomically:

select * from my_table where my_condition;

update my_table set my_column = my_column where my_condition;

Since the rows affected by my_condition are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.

Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.

What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.

How to expand a list to function arguments in Python

That can be done with:

foo(*values)

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

How to export table as CSV with headings on Postgresql?

The COPY command isn't what is restricted. What is restricted is directing the output from the TO to anywhere except to STDOUT. However, there is no restriction on specifying the output file via the \o command.

\o '/tmp/products_199.csv';
COPY products_273 TO STDOUT WITH (FORMAT CSV, HEADER);

Check if an array is empty or exists

When you create your image_array, it's empty, therefore your image_array.length is 0

As stated in the comment below, i edit my answer based on this question's answer) :

var image_array = []

inside the else brackets doesn't change anything to the image_array defined before in the code

How to get current time and date in Android

Kotlin

Here are various ways in to get current date time in kotlin.

fun main(args: Array<String>) {
    println(System.currentTimeMillis()) // current millisecond

    val date = Calendar.getInstance().time // current date object
    val date1 = Date(System.currentTimeMillis())

    println(date.toString())
    println(date1.toString())

    val now = Time(System.currentTimeMillis()) // current time object
    println(now.toString())

    val sdf = SimpleDateFormat("yyyy:MM:dd h:mm a", Locale.getDefault())
    println(sdf.format(Date())) // format current date

    println(DateFormat.getDateTimeInstance().format(System.currentTimeMillis())) // using getDateTimeInstance()

    println(LocalDateTime.now().toString()) // java 8

    println(ZonedDateTime.now().toString()) // java 8
}

How to simulate key presses or a click with JavaScript?

you can raise the click event on an element by doing

// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");

if (element) element.click();

Example here

Refresh an asp.net page on button click

When you say refresh the page, its new instance of the page that you are creating so you need to either have a static variable/session variable or a method to store and retrieve the count of hits on your page.

As far as refreshing the page is concerned, Response.Redirect(Request.RawUrl); or window.location=window.location would do the job for you.

Grouping into interval of 5 minutes within a time range

I came across the same issue.

I found that it is easy to group by any minute interval is just dividing epoch by minutes in amount of seconds and then either rounding or using floor to get ride of the remainder. So if you want to get interval in 5 minutes you would use 300 seconds.

    SELECT COUNT(*) cnt, 
    to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300) 
    AT TIME ZONE 'UTC' as interval_alias
    FROM TABLE_NAME GROUP BY interval_alias
interval_alias       cnt
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:45:00  8
2010-11-16 10:55:00  11 

This will return the data correctly group by the selected minutes interval; however, it will not return the intervals that don't contains any data. In order to get those empty intervals we can use the function generate_series.

    SELECT generate_series(MIN(date_trunc('hour',timestamp_column)),
    max(date_trunc('minute',timestamp_column)),'5m') as interval_alias FROM 
    TABLE_NAME

Result:

interval_alias       
-------------------    
2010-11-16 10:30:00  
2010-11-16 10:35:00
2010-11-16 10:40:00   
2010-11-16 10:45:00
2010-11-16 10:50:00   
2010-11-16 10:55:00   

Now to get the result with interval with zero occurrences we just outer join both result sets.

    SELECT series.minute as interval,  coalesce(cnt.amnt,0) as count from 
       (
       SELECT count(*) amnt,
       to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
       AT TIME ZONE 'UTC' as interval_alias
       from TABLE_NAME  group by interval_alias
       ) cnt
    
    RIGHT JOIN 
       (    
       SELECT generate_series(min(date_trunc('hour',timestamp_column)),
       max(date_trunc('minute',timestamp_column)),'5m') as minute from TABLE_NAME 
       ) series
  on series.minute = cnt.interval_alias

The end result will include the series with all 5 minute intervals even those that have no values.

interval             count
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:40:00  0
2010-11-16 10:45:00  8
2010-11-16 10:50:00  0 
2010-11-16 10:55:00  11 

The interval can be easily changed by adjusting the last parameter of generate_series. In our case we use '5m' but it could be any interval we want.

mysql update query with sub query

For the impatient:

UPDATE target AS t
INNER JOIN (
  SELECT s.id, COUNT(*) AS count
  FROM source_grouped AS s
  -- WHERE s.custom_condition IS (true)
  GROUP BY s.id
) AS aggregate ON aggregate.id = t.id
SET t.count = aggregate.count

That's @mellamokb's answer, as above, reduced to the max.

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Is there a need for range(len(a))?

Very simple example:

def loadById(self, id):
    if id in range(len(self.itemList)):
        self.load(self.itemList[id])

I can't think of a solution that does not use the range-len composition quickly.

But probably instead this should be done with try .. except to stay pythonic i guess..

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

Make a div into a link

This is the best way to do it as used on the BBC website and the Guardian:

I found the technique here: http://codepen.io/IschaGast/pen/Qjxpxo

heres the html

<div class="highlight block-link">
      <h2>I am an example header</h2>
      <p><a href="pageone" class="block-link__overlay-link">This entire box</a> links somewhere, thanks to faux block links. I am some example text with a <a href="pagetwo">custom link</a> that sits within the block</p>

</div>

heres the CSS

/**
 * Block Link
 *
 * A Faux block-level link. Used for when you need a block-level link with
 * clickable areas within it as directly nesting a tags breaks things.
 */


.block-link {
    position: relative;
}

.block-link a {
  position: relative;
  z-index: 1;
}

.block-link .block-link__overlay-link {
    position: static;
    &:before {
      bottom: 0;
      content: "";
      left: 0;
      overflow: hidden;
      position: absolute;
      right: 0;
      top: 0;
      white-space: nowrap;
      z-index: 0;
    }
    &:hover,
    &:focus {
      &:before {
        background: rgba(255,255,0, .2);
      }
    }
}

GridView - Show headers on empty data source

After posting this I did come up with a way that works. However, I don't feel it is the best way to handle this. Any suggestions on a better one?

//Check to see if we get rows back, if we do just bind.

if (dtFunding.Rows.Count != 0)
{
    grdFunding.DataSource = dtFunding;
    grdFunding.DataBind();
}
else
{
  //Other wise add a emtpy "New Row" to the datatable and then hide it after binding.

     dtFunding.Rows.Add(dtFunding.NewRow());
     grdFunding.DataSource = dtFunding;
     grdFunding.DataBind();
     grdFunding.Rows[0].Visible = false;
}

Can someone explain Microsoft Unity?

I just watched the 30 minute Unity Dependency Injection IoC Screencast by David Hayden and felt that was a good explaination with examples. Here is a snippet from the show notes:

The screencast shows several common usages of the Unity IoC, such as:

  • Creating Types Not In Container
  • Registering and Resolving TypeMappings
  • Registering and Resolving Named TypeMappings
  • Singletons, LifetimeManagers, and the ContainerControlledLifetimeManager
  • Registering Existing Instances
  • Injecting Dependencies into Existing Instances
  • Populating the UnityContainer via App.config / Web.config
  • Specifying Dependencies via Injection API as opposed to Dependency Attributes
  • Using Nested ( Parent-Child ) Containers

Convert a string into an int

Yet another way: if you are working with a C string, e.g. const char *, C native atoi() is more convenient.

How to convert String object to Boolean Object?

Boolean b = Boolean.valueOf(string);

The value of b is true if the string is not a null and equal to true (ignoring case).

Java Delegates?

While it is nowhere nearly as clean, but you could implement something like C# delegates using a Java Proxy.

How to check if a query string value is present via JavaScript?

You could also use a regular expression:

/[?&]q=/.test(location.search)

How do I parse an ISO 8601-formatted date?

In these days, Arrow also can be used as a third-party solution:

>>> import arrow
>>> date = arrow.get("2008-09-03T20:56:35.450686Z")
>>> date.datetime
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())

Explaining Apache ZooKeeper

I understand the ZooKeeper in general but had problems with the terms "quorum" and "split brain" so maybe I can share my findings with you (I consider myself also a layman).

Let's say we have a ZooKeeper cluster of 5 servers. One of the servers will become the leader and the others will become followers.

  • These 5 servers form a quorum. Quorum simply means "these servers can vote upon who should be the leader".

  • So the voting is based on majority. Majority simply means "more than half" so more than half of the number of servers must agree for a specific server to become the leader.

  • So there is this bad thing that may happen called "split brain". A split brain is simply this, as far as I understand: The cluster of 5 servers splits into two parts, or let's call it "server teams", with maybe one part of 2 and the other of 3 servers. This is really a bad situation as if both "server teams" must execute a specific order how would you decide wich team should be preferred? They might have received different information from the clients. So it is really important to know what "server team" is still relevant and which one can/should be ignored.

  • Majority is also the reason you should use an odd number of servers. If you have 4 servers and a split brain where 2 servers seperate then both "server teams" could say "hey, we want to decide who is the leader!" but how should you decide which 2 servers you should choose? With 5 servers it's simple: The server team with 3 servers has the majority and is allowed to select the new leader.

  • Even if you just have 3 servers and one of them fails the other 2 still form the majority and can agree that one of them will become the new leader.

I realize once you think about it some time and understand the terms it's not so complicated anymore. I hope this also helps anyone in understanding these terms.

Install a Windows service using a Windows command prompt?

Open Visual studio and select new project by selecting Windows Service template in Windows Desktop tab. Than copy following code into your service_name.cs file.

using System.Diagnostics;
using System.ServiceProcess;
namespace TimerService
{
    public partial class Timer_Service : ServiceBase
    {
        public Timer_Service()
        {
            InitializeComponent();
        }
        static void Main()
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Timer_Service service = new Timer_Service();
                service.OnStart(null);
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new Timer_Service()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
        protected override void OnStart(string[] args)
        {
            EventLog.WriteEvent("Timer_Service", new EventInstance(0, 0, EventLogEntryType.Information), new string[] { "Service start successfully." });
        }
        protected override void OnStop()
        {            
            EventLog.WriteEvent("Timer_Service", new EventInstance(0, 0, EventLogEntryType.Information), new string[] { "Service stop successfully." });
        }
    }
}

Right-Click on service_name.cs file and open designer of service. than right-click and select Add Installer. than right-click on serviceProcessInstaller1 and change its property value of Account from User to Local System.

Remove static void main method from Program.cs file. Than save and Build your project.

NOTE: goto bin\Ddebug folder of your project folder. Than open Properties of your service_name.exe file. Than goto Compatibility tab. Than click on Change Settings For All Users.

Select option Run this program as an administrator.

Now, You have to open CommandPromt as Administrator. After open, set directory to where your InstallUtil.exe file is placed. for ex: C:\Windows\Microsoft.NET\Framework64\v4.0.30319. now write the following command:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>InstallUtil.exe -i C:\TimerService\TimerService\bin\Debug\TimerService.exe

Note: -i is for install he service and -u for Unsinstall.

after -i set the write the path where you want to install your service.

now write the command in CommandPromt as follows:

C:\TimerService\TimerService\bin\Debug>net start service_name

Note: use stop for stop the Service.

Now, open ViewEventLog.exe. Select Windows Logs>Application. There you can check your Service's log by start and stop the service.

How do I deal with installing peer dependencies in Angular CLI?

Peer dependency warnings, more often than not, can be ignored. The only time you will want to take action is if the peer dependency is missing entirely, or if the version of a peer dependency is higher than the version you have installed.

Let's take this warning as an example:

npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself.

With Angular, you would like the versions you are using to be consistent across all packages. If there are any incompatible versions, change the versions in your package.json, and run npm install so they are all synced up. I tend to keep my versions for Angular at the latest version, but you will need to make sure your versions are consistent for whatever version of Angular you require (which may not be the most recent).

In a situation like this:

npm WARN [email protected] requires a peer of @angular/core@^2.4.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.

If you are working with a version of Angular that is higher than 4.0.0, then you will likely have no issues. Nothing to do about this one then. If you are using an Angular version under 2.4.0, then you need to bring your version up. Update the package.json, and run npm install, or run npm install for the specific version you need. Like this:

npm install @angular/[email protected] --save

You can leave out the --save if you are running npm 5.0.0 or higher, that version saves the package in the dependencies section of the package.json automatically.

In this situation:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

You are running Windows, and fsevent requires OSX. This warning can be ignored.

Hope this helps, and have fun learning Angular!

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

You never named your submit button, so as far as the form is concerned it's just an action.

Either:

  1. Name the submit button (<input type="submit" name="submit" ... />)
  2. Test if (!empty($_POST)) instead to detect when data has been posted.

Remember that keys in the $_POST superglobal only appear for named input elements. So, unless the element has the name attribute, it won't come through to $_POST (or $_GET/$_REQUEST)

Is it possible to get all arguments of a function as single object inside that function?

In ES6, use Array.from:

function foo()
  {
  foo.bar = Array.from(arguments);
  foo.baz = foo.bar.join();
  }

foo(1,2,3,4,5,6,7);
foo.bar // Array [1, 2, 3, 4, 5, 6, 7]
foo.baz // "1,2,3,4,5,6,7"

For non-ES6 code, use JSON.stringify and JSON.parse:

function foo()
  {
  foo.bar = JSON.stringify(arguments); 
  foo.baz = JSON.parse(foo.bar); 
  }

/* Atomic Data */
foo(1,2,3,4,5,6,7);
foo.bar // "{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7}"
foo.baz // [object Object]

/* Structured Data */
foo({1:2},[3,4],/5,6/,Date())
foo.bar //"{"0":{"1":2},"1":[3,4],"2":{},"3":"Tue Dec 17 2013 16:25:44 GMT-0800 (Pacific Standard Time)"}"
foo.baz // [object Object]

If preservation is needed instead of stringification, use the internal structured cloning algorithm.

If DOM nodes are passed, use XMLSerializer as in an unrelated question.

with (new XMLSerializer()) {serializeToString(document.documentElement) }

If running as a bookmarklet, you may need to wrap the each structured data argument in an Error constructor for JSON.stringify to work properly.

References

How do I update a formula with Homebrew?

I prefer to upgrade all homebrew formulae and homebrew cask formulae.

I added a Bourne shell function to my environment for this one (I load a .bashrc)

function updatebrew() {
set -x;
brew update;
brew cleanup;
brew cask upgrade --greedy
)
}
  • set -x for transparency: So that the terminal outputs whatever Homebrew is doing in the background.
  • brew update to update homebrew formulas
  • brew cleanup to remove any change left over after installations
  • brew cask upgrade --greedy will install all casks; both those with versioning information and those without

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

You can easily use Node.JS in your web app only for real-time communication. Node.JS is really powerful when it's about WebSockets. Therefore "PHP Notifications via Node.js" would be a great concept.

See this example: Creating a Real-Time Chat App with PHP and Node.js

Finding the indices of matching elements in list in Python

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

Get names of all keys in the collection

If you are using mongodb 3.4.4 and above then you can use below aggregation using $objectToArray and $group aggregation

db.collection.aggregate([
  { "$project": {
    "data": { "$objectToArray": "$$ROOT" }
  }},
  { "$project": { "data": "$data.k" }},
  { "$unwind": "$data" },
  { "$group": {
    "_id": null,
    "keys": { "$addToSet": "$data" }
  }}
])

Here is the working example

Simplest/cleanest way to implement a singleton in JavaScript

For me the cleanest way to do so is:

const singleton = new class {
    name = "foo"
    constructor() {
        console.log(`Singleton ${this.name} constructed`)
    }
}

With this syntax you are certain your singleton is and will remain unique. You can also enjoy the sugarness of class syntax and use this as expected.

(Note that class fields require node v12+ or a modern browser.)

ImportError: No module named PyQt4

If you're using Anaconda to manage Python on your system, you can install it with:

$ conda install pyqt=4

Omit the =4 to install the most current version.

Answer from How to install PyQt4 in anaconda?

How do I find the maximum of 2 numbers?

(num1>=num2)*num1+(num2>num1)*num2 will return the maximum of two values.

MySQL default datetime through phpmyadmin

You can't set CURRENT_TIMESTAMP as default value with DATETIME.

But you can do it with TIMESTAMP.

See the difference here.

Words from this blog

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.

How can I get Git to follow symlinks?

Use hard links instead. This differs from a soft (symbolic) link. All programs, including git will treat the file as a regular file. Note that the contents can be modified by changing either the source or the destination.

On macOS (before 10.13 High Sierra)

If you already have git and Xcode installed, install hardlink. It's a microscopic tool to create hard links.

To create the hard link, simply:

hln source destination

macOS High Sierra update

Does Apple File System support directory hard links?

Directory hard links are not supported by Apple File System. All directory hard links are converted to symbolic links or aliases when you convert from HFS+ to APFS volume formats on macOS.

From APFS FAQ on developer.apple.com

Follow https://github.com/selkhateeb/hardlink/issues/31 for future alternatives.

On Linux and other Unix flavors

The ln command can make hard links:

ln source destination

On Windows (Vista, 7, 8, …)

Use mklink to create a junction on Windows:

mklink /j "source" "destination"

Firing events on CSS class changes in jQuery

IMHO the better solution is to combine two answers by @RamboNo5 and @Jason

I mean overridding addClass function and adding a custom event called cssClassChanged

// Create a closure
(function(){
    // Your base, I'm in it!
    var originalAddClassMethod = jQuery.fn.addClass;

    jQuery.fn.addClass = function(){
        // Execute the original method.
        var result = originalAddClassMethod.apply( this, arguments );

        // trigger a custom event
        jQuery(this).trigger('cssClassChanged');

        // return the original result
        return result;
    }
})();

// document ready function
$(function(){
    $("#YourExampleElementID").bind('cssClassChanged', function(){ 
        //do stuff here
    });
});

what are the .map files used for in Bootstrap 3.x?

From Working with CSS preprocessors in Chrome DevTools:

Many developers generate CSS style sheets using a CSS preprocessor, such as Sass, Less, or Stylus. Because the CSS files are generated, editing the CSS files directly is not as helpful.

For preprocessors that support CSS source maps, DevTools lets you live-edit your preprocessor source files in the Sources panel, and view the results without having to leave DevTools or refresh the page. When you inspect an element whose styles are provided by a generated CSS file, the Elements panel displays a link to the original source file, not the generated .css file.

How do write IF ELSE statement in a MySQL query

You probably want to use a CASE expression.

They look like this:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

C# ASP.NET Single Sign-On Implementation

There are several Identity providers with SSO support out of the box, also third-party** products.

** The only problem with third party products is that they charge per user/month, and it can be quite expensive.

Some of the tools available and with APIs for .NET are:

If you decide to go with your own implementation, you could use the frameworks below categorized by programming language.

  • C#

    • IdentityServer3 (OAuth/OpenID protocols, OWIN/Katana)
    • IdentityServer4 (OAuth/OpenID protocols, ASP.NET Core)
    • OAuth 2.0 by Okta
  • Javascript

    • passport-openidconnect (node.js)
    • oidc-provider (node.js)
    • openid-client (node.js)
  • Python

    • pyoidc
    • Django OIDC Provider

I would go with IdentityServer4 and ASP.NET Core application, it's easy configurable and you can also add your own authentication provider. It uses OAuth/OpenID protocols which are newer than SAML 2.0 and WS-Federation.

.attr("disabled", "disabled") issue

To add disabled attribute

$('#id').attr("disabled", "true");

To remove Disabled Attribute

$('#id').removeAttr('disabled');

How to remove CocoaPods from a project?

Removing CocoaPods from a project is possible, but not currently automated by the CLI. First thing, if the only issue you have is not being able to use an xcworkspace you can use CocoaPods with just xcodeprojs by using the --no-integrate flag which will produce the Pods.xcodeproj but not a workspace. Then you can add this xcodeproj as a subproject to your main xcodeproj.

If you really want to remove all CocoaPods integration you need to do a few things:

NOTE editing some of these things if done incorrectly could break your main project. I strongly encourage you to check your projects into source control just in case. Also these instructions are for CocoaPods version 0.39.0, they could change with new versions.

  1. Delete the standalone files (Podfile Podfile.lock and your Pods directory)
  2. Delete the generated xcworkspace
  3. Open your xcodeproj file, delete the references to Pods.xcconfig and libPods.a (in the Frameworks group)
  4. Under your Build Phases delete the Copy Pods Resources, Embed Pods Frameworks and Check Pods Manifest.lock phases.
  5. This may seem obvious but you'll need to integrate the 3rd party libraries some other way or remove references to them from your code.

After those steps you should be set with a single xcodeproj that existed before you integrated CocoaPods. If I missed anything let me know and I will edit this.

Also we're always looking for suggestions for how to improve CocoaPods so if you have an issues please submit them in our issue tracker so we can come up with a way to fix them!

EDIT

As shown by Jack Wu in the comments there is a third party CocoaPods plugin that can automate these steps for you. It can be found here. Note that it is a third party plugin and might not always be updated when CocoaPods is. Also note that it is made by a CocoaPods core team member so that problem won't be a problem.

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

I had the same issue because of an incorrect product sku.

I was using android.test.purchase instead of android.test.purchased.

SQL - How to select a row having a column with max value

Answer is to add a having clause:

SELECT [columns]
FROM table t1
WHERE value= (select max(value) from table)
AND date = (select MIN(date) from table t2 where t1.value = t2.value)

this should work and gets rid of the neccesity of having an extra sub select in the date clause.

How could I create a function with a completion handler in Swift?

Swift 5.0 + , Simple and Short

example:

Style 1

    func methodName(completionBlock: () -> Void)  {

          print("block_Completion")
          completionBlock()
    }

Style 2

    func methodName(completionBlock: () -> ())  {

        print("block_Completion")
        completionBlock()
    }

Use:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        methodName {

            print("Doing something after Block_Completion!!")
        }
    }

Output

block_Completion

Doing something after Block_Completion!!

What is the best way to seed a database in Rails?

factory_bot sounds like it will do what you are trying to achieve. You can define all the common attributes in the default definition and then override them at creation time. You can also pass an id to the factory:

Factory.define :theme do |t|
  t.background_color '0x000000'
  t.title_text_color '0x000000',
  t.component_theme_color '0x000000'
  t.carrier_select_color '0x000000'
  t.label_text_color '0x000000',
  t.join_upper_gradient '0x000000'
  t.join_lower_gradient '0x000000'
  t.join_text_color '0x000000',
  t.cancel_link_color '0x000000'
  t.border_color '0x000000'
  t.carrier_text_color '0x000000'
  t.public true
end

Factory(:theme, :id => 1, :name => "Lite", :background_color => '0xC7FFD5')
Factory(:theme, :id => 2, :name => "Metallic", :background_color => '0xC7FFD5')
Factory(:theme, :id => 3, :name => "Blues", :background_color => '0x0060EC')

When used with faker it can populate a database really quickly with associations without having to mess about with Fixtures (yuck).

I have code like this in a rake task.

100.times do
    Factory(:company, :address => Factory(:address), :employees => [Factory(:employee)])
end

Spring get current ApplicationContext

Step 1 :Inject following code in class

@Autowired
private ApplicationContext _applicationContext;

Step 2 : Write Getter & Setter

Step 3: define autowire="byType" in xml file in which bean is defined

set environment variable in python script

Compact solution (provided you don't need other environment variables):

call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
      env=dict(LD_LIBRARY_PATH=my_path))

Using the env command line tool:

call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())

Vue.js—Difference between v-model and v-bind

In simple words v-model is for two way bindings means: if you change input value, the bound data will be changed and vice versa.

but v-bind:value is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.

check out this simple example: https://jsfiddle.net/gs0kphvc/

jQuery send HTML data through POST

If you want to send an arbitrary amount of data to your server, POST is the only reliable method to do that. GET would also be possible but clients and servers allow just a limited URL length (something like 2048 characters).

Label encoding across multiple columns in scikit-learn

Following up on the comments raised on the solution of @PriceHardman I would propose the following version of the class:

class LabelEncodingColoumns(BaseEstimator, TransformerMixin):
def __init__(self, cols=None):
    pdu._is_cols_input_valid(cols)
    self.cols = cols
    self.les = {col: LabelEncoder() for col in cols}
    self._is_fitted = False

def transform(self, df, **transform_params):
    """
    Scaling ``cols`` of ``df`` using the fitting

    Parameters
    ----------
    df : DataFrame
        DataFrame to be preprocessed
    """
    if not self._is_fitted:
        raise NotFittedError("Fitting was not preformed")
    pdu._is_cols_subset_of_df_cols(self.cols, df)

    df = df.copy()

    label_enc_dict = {}
    for col in self.cols:
        label_enc_dict[col] = self.les[col].transform(df[col])

    labelenc_cols = pd.DataFrame(label_enc_dict,
        # The index of the resulting DataFrame should be assigned and
        # equal to the one of the original DataFrame. Otherwise, upon
        # concatenation NaNs will be introduced.
        index=df.index
    )

    for col in self.cols:
        df[col] = labelenc_cols[col]
    return df

def fit(self, df, y=None, **fit_params):
    """
    Fitting the preprocessing

    Parameters
    ----------
    df : DataFrame
        Data to use for fitting.
        In many cases, should be ``X_train``.
    """
    pdu._is_cols_subset_of_df_cols(self.cols, df)
    for col in self.cols:
        self.les[col].fit(df[col])
    self._is_fitted = True
    return self

This class fits the encoder on the training set and uses the fitted version when transforming. Initial version of the code can be found here.

Windows Scipy Install: No Lapack/Blas Resources Found

Sorry to necro, but this is the first google search result. This is the solution that worked for me:

  1. Download numpy+mkl wheel from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy. Use the version that is the same as your python version (check using python -V). Eg. if your python is 3.5.2, download the wheel which shows cp35

  2. Open command prompt and navigate to the folder where you downloaded the wheel. Run the command: pip install [file name of wheel]

  3. Download the SciPy wheel from: http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy (similar to the step above).

  4. As above, pip install [file name of wheel]

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.

<LimitExcept OPTIONS>
    AuthType Basic
    AuthName <AUTH_NAME>
    Require valid-user
    AuthUserFile <FILE_PATH>
</LimitExcept>