Programs & Examples On #Sound recognition

How to get bitmap from a url in android?

Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:

File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);

getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.

How to read a text-file resource into Java unit test?

You can use a Junit Rule to create this temporary folder for your test:

@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); File file = temporaryFolder.newFile(".src/test/resources/abc.xml");

How do I directly modify a Google Chrome Extension File? (.CRX)

Note that some zip programs have trouble unzipping a CRX like sathish described - if this is the case, try using 7-Zip - http://www.7-zip.org/

How to use the DropDownList's SelectedIndexChanged event

I think this is the culprit:

cmd = new SqlCommand(query, con);

DataTable dt = Select(query);

cmd.ExecuteNonQuery();

ddtype.DataSource = dt;

I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":

cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();

Or you can create a DataTable as explained here:

cmd = new SqlCommand(query, con);

SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);

ddtype.DataSource = listTable;

How to debug "ImagePullBackOff"?

I forgot to push the image tagged 1.0.8 to the ECR (AWS images hub)... If you are using Helm and upgrade by:

helm upgrade minta-user ./src/services/user/helm-chart

make sure that image tag inside values.yaml is pushed (to ECR or Docker Hub, etc) for example: (this is my helm-chart/values.yaml)

replicaCount: 1

image:
   repository:dkr.ecr.us-east-1.amazonaws.com/minta-user
   tag: 1.0.8

you need to make sure that the image:1.0.8 is pushed!

How to pass form input value to php function

No, the action should be the name of php file. With on click you may only call JavaScript. And please be aware the hiding your code from the user undermines trust. JS runs on the browser so some trust is needed.

Div table-cell vertical align not working

Sometime floats brake the vertical align, is better to avoid them.

How to print something to the console in Xcode?

In some environments, NSLog() will be unresponsive. But there are other ways to get output...

NSString* url = @"someurlstring";
printf("%s", [url UTF8String]);

By using printf with the appropriate parameters, we can display things this way. This is the only way I have found to work on online Objective-C sandbox environments.

What is the ultimate postal code and zip regex?

If someone is still interested in how to validate zip codes I've found a solution:

Using Google Geocoding API we can check validity of ZIP code having both Country code and a ZIP code itself.

For example I live in Ukraine so I can check like this: https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:80380|country:UA

Or using JS API: https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering

Where 80380 is valid ZIP for Ukraine, actually every (#####) is valid.

Google returns ZERO_RESULTS status if nothing found. Or OK and a result if both are correct.

Hope this will be helpful.

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

LINQ Aggregate algorithm explained

A short and essential definition might be this: Linq Aggregate extension method allows to declare a sort of recursive function applied on the elements of a list, the operands of whom are two: the elements in the order in which they are present into the list, one element at a time, and the result of the previous recursive iteration or nothing if not yet recursion.

In this way you can compute the factorial of numbers, or concatenate strings.

Git pull after forced update

Pull with rebase

A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull command:

git pull --rebase

Download the Android SDK components for offline install

This has changed for android 4.4.2. .. you should look in the repository file and download https://dl-ssl.google.com/android/repository/repository-10.xml

  1. android-sdk_r20.0.1-windows.zip ( I think that is actually windows specific tools)
  2. android-19_r03.zip for all platform ( actual api) and store under platforms in #1

In manual install dir structure should look like

Now you have to..

  1. download win SDK helper ( avd/SDK magr): https://dl.google.com/android/android-sdk_r20.0.1-windows.zip
  2. actual sdk api https://dl-ssl.google.com/android/repository/android-20_r01.zip
  3. samples https://dl-ssl.google.com/android/repository/samples-19_r05.zip
  4. images : https://dl-ssl.google.com/android/repository/sys-img/x86/sys-img.xml e.g. https://dl-ssl.google.com/android/repository/sysimg_armv7a-18_r02.zip extract in : “Platforms > Android-4.4.2>"
  5. platform-tools: https://dl-ssl.google.com/android/repository/platform-tools_r19.0.1-windows.zip
  6. build-tools: create folder (build-tools at main sdk level) https://dl-ssl.google.com/android/repository/build-tools_r17-windows.zip
  7. copy aapt.exe, aidl.exe and dr.bat to platform-tools folder.
  8. you may download tools as well same way
  9. source: https://dl-ssl.google.com/android/repository/sources-19_r02.zip

At this point you should have a working android installation.

Can you have multiple $(document).ready(function(){ ... }); sections?

You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:

http://www.learningjquery.com/2006/09/multiple-document-ready

Try this out:

$(document).ready(function() {
    alert('Hello Tom!');
});

$(document).ready(function() {
    alert('Hello Jeff!');
});

$(document).ready(function() {
    alert('Hello Dexter!');
});

You'll find that it's equivalent to this, note the order of execution:

$(document).ready(function() {
    alert('Hello Tom!');
    alert('Hello Jeff!');
    alert('Hello Dexter!');
});

It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block, I just ran this test:

$(document).ready(function() {
    alert('hello1');
    function saySomething() {
        alert('something');
    }
    saySomething();

});
$(document).ready(function() {
    alert('hello2');
    saySomething();
}); 

output was:

hello1
something
hello2

jQuery: read text file from file system

This is working fine in firefox at least.

The problem I was facing is, that I got an XML object in stead of a plain text string. Reading an xml-file from my local drive works fine (same directory as the html), so I do not see why reading a text file would be an issue.

I figured that I need to tell jquery to pass a string in stead of an XML object. Which is what I did, and it finally worked:

function readFiles()
{
    $.get('file.txt', function(data) {
        alert(data);
    }, "text");
}

Note the addition of '"text"' at the end. This tells jquery to pass the contents of 'file.txt' as a string in stead of an XML object. The alert box will show the contents of the text file. If you remove the '"text"' at the end, the alert box will say 'XML object'.

How do I trim leading/trailing whitespace in a standard way?

A bit late to the game, but I'll throw my routines into the fray. They're probably not the most absolute efficient, but I believe they're correct and they're simple (with rtrim() pushing the complexity envelope):

#include <ctype.h>
#include <string.h>

/*
    Public domain implementations of in-place string trim functions

    Michael Burr
    [email protected]
    2010
*/

char* ltrim(char* s) 
{
    char* newstart = s;

    while (isspace( *newstart)) {
        ++newstart;
    }

    // newstart points to first non-whitespace char (which might be '\0')
    memmove( s, newstart, strlen( newstart) + 1); // don't forget to move the '\0' terminator

    return s;
}


char* rtrim( char* s)
{
    char* end = s + strlen( s);

    // find the last non-whitespace character
    while ((end != s) && isspace( *(end-1))) {
            --end;
    }

    // at this point either (end == s) and s is either empty or all whitespace
    //      so it needs to be made empty, or
    //      end points just past the last non-whitespace character (it might point
    //      at the '\0' terminator, in which case there's no problem writing
    //      another there).    
    *end = '\0';

    return s;
}

char*  trim( char* s)
{
    return rtrim( ltrim( s));
}

Property getters and setters

Update: Swift 4

In the below class setter and getter is applied to variable sideLength

class Triangle: {
    var sideLength: Double = 0.0

    init(sideLength: Double, name: String) { //initializer method
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 3
    }

    var perimeter: Double {
        get { // getter
            return 3.0 * sideLength
        }
        set(newValue) { //setter
            sideLength = newValue / 4.0
        }
   }

Creating object

var triangle = Triangle(sideLength: 3.9, name: "a triangle")

Getter

print(triangle.perimeter) // invoking getter

Setter

triangle.perimeter = 9.9 // invoking setter

Java program to find the largest & smallest number in n numbers without using arrays

Try the code mentioned below

public static void main(String[] args) {
    int smallest=0; int large=0; int num;
    System.out.println("enter the number");
    Scanner input=new Scanner(System.in);
    int n=input.nextInt();
    num=input.nextInt();
    smallest = num;
    for(int i=0;i<n-1;i++)
        {
            num=input.nextInt();
            if(num<smallest)
            {
                smallest=num;
            }
        }
        System.out.println("the smallest is:"+smallest);
}

How can I clear event subscriptions in C#?

Instead of adding and removing callbacks manually and having a bunch of delegate types declared everywhere:

// The hard way
public delegate void ObjectCallback(ObjectType broadcaster);

public class Object
{
    public event ObjectCallback m_ObjectCallback;
    
    void SetupListener()
    {
        ObjectCallback callback = null;
        callback = (ObjectType broadcaster) =>
        {
            // one time logic here
            broadcaster.m_ObjectCallback -= callback;
        };
        m_ObjectCallback += callback;

    }
    
    void BroadcastEvent()
    {
        m_ObjectCallback?.Invoke(this);
    }
}

You could try this generic approach:

public class Object
{
    public Broadcast<Object> m_EventToBroadcast = new Broadcast<Object>();

    void SetupListener()
    {
        m_EventToBroadcast.SubscribeOnce((ObjectType broadcaster) => {
            // one time logic here
        });
    }

    ~Object()
    {
        m_EventToBroadcast.Dispose();
        m_EventToBroadcast = null;
    }

    void BroadcastEvent()
    {
        m_EventToBroadcast.Broadcast(this);
    }
}


public delegate void ObjectDelegate<T>(T broadcaster);
public class Broadcast<T> : IDisposable
{
    private event ObjectDelegate<T> m_Event;
    private List<ObjectDelegate<T>> m_SingleSubscribers = new List<ObjectDelegate<T>>();

    ~Broadcast()
    {
        Dispose();
    }

    public void Dispose()
    {
        Clear();
        System.GC.SuppressFinalize(this);
    }

    public void Clear()
    {
        m_SingleSubscribers.Clear();
        m_Event = delegate { };
    }

    // add a one shot to this delegate that is removed after first broadcast
    public void SubscribeOnce(ObjectDelegate<T> del)
    {
        m_Event += del;
        m_SingleSubscribers.Add(del);
    }

    // add a recurring delegate that gets called each time
    public void Subscribe(ObjectDelegate<T> del)
    {
        m_Event += del;
    }

    public void Unsubscribe(ObjectDelegate<T> del)
    {
        m_Event -= del;
    }

    public void Broadcast(T broadcaster)
    {
        m_Event?.Invoke(broadcaster);
        for (int i = 0; i < m_SingleSubscribers.Count; ++i)
        {
            Unsubscribe(m_SingleSubscribers[i]);
        }
        m_SingleSubscribers.Clear();
    }
}

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Reading my own Jar's Manifest

You can use getProtectionDomain().getCodeSource() like this :

URL url = Menu.class.getProtectionDomain().getCodeSource().getLocation();
File file = DataUtilities.urlToFile(url);
JarFile jar = null;
try {
    jar = new JarFile(file);
    Manifest manifest = jar.getManifest();
    Attributes attributes = manifest.getMainAttributes();
    return attributes.getValue("Built-By");
} finally {
    jar.close();
}

Display back button on action bar

well this is simple one to show back button

actionBar.setDisplayHomeAsUpEnabled(true);

and then you can custom the back event at onOptionsItemSelected

case android.R.id.home:
this.finish();
return true;

Get current date in milliseconds

@JavaZava your solution is good, but if you want to have a 13 digit long value to be consistent with the time stamp formatting in Java or JavaScript (and other languages) use this method:

NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); // returned as a double
long digits = (long)time; // this is the first 10 digits
int decimalDigits = (int)(fmod(time, 1) * 1000); // this will get the 3 missing digits
long timestamp = (digits * 1000) + decimalDigits;

or (if you need a string):

NSString *timestampString = [NSString stringWithFormat:@"%ld%d",digits ,decimalDigits];

how to set the background color of the whole page in css

I've checked your source code and find to change to yellow you need to adds the yellow background color to : #left-padding, #right-padding, html, #hd, #main and #yui-main.

Hope it's what you wanted. See ya

enter image description here

How to iterate over a TreeMap?

    //create TreeMap instance
    TreeMap treeMap = new TreeMap();

    //add key value pairs to TreeMap
    treeMap.put("1","One");
    treeMap.put("2","Two");
    treeMap.put("3","Three");

    /*
      get Collection of values contained in TreeMap using
      Collection values()        
    */
    Collection c = treeMap.values();

    //obtain an Iterator for Collection
    Iterator itr = c.iterator();

    //iterate through TreeMap values iterator
    while(itr.hasNext())
      System.out.println(itr.next());

or:

   for (Map.Entry<K,V> entry : treeMap.entrySet()) {
        V value = entry.getValue();
        K key = entry.getKey();
   }

or:

   // Use iterator to display the keys and associated values
   System.out.println("Map Values Before: ");
   Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
     System.out.println(key + " = " + value);
   }

Laravel 5.1 API Enable Cors

I always use an easy method. Just add below lines to \public\index.php file. You don't have to use a middleware I think.

header('Access-Control-Allow-Origin: *');  
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

Fatal Error :1:1: Content is not allowed in prolog

The real solution that I found for this issue was by disabling any XML Format post processors. I have added a post processor called "jp@gc - XML Format Post Processor" and started noticing the error "Fatal Error :1:1: Content is not allowed in prolog"

By disabling the post processor had stopped throwing those errors.

Count rows with not empty value

=counta(range) 
  • counta: "Returns a count of the number of values in a dataset"

    Note: CountA considers "" to be a value. Only cells that are blank (press delete in a cell to blank it) are not counted.

    Google support: https://support.google.com/docs/answer/3093991

  • countblank: "Returns the number of empty cells in a given range"

    Note: CountBlank considers both blank cells (press delete to blank a cell) and cells that have a formula that returns "" to be empty cells.

    Google Support: https://support.google.com/docs/answer/3093403

If you have a range that includes formulae that result in "", then you can modify your formula from

=counta(range)

to:

=Counta(range) - Countblank(range)

EDIT: the function is countblank, not countblanks, the latter will give an error.

Detect encoding and make everything UTF-8

After sorting out your php scripts, don't forget to tell mysql what charset you are passing and would like to recceive.

Example: set character set utf8

Passing utf8 data to a latin1 table in a latin1 I/O session gives those nasty birdfeets. I see this every other day in oscommerce shops. Back and fourth it might seem right. But phpmyadmin will show the truth. By telling mysql what charset you are passing it will handle the conversion of mysql data for you.

How to recover existing scrambled mysql data is another thread to discuss. :)

How to iterate through table in Lua?

For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.

Examples:

ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}

notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable
1       AAA
2       BBB
3       CCC

ipairs + ipairsCompatable2
1       DDD
2       EEE
3       FFF

ipairs + ipairsCompatable3
1       this
2       does
3       work

ipairs + notIpairsCompatable

pairs + notIpairsCompatable
2       this
3       does
4       not

ipairs + notIpairsCompatable2

pairs + notIpairsCompatable2
2       this
5       doesnt
24      either

ipairs + kindofIpairsCompatable
1       1
2       2
3       3

pairs + kindofIpairsCompatable
1       1
2       2
3       3
5       5
cool    bro

C: Run a System Command and Get Output?

Usually, if the command is an external program, you can use the OS to help you here.

command > file_output.txt

So your C code would be doing something like

exec("command > file_output.txt");

Then you can use the file_output.txt file.

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

TypeScript: Creating an empty typed container array

Okay you got the syntax wrong here, correct way to do this is:

var arr: Criminal[] = [];

I'm assuming you are using var so that means declaring it somewhere inside the func(),my suggestion would be use let instead of var.

If declaring it as c class property usse acces modifiers like private, public, protected.

Execute Insert command and return inserted Id in Sql

SQL Server stored procedure:

CREATE PROCEDURE [dbo].[INS_MEM_BASIC]
    @na varchar(50),
    @occ varchar(50),
    @New_MEM_BASIC_ID int OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO Mem_Basic
    VALUES (@na, @occ)

    SELECT @New_MEM_BASIC_ID = SCOPE_IDENTITY()
END

C# code:

public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
    // values 0 --> -99 are SQL reserved.
    int new_MEM_BASIC_ID = -1971;   
    SqlConnection SQLconn = new SqlConnection(Config.ConnectionString);
    SqlCommand cmd = new SqlCommand("INS_MEM_BASIC", SQLconn);

    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter outPutVal = new SqlParameter("@New_MEM_BASIC_ID", SqlDbType.Int);

    outPutVal.Direction = ParameterDirection.Output;
    cmd.Parameters.Add(outPutVal);
    cmd.Parameters.Add("@na", SqlDbType.Int).Value = Mem_NA;
    cmd.Parameters.Add("@occ", SqlDbType.Int).Value = Mem_Occ;

    SQLconn.Open();
    cmd.ExecuteNonQuery();
    SQLconn.Close();

    if (outPutVal.Value != DBNull.Value) new_MEM_BASIC_ID = Convert.ToInt32(outPutVal.Value);
        return new_MEM_BASIC_ID;
}

I hope these will help to you ....

You can also use this if you want ...

public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
    using (SqlConnection con=new SqlConnection(Config.ConnectionString))
    {
        int newID;
        var cmd = "INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT CAST(scope_identity() AS int)";

        using(SqlCommand cmd=new SqlCommand(cmd, con))
        {
            cmd.Parameters.AddWithValue("@na", Mem_NA);
            cmd.Parameters.AddWithValue("@occ", Mem_Occ);

            con.Open();
            newID = (int)insertCommand.ExecuteScalar();

            if (con.State == System.Data.ConnectionState.Open) con.Close();
                return newID;
        }
    }
}

converting multiple columns from character to numeric format in r

like this?

DF <- data.frame("a" = as.character(0:5),
             "b" = paste(0:5, ".1", sep = ""),
             "c" = paste(10:15),
             stringsAsFactors = FALSE)

DF <- apply(DF, 2, as.numeric)

If there are "real" characters in dataframe like 'a' 'b' 'c', i would recommend answer from davsjob.

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

Use Robocopy to copy only changed files?

You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.

This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.

Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.

backup-robocopy.bat

@REM https://technet.microsoft.com/en-us/library/cc733145.aspx
@REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx

set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt

set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW  cmd.exe /C %basedir%backup-robocopy-movemouse.bat

set dest=E:\backup

call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"

:SPLIT
@REM Split +4GB file to multiple files to support FAT32 destination disk,
@REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
  IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
  dir /b /aa "%srcfile%" && (
    del /Q "%dstfile2%.7z.*"
    c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z"  "%srcfile%"
    attrib -A "%srcfile%"
    @set dt=%date%_%time:~0,8%
    @echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
  )
)

del /Q %basedir%backup-robocopy-lock.txt
GOTO :END


:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF


:END
@set dt=%date%_%time:~0,8%
@echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
@echo %dt% robocopy completed
@pause

backup-robocopy-job.rcj

:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj


:: Source Directory (this is given in command line)
::/SD:c:\examplefolder

:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder

:: Include files matching these names
/IF
    *.*

/M      :: copy only files with the Archive attribute and reset it.
/XJD    :: eXclude Junction points for Directories.

:: Exclude Directories
/XD
    C:\projects\bak
    C:\projects\old
    C:\project\tomcat\logs
    C:\project\tomcat\work
    C:\Users\Myname\.eclipse
    C:\Users\Myname\.m2
    C:\Users\Myname\.thumbnails
    C:\Users\Myname\AppData
    C:\Users\Myname\Favorites
    C:\Users\Myname\Links
    C:\Users\Myname\Saved Games
    C:\Users\Myname\Searches

:: Exclude files matching these names
/XF 
    C:\Users\Myname\ntuser.dat  
    *.~bpl

:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH      

:: Copy options
/S          :: copy Subdirectories, but not empty ones.
/E          :: copy subdirectories, including Empty ones.
/COPY:DAT   :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T    :: COPY Directory Timestamps.
/PURGE      :: delete dest files/dirs that no longer exist in source.

:: Retry Options
/R:0        :: number of Retries on failed copies: default 1 million.
/W:1        :: Wait time between retries: default is 30 seconds.

:: Logging Options (LOG+ append)
/NDL        :: No Directory List - don't log directory names.
/NP         :: No Progress - don't display percentage copied.
/TEE        :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile

backup-robocopy-movemouse.bat

@echo off
@REM Move mouse to prevent maching from sleeping 
@rem while running a backup script

echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.

set basedir=%~dp0
set IDX=0

:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
  SET IDX=0
  echo Move mouse to keep system awake
  c:\apps\commands\nircmdc.exe sendmouse move 5 5
  c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP

What is C# equivalent of <map> in C++?

.NET Framework provides many collection classes too. You can use Dictionary in C#. Please find the below msdn link for details and samples http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

How to insert a blob into a database using sql server management studio

MSDN has an article Working With Large Value Types, which tries to explain how the import parts work, but it can get a bit confusing since it does 2 things simultaneously.

Here I am providing a simplified version, broken into 2 parts. Assume the following simple table:

CREATE TABLE [Thumbnail](
   [Id]        [int] IDENTITY(1,1) NOT NULL,
   [Data]      [varbinary](max) NULL
CONSTRAINT [PK_Thumbnail] PRIMARY KEY CLUSTERED 
(
[Id] ASC
) ) ON [PRIMARY]

If you run (in SSMS):

SELECT * FROM OPENROWSET (BULK 'C:\Test\TestPic1.jpg', SINGLE_BLOB) AS X

it will show, that the result looks like a table with one column named BulkColumn. That's why you can use it in INSERT like:

INSERT [Thumbnail] ( Data )
SELECT * FROM OPENROWSET (BULK 'C:\Test\TestPic1.jpg', SINGLE_BLOB) AS X

The rest is just fitting it into an insert with more columns, which your table may or may not have. If you name the result of that select FOO then you can use SELECT Foo.BulkColumn and as after that constants for other fields in your table.

The part that can get more tricky is how to export that data back into a file so you can check that it's still OK. If you run it on cmd line:

bcp "select Data from B2B.dbo.Thumbnail where Id=1" 
queryout D:\T\TestImage1_out2.dds -T -L 1 

It's going to start whining for 4 additional "params" and will give misleading defaults (which will result in a changed file). You can accept the first one, set the 2nd to 0 and then assept 3rd and 4th, or to be explicit:

Enter the file storage type of field Data [varbinary(max)]:
Enter prefix-length of field Data [8]: 0
Enter length of field Data [0]:
Enter field terminator [none]:

Then it will ask:

Do you want to save this format information in a file? [Y/n] y
Host filename [bcp.fmt]: C:\Test\bcp_2.fmt

Next time you have to run it add -f C:\Test\bcp_2.fmt and it will stop whining :-) Saves a lot of time and grief.

Default value of function parameter

If you put the declaration in a header file, and the definition in a separate .cpp file, and #include the header from a different .cpp file, you will be able to see the difference.

Specifically, suppose:

lib.h

int Add(int a, int b);

lib.cpp

int Add(int a, int b = 3) {
   ...
}

test.cpp

#include "lib.h"

int main() {
    Add(4);
}

The compilation of test.cpp will not see the default parameter declaration, and will fail with an error.

For this reason, the default parameter definition is usually specified in the function declaration:

lib.h

int Add(int a, int b = 3);

Getting Error "Form submission canceled because the form is not connected"

You must ensure that the form is in the document. You can append the form to the body.

Class Diagrams in VS 2017

VS 2017 Professional edition- Go to Quick launch type "Class..." select Class designer and install it.

Once installed go to Add New Items search "Class Diagram" and you are ready to go.

What is difference between sleep() method and yield() method of multi threading?

One way to request the current thread to relinquish CPU so that other threads can get a chance to execute is to use yield in Java.

yield is a static method. It doesn't say which other thread will get the CPU. It is possible for the same thread to get back the CPU and start its execution again.

public class Solution9  {

public static void main(String[] args) {
        yclass yy = new yclass ();
        Thread t1= new Thread(yy);
        t1.start();
        for (int i = 0; i <3; i++) {
            Thread.yield();
            System.out.println("during yield control => " + Thread.currentThread().getName());
        }
    }
}

class yclass implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println("control => " + Thread.currentThread().getName());
        }
    }
}

Lookup City and State by Zip Google Geocode Api

I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.

Using the US Postal Service HTTP/XML API

According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.

According to their documentation, here's what you would send:

http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>

And here's what you would receive back:

<?xml version="1.0"?> 
<CityStateLookupResponse> 
    <ZipCode ID="0"> 
        <Zip5>90210</Zip5> 
        <City>BEVERLY HILLS</City> 
        <State>CA</State> 
    </ZipCode> 
</CityStateLookupResponse>

USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.

Using the Ziptastic HTTP/JSON API (no longer supported)

Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here

This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:

GET http://ziptasticapi.com/48867

And they will return a JSON object along the lines of:

{"country": "US", "state": "MI", "city": "OWOSSO"}

Indeed, it works. You can test this from a command line by doing something like:

curl http://ziptasticapi.com/48867 

String length in bytes in JavaScript

You can try this:

function getLengthInBytes(str) {
  var b = str.match(/[^\x00-\xff]/g);
  return (str.length + (!b ? 0: b.length)); 
}

It works for me.

How do I install a plugin for vim?

Make sure that the actual .vim file is in ~/.vim/plugin/

Which is faster: Stack allocation or Heap allocation

Never do premature assumption as other application code and usage can impact your function. So looking at function is isolation is of no use.

If you are serious with application then VTune it or use any similar profiling tool and look at hotspots.

Ketan

Giving UIView rounded corners

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 50, 200, 200)];

view.layer.backgroundColor = [UIColor whiteColor].CGColor;
view.layer.cornerRadius = 20.0;
view.layer.frame = CGRectInset(v.layer.frame, 20, 20);

view.layer.shadowOffset = CGSizeMake(1, 0);
view.layer.shadowColor = [[UIColor blackColor] CGColor];
view.layer.shadowRadius = 5;
view.layer.shadowOpacity = .25;

[self.view addSubview:view];
[view release];

how to make a whole row in a table clickable as a link?

A very easy option is just use on-click, and more correct, in my point of view, because this separate the view and controller, and you don't need to hard code the URL or whatever more you need do accomplish with the click. It works with Angular ng-click too.

<table>
  <tr onclick="myFunction(this)">
    <td>Click to show rowIndex</td>
  </tr>
</table>

<script>
function myFunction(x) {
    alert("Row index is: " + x.rowIndex);
}
</script>

Exemple working here

What is ToString("N0") format?

It is a sort of format specifier for formatting numeric results. There are additional specifiers on the link.

What N does is that it separates numbers into thousand decimal places according to your CultureInfo and represents only 2 decimal digits in floating part as is N2 by rounding right-most digit if necessary.

N0 does not represent any decimal place but rounding is applied to it.

Let's exemplify.

using System;
using System.Globalization;


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x = 567892.98789;
            CultureInfo someCulture = new CultureInfo("da-DK", false);

            // 10 means left-padded = right-alignment
            Console.WriteLine(String.Format(someCulture, "{0:N} denmark", x));
            Console.WriteLine("{0,10:N} us", x); 

            // watch out rounding 567,893
            Console.WriteLine(String.Format(someCulture, "{0,10:N0}", x)); 
            Console.WriteLine("{0,10:N0}", x);

            Console.WriteLine(String.Format(someCulture, "{0,10:N5}", x));
            Console.WriteLine("{0,10:N5}", x);


            Console.ReadKey();

        }
    }
}

It yields,

567.892,99 denmark
567,892.99 us
   567.893
   567,893
567.892,98789
567,892.98789

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

mvc:annotation-driven is a tag added in Spring 3.0 which does the following:

  1. Configures the Spring 3 Type ConversionService (alternative to PropertyEditors)
  2. Adds support for formatting Number fields with @NumberFormat
  3. Adds support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath
  4. Adds support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath
  5. Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with @RequestBody/@ResponseBody)
  6. Adds support for reading and writing JSON, if Jackson is o n the classpath (along the same lines as #5)

context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.

How to calculate the sentence similarity using word2vec model of gensim with python

There is a function from the documentation taking a list of words and comparing their similarities.

s1 = 'This room is dirty'
s2 = 'dirty and disgusting room' #corrected variable name

distance = model.wv.n_similarity(s1.lower().split(), s2.lower().split())

How to capture a JFrame's close button click event?

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

also works. First create a JFrame called frame, then add this code underneath.

How can I sort one set of data to match another set of data in Excel?

You could also use INDEX MATCH, which is more "powerful" than vlookup. This would give you exactly what you are looking for:

enter image description here

Docker error : no space left on device

For me docker system prune did the trick. I`m running mac os.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Can I embed a .png image into an html page?

I don't know for how long this post has been here. But I stumbled upon similar problem now. Hence posting the solution so that it might help others.

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;

use GD::Graph::pie;
use MIME::Base64;
my @data = (['A','O','S','I'],[3,16,12,47]);

my $mygraph = GD::Graph::pie->new(200, 200);
my $myimage = $mygraph->plot(\@data)->png;

print <<end_html;
<html><head><title>Current Stats</title></head>
<body>
<p align="center">
<img src="data:image/png;base64,
end_html

print encode_base64($myimage);

print <<end_html;
" style="width: 888px; height: 598px; border-width: 2px; border-style: solid;" /></p>
</body>
</html>

end_html

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

Check for the status of the database:

service postgresql status

If the database is not running, start the db:

sudo service postgresql start

Angular 2 - innerHTML styling

The simple solution you need to follow is

import { DomSanitizer } from '@angular/platform-browser';

constructor(private sanitizer: DomSanitizer){}

transformYourHtml(htmlTextWithStyle) {
    return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
}

How can I represent an 'Enum' in Python?

Why must enumerations be ints? Unfortunately, I can't think of any good looking construct to produce this without changing the Python language, so I'll use strings:

class Enumerator(object):
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        if self.name == other:
            return True
        return self is other

    def __ne__(self, other):
        if self.name != other:
            return False
        return self is other

    def __repr__(self):
        return 'Enumerator({0})'.format(self.name)

    def __str__(self):
        return self.name

class Enum(object):
    def __init__(self, *enumerators):
        for e in enumerators:
            setattr(self, e, Enumerator(e))
    def __getitem__(self, key):
        return getattr(self, key)

Then again maybe it's even better now that we can naturally test against strings, for the sake of configuration files or other remote input.

Example:

class Cow(object):
    State = Enum(
        'standing',
        'walking',
        'eating',
        'mooing',
        'sleeping',
        'dead',
        'dying'
    )
    state = State.standing

In [1]: from enum import Enum

In [2]: c = Cow()

In [3]: c2 = Cow()

In [4]: c.state, c2.state
Out[4]: (Enumerator(standing), Enumerator(standing))

In [5]: c.state == c2.state
Out[5]: True

In [6]: c.State.mooing
Out[6]: Enumerator(mooing)

In [7]: c.State['mooing']
Out[7]: Enumerator(mooing)

In [8]: c.state = Cow.State.dead

In [9]: c.state == c2.state
Out[9]: False

In [10]: c.state == Cow.State.dead
Out[10]: True

In [11]: c.state == 'dead'
Out[11]: True

In [12]: c.state == Cow.State['dead']
Out[11]: True

What is the argument for printf that formats a long?

I think to answer this question definitively would require knowing the compiler name and version that you are using and the platform (CPU type, OS etc.) that it is compiling for.

Android Layout Weight

<LinearLayout
    android:id="@+id/linear1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="9"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/ring_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/ring_oss" />

    <ImageView
        android:id="@+id/maila_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
<EditText
        android:id="@+id/edittxt"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
</LinearLayout>

Recommendation for compressing JPG files with ImageMagick

Here's a complete solution for those using Imagick in PHP:

$im = new \Imagick($filePath);
$im->setImageCompression(\Imagick::COMPRESSION_JPEG);
$im->setImageCompressionQuality(85);
$im->stripImage();
$im->setInterlaceScheme(\Imagick::INTERLACE_PLANE);

// Try between 0 or 5 radius. If you find radius of 5 
// produces too blurry  pictures decrease to 0 until you 
// find a good balance between size and quality. 
$im->gaussianBlurImage(0.05, 5);



// Include this part if you also want to specify a maximum size for the images

$size = $im->getImageGeometry();
$maxWidth = 1920;
$maxHeight = 1080;


// ----------
// |        |
// ----------
if($size['width'] >= $size['height']){
  if($size['width'] > $maxWidth){
    $im->resizeImage($maxWidth, 0, \Imagick::FILTER_LANCZOS, 1);
  }
}


// ------
// |    |
// |    |
// |    |
// |    |
// ------
else{
  if($size['height'] > $maxHeight){
    $im->resizeImage(0, $maxHeight, \Imagick::FILTER_LANCZOS, 1);
  }
}

How do I get just the date when using MSSQL GetDate()?

For SQL Server 2008, the best and index friendly way is

DELETE from Table WHERE Date > CAST(GETDATE() as DATE);

For prior SQL Server versions, date maths will work faster than a convert to varchar. Even converting to varchar can give you the wrong result, because of regional settings.

DELETE from Table WHERE Date > DATEDIFF(d, 0, GETDATE());

Note: it is unnecessary to wrap the DATEDIFF with another DATEADD

How to get the currently logged in user's user id in Django?

Assuming you are referring to Django's Auth User, in your view:

def game(request):
  user = request.user

  gta = Game.objects.create(name="gta", owner=user)

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

Does the Java &= operator apply & or &&?

i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.

This worked for me:

a &= a && b()

Check variable equality against a list of values

This is a little helper arrow function:

const letters = ['A', 'B', 'C', 'D'];

function checkInList(arr, val) {
  return arr.some(arrVal => val === arrVal);
}

checkInList(letters, 'E');   // false
checkInList(letters, 'A');   // true

More info here...

PHP __get and __set magic methods

To expand on Berry's answer, that setting the access level to protected allows __get and __set to be used with explicitly declared properties (when accessed outside the class, at least) and the speed being considerably slower, I'll quote a comment from another question on this topic and make a case for using it anyway:

I agree that __get is more slow to a custom get function (doing the same things), this is 0.0124455 the time for __get() and this 0.0024445 is for custom get() after 10000 loops. – Melsi Nov 23 '12 at 22:32 Best practice: PHP Magic Methods __set and __get

According to Melsi's tests, considerably slower is about 5 times slower. That is definitely considerably slower, but also note that the tests show that you can still access a property with this method 10,000 times, counting time for loop iteration, in roughly 1/100 of a second. It is considerably slower in comparison with actual get and set methods defined, and that is an understatement, but in the grand scheme of things, even 5 times slower is never actually slow.

The computing time of the operation is still negligible and not worth considering in 99% of real world applications. The only time it should really be avoided is when you're actually going to be accessing the properties over 10,000 times in a single request. High traffic sites are doing something really wrong if they can't afford throwing a few more servers up to keep their applications running. A single line text ad on the footer of a high traffic site where the access rate becomes an issue could probably pay for a farm of 1,000 servers with that line of text. The end user is never going to be tapping their fingers wondering what is taking the page so long to load because your application's property access takes a millionth of a second.

I say this speaking as a developer coming from a background in .NET, but invisible get and set methods to the consumer is not .NET's invention. They simply aren't properties without them, and these magic methods are PHP's developer's saving grace for even calling their version of properties "properties" at all. Also, the Visual Studio extension for PHP does support intellisense with protected properties, with that trick in mind, I'd think. I would think with enough developers using the magic __get and __set methods in this way, the PHP developers would tune up the execution time to cater to the developer community.

Edit: In theory, protected properties seemed like it'd work in most situation. In practice, it turns out that there's a lot of times you're going to want to use your getters and setters when accessing properties within the class definition and extended classes. A better solution is a base class and interface for when extending other classes, so you can just copy the few lines of code from the base class into the implementing class. I'm doing a bit more with my project's base class, so I don't have an interface to provide right now, but here is the untested stripped down class definition with magic property getting and setting using reflection to remove and move the properties to a protected array:

/** Base class with magic property __get() and __set() support for defined properties. */
class Component {
    /** Gets the properties of the class stored after removing the original
     * definitions to trigger magic __get() and __set() methods when accessed. */
    protected $properties = array();

    /** Provides property get support. Add a case for the property name to
     * expand (no break;) or replace (break;) the default get method. When
     * overriding, call parent::__get($name) first and return if not null,
     * then be sure to check that the property is in the overriding class
     * before doing anything, and to implement the default get routine. */
    public function __get($name) {
        $caller = array_shift(debug_backtrace());
        $max_access = ReflectionProperty::IS_PUBLIC;
        if (is_subclass_of($caller['class'], get_class($this)))
            $max_access = ReflectionProperty::IS_PROTECTED;
        if ($caller['class'] == get_class($this))
            $max_access = ReflectionProperty::IS_PRIVATE;
        if (!empty($this->properties[$name])
            && $this->properties[$name]->class == get_class()
            && $this->properties[$name]->access <= $max_access)
            switch ($name) {
                default:
                    return $this->properties[$name]->value;
            }
    }

    /** Provides property set support. Add a case for the property name to
     * expand (no break;) or replace (break;) the default set method. When
     * overriding, call parent::__set($name, $value) first, then be sure to
     * check that the property is in the overriding class before doing anything,
     * and to implement the default set routine. */
    public function __set($name, $value) {
        $caller = array_shift(debug_backtrace());
        $max_access = ReflectionProperty::IS_PUBLIC;
        if (is_subclass_of($caller['class'], get_class($this)))
            $max_access = ReflectionProperty::IS_PROTECTED;
        if ($caller['class'] == get_class($this))
            $max_access = ReflectionProperty::IS_PRIVATE;
        if (!empty($this->properties[$name])
            && $this->properties[$name]->class == get_class()
            && $this->properties[$name]->access <= $max_access)
            switch ($name) {
                default:
                    $this->properties[$name]->value = $value;
            }
    }

    /** Constructor for the Component. Call first when overriding. */
    function __construct() {
        // Removing and moving properties to $properties property for magic
        // __get() and __set() support.
        $reflected_class = new ReflectionClass($this);
        $properties = array();
        foreach ($reflected_class->getProperties() as $property) {
            if ($property->isStatic()) { continue; }
            $properties[$property->name] = (object)array(
                'name' => $property->name, 'value' => $property->value
                , 'access' => $property->getModifier(), 'class' => get_class($this));
            unset($this->{$property->name}); }
        $this->properties = $properties;
    }
}

My apologies if there are any bugs in the code.

Using a remote repository with non-standard port

This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config file and having something like this

Host git_host
HostName git.host.de
User root
Port 4019

then you can have

url = git_host:/var/cache/git/project.git

and you can also ssh git_host and scp git_host ... and everything will work out.

IOException: Too many open files

Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing

/etc/security/limits.conf

by adding something like this

jetty soft nofile 2048
jetty hard nofile 4096

where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf

log off and then log in again and run

ulimit -n

to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.

The default limit 1024 can be too low for large Java applications.

When do you use POST and when do you use GET?

My general rule of thumb is to use Get when you are making requests to the server that aren't going to alter state. Posts are reserved for requests to the server that alter state.

Setting Inheritance and Propagation flags with set-acl and powershell

Here's a table to help find the required flags for different permission combinations.

    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
    ¦             ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦    files    ¦
    ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦
    ¦ Propagation ¦ none        ¦ none                          ¦ none                   ¦ none             ¦ InheritOnly           ¦ InheritOnly ¦ InheritOnly ¦
    ¦ Inheritance ¦ none        ¦ Container|Object              ¦ Container              ¦ Object           ¦ Container|Object      ¦ Container   ¦ Object      ¦
    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+

So, as David said, you'll want

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
PropagationFlags.None

How do I get a button to open another activity?

If you declared your button in the xml file similar to this:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="next activity"
        android:onClick="goToActivity2"
        />

then you can use it to change the activity by putting this at the java file:

public void goToActivity2 (View view){
    Intent intent = new Intent (this, Main2Activity.class);
    startActivity(intent);
}

Note that my second activity is called "Main2Activity"

Iteration ng-repeat only X times in AngularJs

To repeat 7 times, try to use a an array with length=7, then track it by $index:

<span ng-repeat="a in (((b=[]).length=7)&&b) track by $index" ng-bind="$index + 1 + ', '"></span>

b=[] create an empty Array «b»,
.length=7 set it's size to «7»,
&&b let the new Array «b» be available to ng-repeat,
track by $index where «$index» is the position of iteration.
ng-bind="$index + 1" display starting at 1.

To repeat X times:
just replace 7 by X.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I was getting the same error and it worked for me. Hope it helps.

As Niklas said, you have to update to the latest Gradle version.


My way to solve the error:

  1. Open your Android Studio (AS) program.
  2. Go to your build.gradle file in your project.
  3. Change:

    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
    

    to:

    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.3'
    
  4. Sync your Android project with Gradle: enter image description here

  5. Clean your project.

  6. Rebuild your project.
  7. Done!

If its still not working:

  1. Close your Android Studio program and open it again.
  2. Try compiling the code.
  3. Done!

If you need more help, read the issue on Google Code!

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

Based on Yamikep's answer, I found a better and very simple solution which also handles ModelMultipleChoiceField fields.

Removing field from form.cleaned_data prevents fields from being saved:

class ReadOnlyFieldsMixin(object):
    readonly_fields = ()

    def __init__(self, *args, **kwargs):
        super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)
        for field in (field for name, field in self.fields.iteritems() if
                      name in self.readonly_fields):
            field.widget.attrs['disabled'] = 'true'
            field.required = False

    def clean(self):
        for f in self.readonly_fields:
            self.cleaned_data.pop(f, None)
        return super(ReadOnlyFieldsMixin, self).clean()

Usage:

class MyFormWithReadOnlyFields(ReadOnlyFieldsMixin, MyForm):
    readonly_fields = ('field1', 'field2', 'fieldx')

Redirect from asp.net web api post action

You can check this

[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{

   string url = "https://localhost:44305/Templates/ReportPage.html";

   System.Uri uri = new System.Uri(url);

   return Redirect(uri);
}

How can I implement a tree in Python?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name,
                                     self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name,
                                                 self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes
                if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

Creating custom function in React component

You can try this.

// Author: Hannad Rehman Sat Jun 03 2017 12:59:09 GMT+0530 (India Standard Time)

import React from 'react';
import RippleButton from '../../Components/RippleButton/rippleButton.jsx';

class HtmlComponents extends React.Component {

    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }

    rippleClickFunction(){
        //do stuff. 
        // foo==bar
    }

    render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;

Yhe only concern is you have to bind the context to the function

How to insert DECIMAL into MySQL database

MySql decimal types are a little bit more complicated than just left-of and right-of the decimal point.

The first argument is precision, which is the number of total digits. The second argument is scale which is the maximum number of digits to the right of the decimal point.

Thus, (4,2) can be anything from -99.99 to 99.99.

As for why you're getting 99.99 instead of the desired 3.80, the value you're inserting must be interpreted as larger than 99.99, so the max value is used. Maybe you could post the code that you are using to insert or update the table.

Edit

Corrected a misunderstanding of the usage of scale and precision, per http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html.

Convert datetime to Unix timestamp and convert it back in python

What you missed here is timezones.

Presumably you've five hours off UTC, so 2013-09-01T11:00:00 local and 2013-09-01T06:00:00Z are the same time.

You need to read the top of the datetime docs, which explain about timezones and "naive" and "aware" objects.

If your original naive datetime was UTC, the way to recover it is to use utcfromtimestamp instead of fromtimestamp.

On the other hand, if your original naive datetime was local, you shouldn't have subtracted a UTC timestamp from it in the first place; use datetime.fromtimestamp(0) instead.

Or, if you had an aware datetime object, you need to either use a local (aware) epoch on both sides, or explicitly convert to and from UTC.

If you have, or can upgrade to, Python 3.3 or later, you can avoid all of these problems by just using the timestamp method instead of trying to figure out how to do it yourself. And even if you don't, you may want to consider borrowing its source code.

(And if you can wait for Python 3.4, it looks like PEP 341 is likely to make it into the final release, which means all of the stuff J.F. Sebastian and I were talking about in the comments should be doable with just the stdlib, and working the same way on both Unix and Windows.)

What is the difference between GitHub and gist?

The main differences between github and gists are in terms of number of features and user interface:

One is designed with a great number of features and flexibility in mind, which is a good fit for both small and very big projects, while gists are only a good fit for very small projects.

For example, gists do support multi-files, but the interface is very simple, and they're limited in features, so they don't even have a file browser, nor issues, pull requests or wiki. If you dont need to have that, gists are very nice and more discrete. Like the comments, instead of answers, in SO.

Note: Thanks to @Qwerty for the suggestion of making my comment a real answer.

How to use multiprocessing pool.map with multiple arguments?

Having learnt about itertools in J.F. Sebastian answer I decided to take it a step further and write a parmap package that takes care about parallelization, offering map and starmap functions on python-2.7 and python-3.2 (and later also) that can take any number of positional arguments.

Installation

pip install parmap

How to parallelize:

import parmap
# If you want to do:
y = [myfunction(x, argument1, argument2) for x in mylist]
# In parallel:
y = parmap.map(myfunction, mylist, argument1, argument2)

# If you want to do:
z = [myfunction(x, y, argument1, argument2) for (x,y) in mylist]
# In parallel:
z = parmap.starmap(myfunction, mylist, argument1, argument2)

# If you want to do:
listx = [1, 2, 3, 4, 5, 6]
listy = [2, 3, 4, 5, 6, 7]
param = 3.14
param2 = 42
listz = []
for (x, y) in zip(listx, listy):
        listz.append(myfunction(x, y, param1, param2))
# In parallel:
listz = parmap.starmap(myfunction, zip(listx, listy), param1, param2)

I have uploaded parmap to PyPI and to a github repository.

As an example, the question can be answered as follows:

import parmap

def harvester(case, text):
    X = case[0]
    text+ str(X)

if __name__ == "__main__":
    case = RAW_DATASET  # assuming this is an iterable
    parmap.map(harvester, case, "test", chunksize=1)

How to make padding:auto work in CSS?

You should just scope your * selector to the specific areas that need the reset. .legacy * { }, etc.

What exactly does an #if 0 ..... #endif block do?

It's identical to commenting out the block, except with one important difference: Nesting is not a problem. Consider this code:

foo();
bar(x, y); /* x must not be NULL */
baz();

If I want to comment it out, I might try:

/*
foo();
bar(x, y); /* x must not be NULL */
baz();
*/

Bzzt. Syntax error! Why? Because block comments do not nest, and so (as you can see from SO's syntax highlighting) the */ after the word "NULL" terminates the comment, making the baz call not commented out, and the */ after baz a syntax error. On the other hand:

#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif

Works to comment out the entire thing. And the #if 0s will nest with each other, like so:

#if 0
pre_foo();
#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif
quux();
#endif

Although of course this can get a bit confusing and become a maintenance headache if not commented properly.

Transparent CSS background color

Yes you can just plain text as

.someDive{
    background:transparent 
}

How to test whether a service is running from the command line

if you don't mind to combine the net command with grep you can use the following script.

@echo off
net start | grep -x "Service"
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:end

VBoxManage: error: Failed to create the host-only adapter

I'm running Debian 8 (Jessie), Vagrant 1.6.5 and Virtual Box 4.3.x with the same problem.

For me it got fixed executing:

sudo /etc/init.d/vboxdrv setup

How do I set the colour of a label (coloured text) in Java?

You can set the color of a JLabel by altering the foreground category:

JLabel title = new JLabel("I love stackoverflow!", JLabel.CENTER);

title.setForeground(Color.white);

As far as I know, the simplest way to create the two-color label you want is to simply make two labels, and make sure they get placed next to each other in the proper order.

Linking a qtDesigner .ui file to python/pyqt?

In order to compile .ui files to .py files, I did:

python pyuic.py form1.ui > form1.py

Att.

How can I have grep not print out 'No such file or directory' errors?

Have you tried the -0 option in xargs? Something like this:

ls -r1 | xargs -0 grep 'some text'

server error:405 - HTTP verb used to access this page is not allowed

It means litraly that, your trying to use the wrong http verb when accessing some http content. A lot of content on webservices you need to use a POST to consume. I suspect your trying to access the facebook API using the wrong http verb.

View tabular file such as CSV from command line

tblless in the Tabulator package wraps the unix column command, and also aligns numeric columns.

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

How to avoid "RuntimeError: dictionary changed size during iteration" error?

For situations like this, i like to make a deep copy and loop through that copy while modifying the original dict.

If the lookup field is within a list, you can enumerate in the for loop of the list and then specify the position as index to access the field in the original dict.

Cannot use object of type stdClass as array?

When you try to access it as $result['context'], you treating it as an array, the error it's telling you that you are actually dealing with an object, then you should access it as $result->context

Matplotlib scatterplot; colour as a function of a third variable

In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'

Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:

from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [str(item/255.) for item in y]

plt.scatter(x, y, s=500, c=color)

plt.show()

enter image description here

Difference between static and shared libraries?

Static libraries are compiled as part of an application, whereas shared libraries are not. When you distribute an application that depends on shared libaries, the libraries, eg. dll's on MS Windows need to be installed.

The advantage of static libraries is that there are no dependencies required for the user running the application - e.g. they don't have to upgrade their DLL of whatever. The disadvantage is that your application is larger in size because you are shipping it with all the libraries it needs.

As well as leading to smaller applications, shared libraries offer the user the ability to use their own, perhaps better version of the libraries rather than relying on one that's part of the application

How to use regex in XPath "contains" function

In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me

//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\

What are good examples of genetic algorithms/genetic programming solutions?

A couple of weeks ago, I suggested a solution on SO using genetic algorithms to solve a problem of graph layout. It is an example of a constrained optimization problem.

Also in the area of machine learning, I implemented a GA-based classification rules framework in c/c++ from scratch.
I've also used GA in a sample project for training artificial neural networks (ANN) as opposed to using the famous backpropagation algorithm.

In addition, and as part of my graduate research, I've used GA in training Hidden Markov Models as an additional approach to the EM-based Baum-Welch algorithm (in c/c++ again).

Java method to sum any number of ints

You need:

public int sumAll(int...numbers){

    int result = 0;
    for(int i = 0 ; i < numbers.length; i++) {
        result += numbers[i];
    } 
    return result;
}

Then call the method and give it as many int values as you need:

int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);

In Typescript, How to check if a string is Numeric

For full numbers (non-floats) in Angular you can use:

if (Number.isInteger(yourVariable)) { ... }

How do I use a C# Class Library in a project?

I'm not certain why everyone is claiming that you need a using statement at the top of your file, as this is entirely unnecessary.

Right-click on the "References" folder in your project and select "Add Reference". If your new class library is a project in the same solution, select the "Project" tab and pick the project. If the new library is NOT in the same solution, click the "Browse" tab and find the .dll for your new project.

jQuery scroll to element

Animations:

// slide to top of the page
$('.up').click(function () {
    $("html, body").animate({
        scrollTop: 0
    }, 600);
    return false;
});

// slide page to anchor
$('.menutop b').click(function(){
    //event.preventDefault();
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 600);
    return false;
});

// Scroll to class, div
$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#target-element").offset().top
    }, 1000);
});

// div background animate
$(window).scroll(function () {

    var x = $(this).scrollTop();

    // freezze div background
    $('.banner0').css('background-position', '0px ' + x +'px');

    // from left to right
    $('.banner0').css('background-position', x+'px ' +'0px');

    // from right to left
    $('.banner0').css('background-position', -x+'px ' +'0px');

    // from bottom to top
    $('#skills').css('background-position', '0px ' + -x + 'px');

    // move background from top to bottom
    $('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');

    // Show hide mtop menu  
    if ( x > 100 ) {
    $( ".menu" ).addClass( 'menushow' );
    $( ".menu" ).fadeIn("slow");
    $( ".menu" ).animate({opacity: 0.75}, 500);
    } else {
    $( ".menu" ).removeClass( 'menushow' );
    $( ".menu" ).animate({opacity: 1}, 500);
    }

});

// progres bar animation simple
$('.bar1').each(function(i) {
  var width = $(this).data('width');  
  $(this).animate({'width' : width + '%' }, 900, function(){
    // Animation complete
  });  
});

Remove Duplicate objects from JSON Array

You can use lodash, download here (4.17.15)

Example code:

var object = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.uniqWith(object, _.isEqual);

// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

How can I pass arguments to anonymous functions in JavaScript?

Event handlers expect one parameter which is the event that was fired. You happen to be renaming that to 'myMessage' and therefore you are alerting the event object rather than your message.

A closure can allow you to reference the variable you have defined outside the function however if you are using Jquery you may want to look at its event specific API e.g.

http://docs.jquery.com/Events/bind#typedatafn

This has an option for passing in your own data.

Add placeholder text inside UITextView in Swift?

I like @nerdist's solution. Based on that, I created an extension to UITextView:

import Foundation
import UIKit

extension UITextView
{
  private func add(_ placeholder: UILabel) {
    for view in self.subviews {
        if let lbl = view as? UILabel  {
            if lbl.text == placeholder.text {
                lbl.removeFromSuperview()
            }
        }
    }
    self.addSubview(placeholder)
  }

  func addPlaceholder(_ placeholder: UILabel?) {
    if let ph = placeholder {
      ph.numberOfLines = 0  // support for multiple lines
      ph.font = UIFont.italicSystemFont(ofSize: (self.font?.pointSize)!)
      ph.sizeToFit()
      self.add(ph)
      ph.frame.origin = CGPoint(x: 5, y: (self.font?.pointSize)! / 2)
      ph.textColor = UIColor(white: 0, alpha: 0.3)
      updateVisibility(ph)
    }
  }

  func updateVisibility(_ placeHolder: UILabel?) {
    if let ph = placeHolder {
      ph.isHidden = !self.text.isEmpty
    }
  }
}

In a ViewController class, for example, this is how I use it:

class MyViewController: UIViewController, UITextViewDelegate {
  private var notePlaceholder: UILabel!
  @IBOutlet weak var txtNote: UITextView!
  ...
  // UIViewController
  override func viewDidLoad() {
    notePlaceholder = UILabel()
    notePlaceholder.text = "title\nsubtitle\nmore..."
    txtNote.addPlaceholder(notePlaceholder)
    ...
  }

  // UITextViewDelegate
  func textViewDidChange(_ textView: UITextView) {
    txtNote.updateVisbility(notePlaceholder)
    ...
  }

Placeholder on UITextview!

enter image description here

UPDATE:

In case you change textview's text in code, remember to call updateVisibitly method to hide placeholder:

txtNote.text = "something in code"
txtNote.updateVisibility(self.notePlaceholder) // hide placeholder if text is not empty.

To prevent the placeholder being added more than once, a private add() function is added in extension.

Changing background colour of tr element on mouseover

tr:hover td {background-color:#000;}

How to fix Error: laravel.log could not be opened?

Run following commands and you can add sudo at starting of command depends on your system:

chmod -R 775 storage/framework
chmod -R 775 storage/logs
chmod -R 775 bootstrap/cache 

Why is it not advisable to have the database and web server on the same machine?

On the other hand, referring to a different blogging Scott (Watermasyck, of Telligent) - they found that most users could speed up the websites (using Telligent's Community Server), by putting the database on the same machine as the web site. However, in their customer's case, usually the db & web server are the only applications on that machine, and the website isn't straining the machine that much. Then, the efficiency of not having to send data across the network more that made up for the increased strain.

Validate phone number with JavaScript

try this

/^[\+]?\d{2,}?[(]?\d{2,}[)]?[-\s\.]?\d{2,}?[-\s\.]?\d{2,}[-\s\.]?\d{0,9}$/im

valid formats:

  1. (123) 456-7890
  2. (123)456-7890
  3. 123-456-7890
  4. 123.456.7890
  5. 1234567890
  6. +31636363634
  7. +3(123) 123-12-12
  8. +3(123)123-12-12
  9. +3(123)1231212
  10. +3(123) 12312123
  11. 075-63546725

How to implement a secure REST API with node.js

I just finished a sample app that does this in a pretty basic, but clear way. It uses mongoose with mongodb to store users and passport for auth management.

https://github.com/Khelldar/Angular-Express-Train-Seed

Reducing the gap between a bullet and text in a list item

Try this....

ul.list-group li {
     padding-left: 13px;
     position: relative;
}

ul.list-group li:before {
     left: 0 !important;
     position: absolute;
}

How to get exception message in Python properly

If you look at the documentation for the built-in errors, you'll see that most Exception classes assign their first argument as a message attribute. Not all of them do though.

Notably,EnvironmentError (with subclasses IOError and OSError) has a first argument of errno, second of strerror. There is no message... strerror is roughly analogous to what would normally be a message.

More generally, subclasses of Exception can do whatever they want. They may or may not have a message attribute. Future built-in Exceptions may not have a message attribute. Any Exception subclass imported from third-party libraries or user code may not have a message attribute.

I think the proper way of handling this is to identify the specific Exception subclasses you want to catch, and then catch only those instead of everything with an except Exception, then utilize whatever attributes that specific subclass defines however you want.

If you must print something, I think that printing the caught Exception itself is most likely to do what you want, whether it has a message attribute or not.

You could also check for the message attribute if you wanted, like this, but I wouldn't really suggest it as it just seems messy:

try:
    pass
except Exception as e:
    # Just print(e) is cleaner and more likely what you want,
    # but if you insist on printing message specifically whenever possible...
    if hasattr(e, 'message'):
        print(e.message)
    else:
        print(e)

How to set environment variables in PyCharm?

You can set environmental variables in Pycharm's run configurations menu.

  1. Open the Run Configuration selector in the top-right and cick Edit Configurations...

    Edit Configurations...

  2. Find Environmental variables and click ...

    Environmental variables

  3. Add or change variables, then click OK

    Editing environmental variables

You can access your environmental variables with os.environ

import os
print(os.environ['SOME_VAR'])

How to scroll the window using JQuery $.scrollTo() function

To get around the html vs body issue, I fixed this by not animating the css directly but rather calling window.scrollTo(); on each step:

$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
  duration: 600,
  easing: 'swing',
  step: function(val) {
    window.scrollTo(0, val);
  }
});

This works nicely without any refresh gotchas as it's using cross-browser JavaScript.

Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.

How to select all rows which have same value in some column

How about

SELECT *
FROM Employees
WHERE PhoneNumber IN (
    SELECT PhoneNumber
    FROM Employees
    GROUP BY PhoneNumber
    HAVING COUNT(Employee_ID) > 1
    )

SQL Fiddle DEMO

Html Agility Pack get all elements by class

(Updated 2018-03-17)

The problem:

The problem, as you've spotted, is that String.Contains does not perform a word-boundary check, so Contains("float") will return true for both "foo float bar" (correct) and "unfloating" (which is incorrect).

The solution is to ensure that "float" (or whatever your desired class-name is) appears alongside a word-boundary at both ends. A word-boundary is either the start (or end) of a string (or line), whitespace, certain punctuation, etc. In most regular-expressions this is \b. So the regex you want is simply: \bfloat\b.

A downside to using a Regex instance is that they can be slow to run if you don't use the .Compiled option - and they can be slow to compile. So you should cache the regex instance. This is more difficult if the class-name you're looking for changes at runtime.

Alternatively you can search a string for words by word-boundaries without using a regex by implementing the regex as a C# string-processing function, being careful not to cause any new string or other object allocation (e.g. not using String.Split).

Approach 1: Using a regular-expression:

Suppose you just want to look for elements with a single, design-time specified class-name:

class Program {

    private static readonly Regex _classNameRegex = new Regex( @"\bfloat\b", RegexOptions.Compiled );

    private static IEnumerable<HtmlNode> GetFloatElements(HtmlDocument doc) {
        return doc
            .Descendants()
            .Where( n => n.NodeType == NodeType.Element )
            .Where( e => e.Name == "div" && _classNameRegex.IsMatch( e.GetAttributeValue("class", "") ) );
    }
}

If you need to choose a single class-name at runtime then you can build a regex:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    Regex regex = new Regex( "\\b" + Regex.Escape( className ) + "\\b", RegexOptions.Compiled );

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e => e.Name == "div" && regex.IsMatch( e.GetAttributeValue("class", "") ) );
}

If you have multiple class-names and you want to match all of them, you could create an array of Regex objects and ensure they're all matching, or combine them into a single Regex using lookarounds, but this results in horrendously complicated expressions - so using a Regex[] is probably better:

using System.Linq;

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String[] classNames) {

    Regex[] exprs = new Regex[ classNames.Length ];
    for( Int32 i = 0; i < exprs.Length; i++ ) {
        exprs[i] = new Regex( "\\b" + Regex.Escape( classNames[i] ) + "\\b", RegexOptions.Compiled );
    }

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            exprs.All( r =>
                r.IsMatch( e.GetAttributeValue("class", "") )
            )
        );
}

Approach 2: Using non-regex string matching:

The advantage of using a custom C# method to do string matching instead of a regex is hypothetically faster performance and reduced memory usage (though Regex may be faster in some circumstances - always profile your code first, kids!)

This method below: CheapClassListContains provides a fast word-boundary-checking string matching function that can be used the same way as regex.IsMatch:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            CheapClassListContains(
                e.GetAttributeValue("class", ""),
                className,
                StringComparison.Ordinal
            )
        );
}

/// <summary>Performs optionally-whitespace-padded string search without new string allocations.</summary>
/// <remarks>A regex might also work, but constructing a new regex every time this method is called would be expensive.</remarks>
private static Boolean CheapClassListContains(String haystack, String needle, StringComparison comparison)
{
    if( String.Equals( haystack, needle, comparison ) ) return true;
    Int32 idx = 0;
    while( idx + needle.Length <= haystack.Length )
    {
        idx = haystack.IndexOf( needle, idx, comparison );
        if( idx == -1 ) return false;

        Int32 end = idx + needle.Length;

        // Needle must be enclosed in whitespace or be at the start/end of string
        Boolean validStart = idx == 0               || Char.IsWhiteSpace( haystack[idx - 1] );
        Boolean validEnd   = end == haystack.Length || Char.IsWhiteSpace( haystack[end] );
        if( validStart && validEnd ) return true;

        idx++;
    }
    return false;
}

Approach 3: Using a CSS Selector library:

HtmlAgilityPack is somewhat stagnated doesn't support .querySelector and .querySelectorAll, but there are third-party libraries that extend HtmlAgilityPack with it: namely Fizzler and CssSelectors. Both Fizzler and CssSelectors implement QuerySelectorAll, so you can use it like so:

private static IEnumerable<HtmlNode> GetDivElementsWithFloatClass(HtmlDocument doc) {

    return doc.QuerySelectorAll( "div.float" );
}

With runtime-defined classes:

private static IEnumerable<HtmlNode> GetDivElementsWithClasses(HtmlDocument doc, IEnumerable<String> classNames) {

    String selector = "div." + String.Join( ".", classNames );

    return doc.QuerySelectorAll( selector  );
}

git: fatal unable to auto-detect email address

Steps to solve this problem

note: This problem mainly occurs due to which we haven't assigned our user name and email id in git so what we gonna do is assigning it in git

  1. Open git that you have installed

  2. Now we have to assign our user name and email id

  3. Just type git config --user.name <your_name> and click enter (you can mention or type any name you want)

  4. Similarly type git config --user.email <[email protected]> and click enter (you have to type your primary mail id)

  5. And that's it.

    Have a Good Day!!!.

Column name or number of supplied values does not match table definition

This is an older post but I want to also mention that if you have something like

insert into blah
       select * from blah2

and blah and blah2 are identical keep in mind that a computed column will throw this same error...

I just realized that when the above failed and I tried

insert into blah (cola, colb, colc)
       select cola, colb, colc from blah2

In my example it was fullname field (computed from first and last, etc)

Correct way to import lodash

You can import them as

import {concat, filter, orderBy} from 'lodash';

or as

import concat from 'lodash/concat';
import orderBy from 'lodash/orderBy';
import filter from 'lodash/filter';

the second one is much optimized than the first because it only loads the needed modules

then use like this

pendingArray: concat(
                    orderBy(
                        filter(payload, obj => obj.flag),
                        ['flag'],
                        ['desc'],
                    ),
                    filter(payload, obj => !obj.flag),

No String-argument constructor/factory method to deserialize from String value ('')

Try setting mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)

or

mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

depending on your Jackson version.

What are all the different ways to create an object in Java?

There is a type of object, which can't be constructed by normal instance creation mechanisms (calling constructors): Arrays. Arrays are created with

 A[] array = new A[len];

or

 A[] array = new A[] { value0, value1, value2 };

As Sean said in a comment, this is syntactically similar to a constructor call and internally it is not much more than allocation and zero-initializing (or initializing with explicit content, in the second case) a memory block, with some header to indicate the type and the length.

When passing arguments to a varargs-method, an array is there created (and filled) implicitly, too.

A fourth way would be

 A[] array = (A[]) Array.newInstance(A.class, len);

Of course, cloning and deserializing works here, too.

There are many methods in the Standard API which create arrays, but they all in fact are using one (or more) of these ways.

Get filename and path from URI from mediastore

This works for me perfectly if your system version is above 19, Hope this can help you.

  @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {
        final boolean isOverKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isOverKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

How to get .app file of a xcode application

~/Library/Developer/Xcode/DerivedData/{app name}/Build/Products/Debug-iphonesimulator/

Regex lookahead, lookbehind and atomic groups

Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.

Read regular-expression.info for more details.

  • Positive lookahead:

Syntax:

(?=REGEX_1)REGEX_2

Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.

example:

(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}

REGEX_1 is [a-z0-9]{4}$ which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3} which matches one or two letters followed by two or three digits.

REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.

  • Negative lookahead

Syntax:

(?!REGEX_1)REGEX_2

Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.

example:

(?!.*\bFWORD\b)\w{10,30}$

The look-ahead part checks for the FWORD in the string and fails if it finds it. If it doesn't find FWORD, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_

Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.

  • Atomic groups basically discards/forgets the subsequent tokens in the group once a token matches. Check this page for examples of atomic groups

Installing PIL with pip

It is very simple using apt install use this command to get it done

sudo apt-get install python-PIL

or

sudo pip install pillow

or

sudo easy_install pillow

JAVA_HOME directory in Linux

echo $JAVA_HOME will print the value if it's set. However, if you didn't set it manually in your startup scripts, it probably isn't set.

If you try which java and it doesn't find anything, Java may not be installed on your machine, or at least isn't in your path. Depending on which Linux distribution you have and whether or not you have root access, you can go to http://www.java.com to download the version you need. Then, you can set JAVA_HOME to point to this directory. Remember, that this is just a convention and shouldn't be used to determine if java is installed or not.

Pythonic way to create a long multi-line string

Your actual code shouldn't work; you are missing white spaces at the end of "lines" (for example, role.descr as roleFROM...).

There are triple quotes for multiline strings:

string = """line
  line2
  line3"""

It will contain the line breaks and extra spaces, but for SQL that's not a problem.

trace a particular IP and port

Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.

You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).

How to run a python script from IDLE interactive shell?

In a python console, one can try the following 2 ways.

under the same work directory,

1. >> import helloworld

# if you have a variable x, you can print it in the IDLE.

>> helloworld.x

# if you have a function func, you can also call it like this.

>> helloworld.func()

2. >> runfile("./helloworld.py")

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Deleting/commenting

- (void)viewWillAppear:(BOOL)animated {[super viewWillAppear:YES];}

function solved the problem for me.

XCode (11.3.1)

ERROR 1044 (42000): Access denied for 'root' With All Privileges

The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:

DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';

I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Try to add

GRANT USAGE ON SCHEMA public to readonly;

You probably were not aware that one needs to have the requisite permissions to a schema, in order to use objects in the schema.

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

Force overwrite of local file with what's in origin repo?

This worked for me:

git reset HEAD <filename>

Best way to Bulk Insert from a C# DataTable

If using SQL Server, SqlBulkCopy.WriteToServer(DataTable)

Or also with SQL Server, you can write it to a .csv and use BULK INSERT

If using MySQL, you could write it to a .csv and use LOAD DATA INFILE

If using Oracle, you can use the array binding feature of ODP.NET

If SQLite:

sql server Get the FULL month name from a date

SELECT DATENAME(MONTH, GETDATE()) 
         + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY]

OR Date without Comma Between date and year, you can use the following

SELECT DATENAME(MONTH, GETDATE()) + ' ' + CAST(DAY(GETDATE()) AS VARCHAR(2))
           + ' ' + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month DD YYYY]

How to specify preference of library path?

As an alternative, you can use the environment variables LIBRARY_PATH and CPLUS_INCLUDE_PATH, which respectively indicate where to look for libraries and where to look for headers (CPATH will also do the job), without specifying the -L and -I options.

Edit: CPATH includes header with -I and CPLUS_INCLUDE_PATH with -isystem.

QLabel: set color of text and background

You can use QPalette, however you must set setAutoFillBackground(true); to enable background color

QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);

sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");

It works fine on Windows and Ubuntu, I haven't played with any other OS.

Note: Please see QPalette, color role section for more details

How to run Unix shell script from Java code?

As for me all things must be simple. For running script just need to execute

new ProcessBuilder("pathToYourShellScript").start();

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Nodejs convert string into UTF-8

I'd recommend using the Buffer class:

var someEncodedString = Buffer.from('someString', 'utf-8');

This avoids any unnecessary dependencies that other answers require, since Buffer is included with node.js, and is already defined in the global scope.

How do I add more members to my ENUM-type column in MySQL?

It's possible if you believe. Hehe. try this code.

public function add_new_enum($new_value)
  {
    $table="product";
    $column="category";
         $row = $this->db->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = ? AND COLUMN_NAME = ?", array($table, $column))->row_array();

    $old_category = array();
    $new_category="";
    foreach (explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE']) - 6)))) as $val)
    {
        //getting the old category first

        $old_category[$val] = $val;
        $new_category.="'".$old_category[$val]."'".",";
    }

     //after the end of foreach, add the $new_value to $new_category

      $new_category.="'".$new_value."'";

    //Then alter the table column with the new enum

    $this->db->query("ALTER TABLE product CHANGE category category ENUM($new_category)");
  }

Before adding new value

After adding new value

Press enter in textbox to and execute button command

Alternatively, you could set the .AcceptButton property of your form. Enter will automcatically create a click event.

this.AcceptButton = this.buttonSearch;

iPhone Navigation Bar Title text color

You should call [label sizeToFit]; after setting the text to prevent strange offsets when the label is automatically repositioned in the title view when other buttons occupy the nav bar.

How to print all information from an HTTP request to the screen, in PHP

Well, you can read the entirety of the POST body like so

echo file_get_contents( 'php://input' );

And, assuming your webserver is Apache, you can read the request headers like so

$requestHeaders = apache_request_headers();

get client time zone from browser

Often when people are looking for "timezones", what will suffice is just "UTC offset". e.g., their server is in UTC+5 and they want to know that their client is running in UTC-8.


In plain old javascript (new Date()).getTimezoneOffset()/60 will return the current number of hours offset from UTC.

It's worth noting a possible "gotcha" in the sign of the getTimezoneOffset() return value (from MDN docs):

The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, for time zone UTC+10:00 (Australian Eastern Standard Time, Vladivostok Time, Chamorro Standard Time), -600 will be returned.


However, I recommend you use the day.js for time/date related Javascript code. In which case you can get an ISO 8601 formatted UTC offset by running:

> dayjs().format("Z")
"-08:00"

It probably bears mentioning that the client can easily falsify this information.

(Note: this answer originally recommended https://momentjs.com/, but dayjs is a more modern, smaller alternative.)

NPM: npm-cli.js not found when running npm

You need to run this in the command line.

SET PATH=C:\Program Files\Nodejs;%PATH%

How to randomize (shuffle) a JavaScript array?

I like to share one of the million ways to solve this problem =)

function shuffleArray(array = ["banana", "ovo", "salsicha", "goiaba", "chocolate"]) {
const newArray = [];
let number = Math.floor(Math.random() * array.length);
let count = 1;
newArray.push(array[number]);

while (count < array.length) {
    const newNumber = Math.floor(Math.random() * array.length);
    if (!newArray.includes(array[newNumber])) {
        count++;
        number = newNumber;
        newArray.push(array[number]);
    }
}

return newArray;

}

How do I add options to a DropDownList using jQuery?

Pease note @Phrogz's solution doesn't work in IE 8 while @nickf's works in all major browsers. Another approach is:

$.each(myOptions, function(val, text) {
    $("#mySelect").append($("&lt;option/&gt;").attr("value", val).text(text));
});

Binding ConverterParameter

No, unfortunately this will not be possible because ConverterParameter is not a DependencyProperty so you won't be able to use bindings

But perhaps you could cheat and use a MultiBinding with IMultiValueConverter to pass in the 2 Tag properties.

ValueError: could not convert string to float: id

This error is pretty verbose:

ValueError: could not convert string to float: id

Somewhere in your text file, a line has the word id in it, which can't really be converted to a number.

Your test code works because the word id isn't present in line 2.


If you want to catch that line, try this code. I cleaned your code up a tad:

#!/usr/bin/python

import os, sys
from scipy import stats
import numpy as np

for index, line in enumerate(open('data2.txt', 'r').readlines()):
    w = line.split(' ')
    l1 = w[1:8]
    l2 = w[8:15]

    try:
        list1 = map(float, l1)
        list2 = map(float, l2)
    except ValueError:
        print 'Line {i} is corrupt!'.format(i = index)'
        break

    result = stats.ttest_ind(list1, list2)
    print result[1]

What's the use of session.flush() in Hibernate

I only know that when we call session.flush() our statements are execute in database but not committed.

Suppose we don't call flush() method on session object and if we call commit method it will internally do the work of executing statements on the database and then committing.

commit=flush+commit (in case of functionality)

Thus, I conclude that when we call method flush() on Session object, then it doesn't get commit but hits the database and executes the query and gets rollback too.

In order to commit we use commit() on Transaction object.

Warning about SSL connection when connecting to MySQL database

I use this property for hibernate in config xml

<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/bookshop?serverTimezone=UTC&amp;useSSL=false
</property>

without - serverTimezone=UTC - it doesn't work

Re-ordering columns in pandas dataframe based on column name

df = df.reindex(sorted(df.columns), axis=1)

This assumes that sorting the column names will give the order you want. If your column names won't sort lexicographically (e.g., if you want column Q10.3 to appear after Q9.1), you'll need to sort differently, but that has nothing to do with pandas.

Rounded corner for textview in android

  1. Create rounded_corner.xml in the drawable folder and add the following content,

    <solid android:color="#ffffff" />
    
    <padding
            android:left="1dp"
            android:right="1dp"
            android:bottom="1dp"
            android:top="1dp" />
    
    <corners android:radius="5dp" />
    
  2. Set this drawable in the TextView background property like so:

    android:background="@drawable/rounded_corner"
    

I hope this is useful for you.

importing jar libraries into android-studio

I also faced same obstacle but not able to find out solution from given answers. Might be it's happening due to project path which is having special characters & space etc... So please try to add this line in your build.gradle.

compile files('../app/libs/jtwitter.jar')// pass your .jar file name

".." (Double dot) will find your root directory of your project.

Parsing date string in Go

As answered but to save typing out "2006-01-02T15:04:05.000Z" for the layout, you could use the package's constant RFC3339.

str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(time.RFC3339, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

https://play.golang.org/p/Dgu2ZvHwTh

Clear form after submission with jQuery

Just add this to your Action file in some div or td, so that it comes with incoming XML object

    <script type="text/javascript">
    $("#formname").resetForm();
    </script>

Where "formname" is the id of form you want to edit

Select something that has more/less than x character

If your experiencing the same problem while querying a DB2 database, you'll need to use the below query.

SELECT * 
FROM OPENQUERY(LINK_DB,'SELECT
CITY,
cast(STATE as varchar(40)) 
FROM DATABASE')

T-SQL - function with default parameters

You can call it three ways - with parameters, with DEFAULT and via EXECUTE

SET NOCOUNT ON;

DECLARE
@Table  SYSNAME = 'YourTable',
@Schema SYSNAME = 'dbo',
@Rows   INT;

SELECT dbo.TableRowCount( @Table, @Schema )

SELECT dbo.TableRowCount( @Table, DEFAULT )

EXECUTE @Rows = dbo.TableRowCount @Table

SELECT @Rows

Linux Process States

As already explained by others, processes in "D" state (uninterruptible sleep) are responsible for the hang of ps process. To me it has happened many times with RedHat 6.x and automounted NFS home directories.

To list processes in D state you can use the following commands:

cd /proc
for i in [0-9]*;do echo -n "$i :";cat $i/status |grep ^State;done|grep D

To know the current directory of the process and, may be, the mounted NFS disk that has issues you can use a command similar to the following example (replace 31134 with the sleeping process number):

# ls -l /proc/31134/cwd
lrwxrwxrwx 1 pippo users 0 Aug  2 16:25 /proc/31134/cwd -> /auto/pippo

I found that giving the umount command with the -f (force) switch, to the related mounted nfs file system, was able to wake-up the sleeping process:

umount -f /auto/pippo

the file system wasn't unmounted, because it was busy, but the related process did wake-up and I was able to solve the issue without rebooting.

Axios get access to response header fields

In case you're using Laravel 8 for the back-end side with CORS properly configured, add this line to config/cors.php:

'exposed_headers' => ['Authorization'],

Git add and commit in one command

You ca use -a

git commit -h

...
Commit contents options
    -a, -all    commit all changed files
...

git commit -a # It will add all files and also will open your default text editor.

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

Change/Get check state of CheckBox

This will be useful

$("input[type=checkbox]").change((e)=>{ 
  console.log(e.target.checked);
});

Git list of staged files

The best way to do this is by running the command:

git diff --name-only --cached

When you check the manual you will likely find the following:

--name-only
    Show only names of changed files.

And on the example part of the manual:

git diff --cached
    Changes between the index and your current HEAD.

Combined together you get the changes between the index and your current HEAD and Show only names of changed files.

Update: --staged is also available as an alias for --cached above in more recent git versions.

How to unblock with mysqladmin flush hosts

You should put it into command line in windows.

mysqladmin -u [username] -p flush-hosts
**** [MySQL password]

or

mysqladmin flush-hosts -u [username] -p
**** [MySQL password]

For network login use the following command:

mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts 

you can permanently solution your problem by editing my.ini file[Mysql configuration file] change variables max_connections = 10000;

or

login into MySQL using command line -

mysql -u [username] -p
**** [MySQL password]

put the below command into MySQL window

SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;

check veritable using command-

show variables like "max_connections";
show variables like "max_connect_errors";

Including non-Python files with setup.py

This works in 2020!

As others said create "MANIFEST.in" where your setup.py is located.

Next in manifest include/exclude all the necessary things. Be careful here regarding the syntax. Ex: lets say we have template folder to be included in the source package.

in manifest file do this :

recursive-include template *

Make sure you leave space between dir-name and pattern for files/dirs like above. Dont do like this like we do in .gitignore

recursive-include template/* [this won't work]

Other option is to use include. There are bunch of options. Look up here at their docs for Manifest.in

And the final important step, include this param in your setup.py and you are good to go!

   setup(
    ...
    include_package_data=True,
    ......
)

Hope that helps! Happy Coding!

CSS @media print issues with background-color;

For Chrome:::::::::::::::::

Ctrl+P => Select the Click On More Settings => In the Options Menu Select the Background and Graphics Options

                      :) Will Work

**Why wasn't it working!Reason:**Chrome Browser had Fonts And Headers Enabled

General Case:::::

When you dont need to turn on this option manually.In body in CSS type:::::

-webkit-print-color-adjust:exact !important;

:)Works

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

Android Studio - How to increase Allocated Heap Size

I found on on Windows 7/8 (64-bit), as of Android Studio 1.1.0:

[INSTALL_DIR]\bin\studio64.exe.vmoptions be used (if it exists), otherwise it would always fall back to %USERPROFILE%.\AndroidStudio\studio[64].exe.vmoptions

If you want the settings managed from %USERPROFILE%.\AndroidStudio\studio[64].exe.vmoptions, just delete the one in the installation directory.

Run JavaScript when an element loses focus

You're looking for the onblur event. Look here, for more details.

Percentage width in a RelativeLayout

You can use PercentRelativeLayout, It is a recent undocumented addition to the Design Support Library, enables the ability to specify not only elements relative to each other but also the total percentage of available space.

Subclass of RelativeLayout that supports percentage based dimensions and margins. You can specify dimension or a margin of child by using attributes with "Percent" suffix.

<android.support.percent.PercentRelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
  <ImageView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_widthPercent="50%"
      app:layout_heightPercent="50%"
      app:layout_marginTopPercent="25%"
      app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentFrameLayout>

The Percent package provides APIs to support adding and managing percentage based dimensions in your app.

To use, you need to add this library to your Gradle dependency list:

dependencies {
    compile 'com.android.support:percent:22.2.0'//23.1.1
}

How to advance to the next form input when the current input has a value?

If you have jQuery UI this little function allows basic tabbing

handlePseudoTab(direction) {
    if (!document.hasFocus() || !document.activeElement) {
        return;
    }
    const focusList = $(":focusable", $yourHTMLElement);
    const i = focusList.index(document.activeElement);
    if (i < 0) {
        focusList[0].focus(); // nothing is focussed so go to list item 0
    } else if (direction === 'next' && i + 1 < focusList.length) {
        focusList[i + 1].focus(); // advance one
    } else if (direction === 'prev' && i - 1 > -1) {
        focusList[i - 1].focus(); // go back one
    }
}

How can I find which tables reference a given table in Oracle SQL Developer?

I like to do this with a straight SQL query, rather than messing about with the SQL Developer application.

Here's how I just did it. Best to read through this and understand what's going on, so you can tweak it to fit your needs...

WITH all_primary_keys AS (
  SELECT constraint_name AS pk_name,
         table_name
    FROM all_constraints
   WHERE owner = USER
     AND constraint_type = 'P'
)
  SELECT ac.table_name || ' table has a foreign key called ' || upper(ac.constraint_name)
         || ' which references the primary key ' || upper(ac.r_constraint_name) || ' on table ' || apk.table_name AS foreign_keys
    FROM all_constraints ac
         LEFT JOIN all_primary_keys apk
                ON ac.r_constraint_name = apk.pk_name
   WHERE ac.owner = USER
     AND ac.constraint_type = 'R'
     AND ac.table_name = nvl(upper(:table_name), ac.table_name)
ORDER BY ac.table_name, ac.constraint_name
;

Initialize value of 'var' in C# to null

The var keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var keyword has a type. For instance, you'll find that the following code outputs "String".

var myString = "";
Console.Write(myString.GetType().Name);

Furthermore, the code above is equivalent to:

String myString = "";
Console.Write(myString.GetType().Name);

The var keyword is simply C#'s way of saying "I can figure out the type for myString from the context, so don't worry about specifying the type."

var myVariable = (MyType)null or MyType myVariable = null should work because you are giving the C# compiler context to figure out what type myVariable should will be.

For more information:

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

In Python 2.x, it is not guaranteed at all:

>>> False = 5
>>> 0 == False
False

So it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work.

In general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1, but on Python 3.x, this will always be the case, no matter what.

Java - Get a list of all Classes loaded in the JVM

There are multiple answers to this question, partly due to ambiguous question - the title is talking about classes loaded by the JVM, whereas the contents of the question says "may or may not be loaded by the JVM".

Assuming that OP needs classes that are loaded by the JVM by a given classloader, and only those classes - my need as well - there is a solution (elaborated here) that goes like this:

import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class CPTest {

    private static Iterator list(ClassLoader CL)
        throws NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {
        Class CL_class = CL.getClass();
        while (CL_class != java.lang.ClassLoader.class) {
            CL_class = CL_class.getSuperclass();
        }
        java.lang.reflect.Field ClassLoader_classes_field = CL_class
                .getDeclaredField("classes");
        ClassLoader_classes_field.setAccessible(true);
        Vector classes = (Vector) ClassLoader_classes_field.get(CL);
        return classes.iterator();
    }

    public static void main(String args[]) throws Exception {
        ClassLoader myCL = Thread.currentThread().getContextClassLoader();
        while (myCL != null) {
            System.out.println("ClassLoader: " + myCL);
            for (Iterator iter = list(myCL); iter.hasNext();) {
                System.out.println("\t" + iter.next());
            }
            myCL = myCL.getParent();
        }
    }

}

One of the neat things about it is that you can choose an arbitrary classloader you want to check. It is however likely to break should internals of classloader class change, so it is to be used as one-off diagnostic tool.

Vue equivalent of setTimeout?

after encountering the same issue, I ended up on this thread. For future generation's sake: The current up-most voted answer, attempts to bind "this" to a variable in order to avoid changing the context when invoking the function which is defined in the setTimeout.

An alternate and more recommended approach(using Vue.JS 2.2 & ES6) is to use an arrow function in order to bind the context to the parent (Basically "addToBasket"'s "this" and the "setTimeout"'s "this" would still refer to the same object):

addToBasket: function(){
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        setTimeout(() => {
            this.basketAddSuccess = false;
        }, 2000);
    }

javaw.exe cannot find path

Make sure to download these from here:

enter image description here

Also create PATH enviroment variable on you computer like this (if it doesn't exist already):

  1. Right click on My Computer/Computer
  2. Properties
  3. Advanced system settings (or just Advanced)
  4. Enviroment variables
  5. If PATH variable doesn't exist among "User variables" click New (Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin; <-- please check out the right version, this may differ as Oracle keeps updating Java). ; in the end enables assignment of multiple values to PATH variable.
  6. Click OK! Done

enter image description here

To be sure that everything works, open CMD Prompt and type: java -version to check for Java version and javac to be sure that compiler responds.

enter image description here

I hope this helps. Good luck!

Convert Xml to Table SQL Server

The sp_xml_preparedocument stored procedure will parse the XML and the OPENXML rowset provider will show you a relational view of the XML data.

For details and more examples check the OPENXML documentation.

As for your question,

DECLARE @XML XML
SET @XML = '<rows><row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row></rows>'

DECLARE @handle INT  
DECLARE @PrepareXmlStatus INT  

EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML  

SELECT  *
FROM    OPENXML(@handle, '/rows/row', 2)  
    WITH (
    IdInvernadero INT,
    IdProducto INT,
    IdCaracteristica1 INT,
    IdCaracteristica2 INT,
    Cantidad INT,
    Folio INT
    )  


EXEC sp_xml_removedocument @handle 

Ignore duplicates when producing map using streams

Assuming you have people is List of object

  Map<String, String> phoneBook=people.stream()
                                        .collect(toMap(Person::getName, Person::getAddress));

Now you need two steps :

1)

people =removeDuplicate(people);

2)

Map<String, String> phoneBook=people.stream()
                                        .collect(toMap(Person::getName, Person::getAddress));

Here is method to remove duplicate

public static List removeDuplicate(Collection<Person>  list) {
        if(list ==null || list.isEmpty()){
            return null;
        }

        Object removedDuplicateList =
                list.stream()
                     .distinct()
                     .collect(Collectors.toList());
     return (List) removedDuplicateList;

      }

Adding full example here

 package com.example.khan.vaquar;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RemovedDuplicate {

    public static void main(String[] args) {
        Person vaquar = new Person(1, "Vaquar", "Khan");
        Person zidan = new Person(2, "Zidan", "Khan");
        Person zerina = new Person(3, "Zerina", "Khan");

        // Add some random persons
        Collection<Person> duplicateList = Arrays.asList(vaquar, zidan, zerina, vaquar, zidan, vaquar);

        //
        System.out.println("Before removed duplicate list" + duplicateList);
        //
        Collection<Person> nonDuplicateList = removeDuplicate(duplicateList);
        //
        System.out.println("");
        System.out.println("After removed duplicate list" + nonDuplicateList);
        ;

        // 1) solution Working code
        Map<Object, Object> k = nonDuplicateList.stream().distinct()
                .collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
        System.out.println("");
        System.out.println("Result 1 using method_______________________________________________");
        System.out.println("k" + k);
        System.out.println("_____________________________________________________________________");

        // 2) solution using inline distinct()
        Map<Object, Object> k1 = duplicateList.stream().distinct()
                .collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
        System.out.println("");
        System.out.println("Result 2 using inline_______________________________________________");
        System.out.println("k1" + k1);
        System.out.println("_____________________________________________________________________");

        //breacking code
        System.out.println("");
        System.out.println("Throwing exception _______________________________________________");
        Map<Object, Object> k2 = duplicateList.stream()
                .collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
        System.out.println("");
        System.out.println("k2" + k2);
        System.out.println("_____________________________________________________________________");
    }

    public static List removeDuplicate(Collection<Person> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }

        Object removedDuplicateList = list.stream().distinct().collect(Collectors.toList());
        return (List) removedDuplicateList;

    }

}

// Model class
class Person {
    public Person(Integer id, String fname, String lname) {
        super();
        this.id = id;
        this.fname = fname;
        this.lname = lname;
    }

    private Integer id;
    private String fname;
    private String lname;

    // Getters and Setters

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", fname=" + fname + ", lname=" + lname + "]";
    }

}

Results :

Before removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan]]

After removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan]]

Result 1 using method_______________________________________________
k{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________

Result 2 using inline_______________________________________________
k1{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________

Throwing exception _______________________________________________
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Person [id=1, fname=Vaquar, lname=Khan]
    at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
    at java.util.HashMap.merge(HashMap.java:1253)
    at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
    at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at com.example.khan.vaquar.RemovedDuplicate.main(RemovedDuplicate.java:48)

Can I invoke an instance method on a Ruby module without including it?

Firstly, I'd recommend breaking the module up into the useful things you need. But you can always create a class extending that for your invocation:

module UsefulThings
  def a
    puts "aaay"
  end
  def b
    puts "beee"
  end
end

def test
  ob = Class.new.send(:include, UsefulThings).new
  ob.a
end

test

How to get the list of files in a directory in a shell script?

The accepted answer will not return files prefix with a . To do that use

for entry in "$search_dir"/* "$search_dir"/.[!.]* "$search_dir"/..?*
do
  echo "$entry"
done

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

How do I change UIView Size?

Swift 3 and Swift 4:

myView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

SELECT Id   'PatientId',
       ISNULL(CONVERT(varchar(50),ParentId),'')  'ParentId'
FROM Patients

ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.


COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.

(It's also generally preferred because it extends to more than two arguments)

Vue.js - How to properly watch for nested data

Another way to add that I used to 'hack' this solution was to do this: I set up a seperate computed value that would simply return the nested object value.

data : function(){
    return {
        my_object : {
            my_deep_object : {
                my_value : "hello world";
            }.
        },
    };
},
computed : {
    helper_name : function(){
        return this.my_object.my_deep_object.my_value;
    },
},
watch : {
    helper_name : function(newVal, oldVal){
        // do this...
    }
}

WCF, Service attribute value in the ServiceHost directive could not be found

Add reference of service in your service or copy dll.

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

Executing periodic actions in Python

If you meant to run foo() inside a python script every 10 seconds, you can do something on these lines.

import time

def foo():
    print "Howdy"

while True:
    foo()
    time.sleep(10)

How to create an HTML button that acts like a link?

If it's the visual appearance of a button you're looking for in a basic HTML anchor tag then you can use the Twitter Bootstrap framework to format any of the following common HTML type links/buttons to appear as a button. Please note the visual differences between version 2, 3 or 4 of the framework:

<a class="btn" href="">Link</a>
<button class="btn" type="submit">Button</button>
<input class="btn" type="button" value="Input">
<input class="btn" type="submit" value="Submit">

Bootstrap (v4) sample appearance:

Sample output of Boostrap v4 buttons

Bootstrap (v3) sample appearance:

Sample output of Boostrap v3 buttons

Bootstrap (v2) sample appearance:

Sample output of Boostrap v2 buttons

Bootstrap carousel resizing image

replace your image tag with

<img src="http://localhost:6054/wp-content/themes/BLANK-Theme/images/material/images.jpg" alt="the-buzz-img3"  style="width:640px;height:360px" />

use style attribute and make sure there is no css class for image which set image height and width