Programs & Examples On #Workitem

Workitems are used for tracking work within TFS.

How to filter an array/object by checking multiple values

You can use .filter() method of the Array object:

var filtered = workItems.filter(function(element) {
   // Create an array using `.split()` method
   var cats = element.category.split(' ');

   // Filter the returned array based on specified filters
   // If the length of the returned filtered array is equal to
   // length of the filters array the element should be returned  
   return cats.filter(function(cat) {
       return filtersArray.indexOf(cat) > -1;
   }).length === filtersArray.length;
});

http://jsfiddle.net/6RBnB/

Some old browsers like IE8 doesn't support .filter() method of the Array object, if you are using jQuery you can use .filter() method of jQuery object.

jQuery version:

var filtered = $(workItems).filter(function(i, element) {
   var cats = element.category.split(' ');

    return $(cats).filter(function(_, cat) {
       return $.inArray(cat, filtersArray) > -1;
    }).length === filtersArray.length;
});

Can typescript export a function?

It's hard to tell what you're going for in that example. exports = is about exporting from external modules, but the code sample you linked is an internal module.

Rule of thumb: If you write module foo { ... }, you're writing an internal module; if you write export something something at top-level in a file, you're writing an external module. It's somewhat rare that you'd actually write export module foo at top-level (since then you'd be double-nesting the name), and it's even rarer that you'd write module foo in a file that had a top-level export (since foo would not be externally visible).

The following things make sense (each scenario delineated by a horizontal rule):


// An internal module named SayHi with an exported function 'foo'
module SayHi {
    export function foo() {
       console.log("Hi");
    }

    export class bar { }
}

// N.B. this line could be in another file that has a
// <reference> tag to the file that has 'module SayHi' in it
SayHi.foo();
var b = new SayHi.bar();

file1.ts

// This *file* is an external module because it has a top-level 'export'
export function foo() {
    console.log('hi');
}

export class bar { }

file2.ts

// This file is also an external module because it has an 'import' declaration
import f1 = module('file1');
f1.foo();
var b = new f1.bar();

file1.ts

// This will only work in 0.9.0+. This file is an external
// module because it has a top-level 'export'
function f() { }
function g() { }
export = { alpha: f, beta: g };

file2.ts

// This file is also an external module because it has an 'import' declaration
import f1 = require('file1');
f1.alpha(); // invokes f
f1.beta(); // invokes g

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

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

If you want the super-hacky way to do it:

cat .git/`cat .git/HEAD | cut -d \  -f 2`

Basically, git stores the location of HEAD in .git/HEAD, in the form ref: {path from .git}. This command reads that out, slices off the "ref: ", and reads out whatever file it pointed to.

This, of course, will fail in detached-head mode, as HEAD won't be "ref:...", but the hash itself - but you know, I don't think you expect that much smarts in your bash one-liners. If you don't think semicolons are cheating, though...

HASH="ref: HEAD"; while [[ $HASH == ref\:* ]]; do HASH="$(cat ".git/$(echo $HASH | cut -d \  -f 2)")"; done; echo $HASH

How do I combine 2 select statements into one?

select t1.* from 
(select * from TABLE Where CCC='D' AND DDD='X') as t1,
(select * from TABLE Where CCC<>'D' AND DDD='X') as t2

Another way to do this!

How can you find out which process is listening on a TCP or UDP port on Windows?

Type in the command: netstat -aon | findstr :DESIRED_PORT_NUMBER

For example, if I want to find port 80: netstat -aon | findstr :80

This answer was originally posted to this question.

How to avoid Number Format Exception in java?

To Determine if a string is Int or Float and to represent in longer format.

Integer

 String  cost=Long.MAX_VALUE+"";
  if (isNumeric (cost))    // returns false for non numeric
  {  
      BigInteger bi  = new BigInteger(cost);

  }

public static boolean isNumeric(String str) 
{ 
  NumberFormat formatter = NumberFormat.getInstance(); 
  ParsePosition pos = new ParsePosition(0); 
  formatter.parse(str, pos); 
  return str.length() == pos.getIndex(); 
} 

How to create EditText accepts Alphabets only in android?

Try This Method

For Java :

EditText yourEditText = (EditText) findViewById(R.id.yourEditText);
yourEditText.setFilters(new InputFilter[] {
new InputFilter() {
    @Override
    public CharSequence filter(CharSequence cs, int start,
                int end, Spanned spanned, int dStart, int dEnd) {
        // TODO Auto-generated method stub
        if(cs.equals("")){ // for backspace
             return cs;
        }
        if(cs.toString().matches("[a-zA-Z ]+")){
             return cs;
        }
        return "";
    }
}});

For Kotlin :

 val yourEditText = findViewById<View>(android.R.id.yourEditText) as EditText
    val reges = Regex("^[0-9a-zA-Z ]+$")
    //this will allow user to only write letter and white space
    yourEditText.filters = arrayOf<InputFilter>(
        object : InputFilter {
            override fun filter(
                cs: CharSequence, start: Int,
                end: Int, spanned: Spanned?, dStart: Int, dEnd: Int,
            ): CharSequence? {
                if (cs == "") { // for backspace
                    return cs
                }
                return if (cs.toString().matches(reges)) {
                    cs
                } else ""
            }
        }
    )

Custom ImageView with drop shadow

My dirty solution:

private static Bitmap getDropShadow3(Bitmap bitmap) {

    if (bitmap==null) return null;
    int think = 6;
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int newW = w - (think);
    int newH = h - (think);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas c = new Canvas(bmp);

    // Right
    Shader rshader = new LinearGradient(newW, 0, w, 0, Color.GRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
    paint.setShader(rshader);
    c.drawRect(newW, think, w, newH, paint);

    // Bottom
    Shader bshader = new LinearGradient(0, newH, 0, h, Color.GRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
    paint.setShader(bshader);
    c.drawRect(think, newH, newW  , h, paint);

    //Corner
    Shader cchader = new LinearGradient(0, newH, 0, h, Color.LTGRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
    paint.setShader(cchader);
    c.drawRect(newW, newH, w  , h, paint);


    c.drawBitmap(sbmp, 0, 0, null);

    return bmp;
}

result: enter image description here

Difference between binary semaphore and mutex

The concept was clear to me after going over above posts. But there were some lingering questions. So, I wrote this small piece of code.

When we try to give a semaphore without taking it, it goes through. But, when you try to give a mutex without taking it, it fails. I tested this on a Windows platform. Enable USE_MUTEX to run the same code using a MUTEX.

#include <stdio.h>
#include <windows.h>
#define xUSE_MUTEX 1
#define MAX_SEM_COUNT 1

DWORD WINAPI Thread_no_1( LPVOID lpParam );
DWORD WINAPI Thread_no_2( LPVOID lpParam );

HANDLE Handle_Of_Thread_1 = 0;
HANDLE Handle_Of_Thread_2 = 0;
int Data_Of_Thread_1 = 1;
int Data_Of_Thread_2 = 2;
HANDLE ghMutex = NULL;
HANDLE ghSemaphore = NULL;


int main(void)
{

#ifdef USE_MUTEX
    ghMutex = CreateMutex( NULL, FALSE, NULL);
    if (ghMutex  == NULL) 
    {
        printf("CreateMutex error: %d\n", GetLastError());
        return 1;
    }
#else
    // Create a semaphore with initial and max counts of MAX_SEM_COUNT
    ghSemaphore = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);
    if (ghSemaphore == NULL) 
    {
        printf("CreateSemaphore error: %d\n", GetLastError());
        return 1;
    }
#endif
    // Create thread 1.
    Handle_Of_Thread_1 = CreateThread( NULL, 0,Thread_no_1, &Data_Of_Thread_1, 0, NULL);  
    if ( Handle_Of_Thread_1 == NULL)
    {
        printf("Create first thread problem \n");
        return 1;
    }

    /* sleep for 5 seconds **/
    Sleep(5 * 1000);

    /*Create thread 2 */
    Handle_Of_Thread_2 = CreateThread( NULL, 0,Thread_no_2, &Data_Of_Thread_2, 0, NULL);  
    if ( Handle_Of_Thread_2 == NULL)
    {
        printf("Create second thread problem \n");
        return 1;
    }

    // Sleep for 20 seconds
    Sleep(20 * 1000);

    printf("Out of the program \n");
    return 0;
}


int my_critical_section_code(HANDLE thread_handle)
{

#ifdef USE_MUTEX
    if(thread_handle == Handle_Of_Thread_1)
    {
        /* get the lock */
        WaitForSingleObject(ghMutex, INFINITE);
        printf("Thread 1 holding the mutex \n");
    }
#else
    /* get the semaphore */
    if(thread_handle == Handle_Of_Thread_1)
    {
        WaitForSingleObject(ghSemaphore, INFINITE);
        printf("Thread 1 holding semaphore \n");
    }
#endif

    if(thread_handle == Handle_Of_Thread_1)
    {
        /* sleep for 10 seconds */
        Sleep(10 * 1000);
#ifdef USE_MUTEX
        printf("Thread 1 about to release mutex \n");
#else
        printf("Thread 1 about to release semaphore \n");
#endif
    }
    else
    {
        /* sleep for 3 secconds */
        Sleep(3 * 1000);
    }

#ifdef USE_MUTEX
    /* release the lock*/
    if(!ReleaseMutex(ghMutex))
    {
        printf("Release Mutex error in thread %d: error # %d\n", (thread_handle == Handle_Of_Thread_1 ? 1:2),GetLastError());
    }
#else
    if (!ReleaseSemaphore(ghSemaphore,1,NULL) )      
    {
        printf("ReleaseSemaphore error in thread %d: error # %d\n",(thread_handle == Handle_Of_Thread_1 ? 1:2), GetLastError());
    }
#endif

    return 0;
}

DWORD WINAPI Thread_no_1( LPVOID lpParam ) 
{ 
    my_critical_section_code(Handle_Of_Thread_1);
    return 0;
}


DWORD WINAPI Thread_no_2( LPVOID lpParam ) 
{
    my_critical_section_code(Handle_Of_Thread_2);
    return 0;
}

The very fact that semaphore lets you signal "it is done using a resource", even though it never owned the resource, makes me think there is a very loose coupling between owning and signaling in the case of semaphores.

How do I convert a number to a numeric, comma-separated formatted string?

I looked at several of the options. Here are my two favorites, because I needed to round the value.

,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(BigNbr / 0.128),0)as money),1), '.00','')
,DataSizeKB2   = format(Round(SUM(BigNbr / 0.128),0),'##,##0')
-----------------
--- below if the full script where I left DataSizeKB in both methods -----------
--- enjoy --------- 
--- Hank Freeman : [email protected] 
-----------------------------------
--- Scritp to get rowcounts and Memory size of index and Primary Keys
   SELECT
   FileGroupName = DS.name
   ,FileGroupType =
      CASE DS.[type]
        WHEN 'FG' THEN 'Filegroup'
        WHEN 'FD' THEN 'Filestream'
        WHEN 'FX' THEN 'Memory-optimized'
        WHEN 'PS' THEN 'Partition Scheme'
        ELSE 'Unknown'
      END
   ,SchemaName = SCH.name
   ,TableName = OBJ.name
   ,IndexType =
      CASE IDX.[type]
        WHEN 0 THEN 'Heap'
        WHEN 1 THEN 'Clustered'
        WHEN 2 THEN 'Nonclustered'
        WHEN 3 THEN 'XML'
        WHEN 4 THEN 'Spatial'
        WHEN 5 THEN 'Clustered columnstore'
        WHEN 6 THEN 'Nonclustered columnstore'
        WHEN 7 THEN 'Nonclustered hash'
      END
   ,IndexName = IDX.name
   ,RowCounts = replace(convert(varchar,Cast(p.rows as money),1), '.00','')  --- MUST show for all types when no Primary key
   --,( Case WHEN IDX.[type] IN (2,6,7) then 0  else  p.rows  end )as Rowcounts_T
   ,AllocationDesc = AU.type_desc
/*
   ,RowCounts = p.rows  --- MUST show for all types when no Primary key
   ,TotalSizeKB2  = Cast(Round(SUM(AU.total_pages / 0.128),0)as int) -- 128 pages per megabyte
   ,UsedSizeKB    = Cast(Round(SUM(AU.used_pages / 0.128),0)as int) 
   ,DataSizeKB    = Cast(Round(SUM(AU.data_pages / 0.128),0)as int)
    --replace(convert(varchar,cast(1234567 as money),1), '.00','')
*/
   ,TotalSizeKB   = replace(convert(varchar,Cast(Round(SUM(AU.total_pages / 0.128),0)as money),1), '.00','') -- 128 pages per megabyte
   ,UsedSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.used_pages / 0.128),0)as money),1), '.00','') 
   ,DataSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.data_pages / 0.128),0)as money),1), '.00','')
   ,DataSizeKB2   = format(Round(SUM(AU.data_pages / 0.128),0),'##,##0')
   ,DataSizeKB3   = format(SUM(AU.data_pages / 0.128),'##,##0')
   --SELECT Format(1234567.8, '##,##0.00')
   ---
   ,is_default    = CONVERT(INT,DS.is_default)
   ,is_read_only = CONVERT(INT,DS.is_read_only)
  FROM
   sys.filegroups DS -- you could also use sys.data_spaces
    LEFT JOIN sys.allocation_units AU ON DS.data_space_id = AU.data_space_id
    LEFT JOIN sys.partitions PA
      ON (AU.[type] IN (1,3) AND
          AU.container_id = PA.hobt_id) OR
         (AU.[type] = 2 AND
          AU.container_id = PA.[partition_id])
    LEFT JOIN sys.objects OBJ ON PA.[object_id] = OBJ.[object_id]
    LEFT JOIN sys.schemas SCH ON OBJ.[schema_id] = SCH.[schema_id]
    LEFT JOIN sys.indexes IDX
      ON PA.[object_id] = IDX.[object_id] AND
         PA.index_id = IDX.index_id
    -----
    INNER JOIN 
      sys.partitions p ON obj.object_id = p.OBJECT_ID AND IDX.index_id = p.index_id
  WHERE
    OBJ.type_desc = 'USER_TABLE' -- only include user tables
    OR
    DS.[type] = 'FD' -- or the filestream filegroup
  GROUP BY
    DS.name ,SCH.name ,OBJ.name ,IDX.[type] ,IDX.name ,DS.[type]  ,DS.is_default   ,DS.is_read_only -- discard different allocation units
   ,p.rows  ,AU.type_desc  --- 
  ORDER BY
    DS.name ,SCH.name ,OBJ.name ,IDX.name
   ---
   ;

If '<selector>' is an Angular component, then verify that it is part of this module

I am using Angular v11 and was facing this error while trying to lazy load a component (await import('./my-component.component')) and even if import and export were correctly set.

I finally figured out that the solution was deleting the separate dedicated module's file and move the module content inside the component file itself.

rm -r my-component.module.ts

and add module inside my-component.ts (same file)

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.page.html',
  styleUrls: ['./my-component.page.scss'],
})
export class MyComponent {
}

@NgModule({
  imports: [CommonModule],
  declarations: [MyComponent],
})
export class MyComponentModule {}

Angular 2: How to style host element of the component?

Try the :host > /deep/ :

Add the following to the parent.component.less file

:host {
    /deep/ app-child-component {
       //your child style
    }
}

Replace the app-child-component by your child selector

How to include a child object's child object in Entity Framework 5

I ended up doing the following and it works:

return DatabaseContext.Applications
     .Include("Children.ChildRelationshipType");

How to initialize var?

C# is a strictly/strongly typed language. var was introduced for compile-time type-binding for anonymous types yet you can use var for primitive and custom types that are already known at design time. At runtime there's nothing like var, it is replaced by an actual type that is either a reference type or value type.

When you say,

var x = null; 

the compiler cannot resolve this because there's no type bound to null. You can make it like this.

string y = null;
var x = y;

This will work because now x can know its type at compile time that is string in this case.

Sending POST data in Android

Better use Apache Commons HttpClient, that is also included in android already. Have a look at Android Developer: Apache HTTP Client Package Summary for general api info.

How can I completely uninstall nodejs, npm and node in Ubuntu

It is better to remove NodeJS and its modules manually because installation leaves a lot of files, links and modules behind and later this creates problems when we reconfigure another version of NodeJS and its modules.

To remove the files, run the following commands:

sudo rm -rf /usr/local/bin/npm 
sudo rm -rf /usr/local/share/man/man1/node* 
sudo rm -rf /usr/local/lib/dtrace/node.d
rm -rf ~/.npm
rm -rf ~/.node-gyp
sudo rm -rf /opt/local/bin/node
sudo rm -rf /opt/local/include/node
sudo rm -rf /opt/local/lib/node_modules
sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*

I have posted a step by step guide with commands on my blog: AMCOS IT Support For Windows and Linux: To completely uninstall node js from Ubuntu.

How to center a label text in WPF?

Sample:

Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;

Find and replace in file and overwrite file doesn't work, it empties the file

When the shell sees > index.html in the command line it opens the file index.html for writing, wiping off all its previous contents.

To fix this you need to pass the -i option to sed to make the changes inline and create a backup of the original file before it does the changes in-place:

sed -i.bak s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html

Without the .bak the command will fail on some platforms, such as Mac OSX.

How to take backup of a single table in a MySQL database?

You can use easily to dump selected tables using MYSQLWorkbench tool ,individually or group of tables at one dump then import it as follow: also u can add host information if u are running it in your local by adding -h IP.ADDRESS.NUMBER after-u username

mysql -u root -p databasename < dumpfileFOurTableInOneDump.sql 

Why is the use of alloca() not considered good practice?

One pitfall with alloca is that longjmp rewinds it.

That is to say, if you save a context with setjmp, then alloca some memory, then longjmp to the context, you may lose the alloca memory. The stack pointer is back where it was and so the memory is no longer reserved; if you call a function or do another alloca, you will clobber the original alloca.

To clarify, what I'm specifically referring to here is a situation whereby longjmp does not return out of the function where the alloca took place! Rather, a function saves context with setjmp; then allocates memory with alloca and finally a longjmp takes place to that context. That function's alloca memory is not all freed; just all the memory that it allocated since the setjmp. Of course, I'm speaking about an observed behavior; no such requirement is documented of any alloca that I know.

The focus in the documentation is usually on the concept that alloca memory is associated with a function activation, not with any block; that multiple invocations of alloca just grab more stack memory which is all released when the function terminates. Not so; the memory is actually associated with the procedure context. When the context is restored with longjmp, so is the prior alloca state. It's a consequence of the stack pointer register itself being used for allocation, and also (necessarily) saved and restored in the jmp_buf.

Incidentally, this, if it works that way, provides a plausible mechanism for deliberately freeing memory that was allocated with alloca.

I have run into this as the root cause of a bug.

Search of table names

You can also use the Filter button to filter tables with a certain string in it. You can do the same with stored procedures and views.

enter image description here

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

AlertDialog styling - how to change style (color) of title, message, etc

I changed color programmatically in this way :

var builder = new AlertDialog.Builder (this);
...
...
...
var dialog = builder.Show ();
int textColorId = Resources.GetIdentifier ("alertTitle", "id", "android");
TextView textColor = dialog.FindViewById<TextView> (textColorId);
textColor?.SetTextColor (Color.DarkRed);

as alertTitle, you can change other data by this way (next example is for titleDivider):

int titleDividerId = Resources.GetIdentifier ("titleDivider", "id", "android");
View titleDivider = dialog.FindViewById (titleDividerId);
titleDivider?.SetBackgroundColor (Color.Red);

this is in C#, but in java it is the same.

Can jQuery get all CSS styles associated with an element?

Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.

Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.

jquery.getStyleObject.js:

/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 */

(function($){
    $.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            };
            style = window.getComputedStyle(dom, null);
            for(var i = 0, l = style.length; i < l; i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            };
            return returns;
        };
        if(style = dom.currentStyle){
            for(var prop in style){
                returns[prop] = style[prop];
            };
            return returns;
        };
        return this.css();
    }
})(jQuery);

Basic usage is pretty simple, but he's written a function for that as well:

$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}

Hope that helps.

Your project contains error(s), please fix it before running it

I had this exact same problem. One solution that would work would be to create a brand new project, but I don't think there's any need for that. For me the problem was that the debug certificate that gets auto-generated had expired. Deleting this file allowed Eclipse to rebuild that file, which solved the problem. You can't run an app with an invalid certificate, whether it be a debug or release certificate. Note that cleaning my project did not work. For more information, see: "Debug certificate expired" error in Eclipse Android plugins

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

This is the only command that worked for me. (I got it from M 8.0 documentation)

ALTER USER 'root'@'*' IDENTIFIED WITH mysql_native_password BY 'YOURPASSWORD';
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YOURPASSWORD';

How to convert a string to utf-8 in Python

  • First, str in Python is represented in Unicode.
  • Second, UTF-8 is an encoding standard to encode Unicode string to bytes. There are many encoding standards out there (e.g. UTF-16, ASCII, SHIFT-JIS, etc.).

When the client sends data to your server and they are using UTF-8, they are sending a bunch of bytes not str.

You received a str because the "library" or "framework" that you are using, has implicitly converted some random bytes to str.

Under the hood, there is just a bunch of bytes. You just need ask the "library" to give you the request content in bytes and you will handle the decoding yourself (if library can't give you then it is trying to do black magic then you shouldn't use it).

  • Decode UTF-8 encoded bytes to str: bs.decode('utf-8')
  • Encode str to UTF-8 bytes: s.encode('utf-8')

How do I remove a specific element from a JSONArray?

To Remove some element from Listview in android then it will remove your specific element and Bind it to listview.

BookinhHistory_adapter.this.productPojoList.remove(position);

BookinhHistory_adapter.this.notifyDataSetChanged();

How to edit .csproj file

For JetBrains Rider:

First Option

  1. Unload Project
  2. Double click the unloaded project

Second option:

  1. Click on the project
  2. Press F4

That's it!

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Open Popup window using javascript

Change the window name in your two different calls:

function popitup(url,windowName) {
       newwindow=window.open(url,windowName,'height=200,width=150');
       if (window.focus) {newwindow.focus()}
       return false;
     }

windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.

Displaying all table names in php from MySQL database

For people that are using PDO statements

$query = $db->prepare('show tables');
$query->execute();

while($rows = $query->fetch(PDO::FETCH_ASSOC)){
     var_dump($rows);
}

how to set radio button checked in edit mode in MVC razor view

Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:

Controller:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
        user.user_gender = collection["rdbtnGender"];
        return RedirectToAction("Index");
    }
    catch(Exception e)
    {
        throw e;
    }
}

public ActionResult Edit(int id)
{
    CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
    ViewBag.UserObj = user;
    return View();
}

VIEW:

Create:

<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label  for="rdbtnGender2">FEMALE</label>

Edit:

<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" @(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>

<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" @(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>

How do you attach and detach from Docker's process?

To detach from a running container, use ^P^Q (hold Ctrl, press P, press Q, release Ctrl).

There's a catch: this only works if the container was started with both -t and -i.

If you have a running container that was started without one (or both) of these options, and you attach with docker attach, you'll need to find another way to detach. Depending on the options you chose and the program that's running, ^C may work, or it may kill the whole container. You'll have to experiment.

Another catch: Depending on the programs you're using, your terminal, shell, SSH client, or multiplexer could be intercepting either ^P or ^Q (usually the latter). To test whether this is the issue, try running or attaching with the --detach-keys z argument. You should now be able to detach by pressing z, without any modifiers. If this works, another program is interfering. The easiest way to work around this is to set your own detach sequence using the --detach-keys argument. (For example, to exit with ^K, use --detach-keys 'ctrl-k'.) Alternatively, you can attempt to disable interception of the keys in your terminal or other interfering program. For example, stty start '' or stty start undef may prevent the terminal from intercepting ^Q on some POSIX systems, though I haven't found this to be helpful.

Hibernate: How to set NULL query-parameter value with HQL?

Here is the solution I found on Hibernate 4.1.9. I had to pass a parameter to my query that can have value NULL sometimes. So I passed the using:

setParameter("orderItemId", orderItemId, new LongType())

After that, I use the following where clause in my query:

where ((:orderItemId is null) OR (orderItem.id != :orderItemId))

As you can see, I am using the Query.setParameter(String, Object, Type) method, where I couldn't use the Hibernate.LONG that I found in the documentation (probably that was on older versions). For a full set of options of type parameter, check the list of implementation class of org.hibernate.type.Type interface.

Hope this helps!

Getting a "This application is modifying the autolayout engine from a background thread" error?

I had the same issue when trying to update error message in UILabel in the same ViewController (it takes a little while to update data when trying to do that with normal coding). I used DispatchQueue in Swift 3 Xcode 8 and it works.

C# DateTime to "YYYYMMDDHHMMSS" format

An easy Method, Full control over 'from type' and 'to type', and only need to remember this code for future castings

DateTime.ParseExact(InputDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd"));

Transform only one axis to log10 scale with ggplot2

Another solution using scale_y_log10 with trans_breaks, trans_format and annotation_logticks()

library(ggplot2)

m <- ggplot(diamonds, aes(y = price, x = color))

m + geom_boxplot() +
  scale_y_log10(
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  theme_bw() +
  annotation_logticks(sides = 'lr') +
  theme(panel.grid.minor = element_blank())

Flutter Circle Design

you can use decoration like this :

   Container(
                    width: 60,
                    height: 60,
                    child: Icon(CustomIcons.option, size: 20,),
                    decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Color(0xFFe0f2f1)),
                  )

Now you have circle shape and Icon on it.

enter image description here

error: ORA-65096: invalid common user or role name in oracle

SQL> alter session set "_ORACLE_SCRIPT"=true;  
SQL> create user sec_admin identified by "Chutinhbk123@!";

What is a difference between unsigned int and signed int in C?

Assuming int is a 16 bit integer (which depends on the C implementation, most are 32 bit nowadays) the bit representation differs like the following:

 5 = 0000000000000101
-5 = 1111111111111011

if binary 1111111111111011 would be set to an unsigned int, it would be decimal 65531.

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

You can get the same error in Asp.net MVC5 if you have a class name and a folder with a matching name Example : If you have class lands where when you want to see view/lands/index.cshtml file, if you also have a folder with name 'lands' you get the error as it first try the lands folder

How to set MimeBodyPart ContentType to "text/html"?

There is a method setText() which takes 3 arguments :

public void setText(String text, String charset, String subtype)
    throws MessagingException

Parameters:

text - the text content to set
charset - the charset to use for the text
subtype - the MIME subtype to use (e.g., "html")

NOTE: the subtype takes text after / in MIME types so for ex.

  • text/html would be html
  • text/css would be css
  • and so on..

psql - save results of command to a file

The psql \o command was already described by jhwist.

An alternative approach is using the COPY TO command to write directly to a file on the server. This has the advantage that it's dumped in an easy-to-parse format of your choice -- rather than psql's tabulated format. It's also very easy to import to another table/database using COPY FROM.

NB! This requires superuser privileges and will write to a file on the server.

Example: COPY (SELECT foo, bar FROM baz) TO '/tmp/query.csv' (format csv, delimiter ';')

Creates a CSV file with ';' as the field separator.

As always, see the documentation for details

How to keep environment variables when using sudo

A simple wrapper function (or in-line for loop)

I came up with a unique solution because:

  • sudo -E "$@" was leaking variables that was causing problems for my command
  • sudo VAR1="$VAR1" ... VAR42="$VAR42" "$@" was long and ugly in my case

demo.sh

#!/bin/bash

function sudo_exports(){
    eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$@"
}

# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' > sudo_test.sh
chmod +x sudo_test.sh

export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."

export _EXPORTS="_EXPORTS VAR1 VAR2 VAR3 VAR4 VAR5 VAR6 VAR7 VAR8 VAR9 VAR10 VAR11 VAR12 VAR13 VAR14 VAR15 VAR16 VAR17 VAR18 VAR19 VAR20 VAR21 VAR22 VAR23 VAR24 VAR25 VAR26 VAR27 VAR28 VAR29 VAR30 VAR31 VAR32 VAR33 VAR34 VAR35 VAR36 VAR37 VAR38 VAR39 VAR40 VAR41 VAR42"

# clean function style
sudo_exports ./sudo_test.sh

# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./sudo_test.sh

Result

$ ./demo.sh
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.

How?

This is made possible by a feature of the bash builtin printf. The %q produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0

Select every Nth element in CSS

As the name implies, :nth-child() allows you to construct an arithmetic expression using the n variable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (an where a is an integer, including positive numbers, negative numbers and zero).

Here's how you would rewrite the above selector list:

div:nth-child(4n)

For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.

Note that this answer assumes that all of the child elements within the same parent element are of the same element type, div. If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type() instead of :nth-child() to ensure you only count div elements:

<body>
  <h1></h1>
  <div>1</div>  <div>2</div>
  <div>3</div>  <div>4</div>
  <h2></h2>
  <div>5</div>  <div>6</div>
  <div>7</div>  <div>8</div>
  <h2></h2>
  <div>9</div>  <div>10</div>
  <div>11</div> <div>12</div>
  <h2></h2>
  <div>13</div> <div>14</div>
  <div>15</div> <div>16</div>
</body>

For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.


By the way, there's not much of a difference between 4n and 4n + 4 with regards to :nth-child(). If you use the n variable, it starts counting at 0. This is what each selector would match:

:nth-child(4n)

4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16
...

:nth-child(4n+4)

4(0) + 4 = 0  + 4 = 4
4(1) + 4 = 4  + 4 = 8
4(2) + 4 = 8  + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20
...

As you can see, both selectors will match the same elements as above. In this case, there is no difference.

How can I check the current status of the GPS receiver?

With LocationManager you can getLastKnownLocation() after you getBestProvider(). This gives you a Location object, which has the methods getAccuracy() in meters and getTime() in UTC milliseconds

Does this give you enough info?

Or perhaps you could iterate over the LocationProviders and find out if each one meetsCriteria( ACCURACY_COARSE )

HttpClient does not exist in .net 4.0: what can I do?

Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):

    HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
    http.Referer = referrer;
    HttpWebResponse response = (HttpWebResponse )http.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        string responseJson = sr.ReadToEnd();
        // more stuff
    }

Does Enter key trigger a click event?

Use (keyup.enter).

Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter pseudo-event.

Difference between decimal, float and double in .NET?

I won't reiterate tons of good (and some bad) information already answered in other answers and comments, but I will answer your followup question with a tip:

When would someone use one of these?

Use decimal for counted values

Use float/double for measured values

Some examples:

  • money (do we count money or measure money?)

  • distance (do we count distance or measure distance? *)

  • scores (do we count scores or measure scores?)

We always count money and should never measure it. We usually measure distance. We often count scores.

* In some cases, what I would call nominal distance, we may indeed want to 'count' distance. For example, maybe we are dealing with country signs that show distances to cities, and we know that those distances never have more than one decimal digit (xxx.x km).

How to save the output of a console.log(object) to a file?

You can use the Chrome DevTools Utilities API copy() command for copying the string representation of the specified object to the clipboard.

If you have lots of objects then you can actually JSON.stringify() all your objects and keep on appending them to a string. Now use copy() method to copy the complete string to clipboard.

Convert Year/Month/Day to Day of Year in Python

Use datetime.timetuple() to convert your datetime object to a time.struct_time object then get its tm_yday property:

from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday  # returns 1 for January 1st

make iframe height dynamic based on content inside- JQUERY/Javascript

Just in case this helps anyone. I was pulling my hair out trying to get this to work, then I noticed that the iframe had a class entry with height:100%. When I removed this, everything worked as expected. So, please check for any css conflicts.

HTML Table width in percentage, table rows separated equally

you can try this, I would do it with CSS, but i think you want it with tables without CSS.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <body leftmargin=0 rightmargin=0>
      <table cellpadding="0" cellspacing="0" width="100%" border="1" height="350px"> 
         <tr>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
         </tr>
      </table> 
   </body>
</html>

Write Array to Excel Range

when you want to write a 1D Array in a Excel sheet you have to transpose it and you don't have to create a 2D array with 1 column ([n, 1]) as I read above! Here is a example of code :

 wSheet.Cells(RowIndex, colIndex).Resize(RowsCount, ).Value = _excel.Application.transpose(My1DArray)

Have a good day, Gilles

Specifying onClick event type with Typescript and React.Konva

You're probably out of luck without some hack-y workarounds

You could try

onClick={(event: React.MouseEvent<HTMLElement>) => {
 makeMove(ownMark, (event.target as any).index)
}}

I'm not sure how strict your linter is - that might shut it up just a little bit

I played around with it for a bit, and couldn't figure it out, but you can also look into writing your own augmented definitions: https://www.typescriptlang.org/docs/handbook/declaration-merging.html

edit: please use the implementation in this reply it is the proper way to solve this issue (and also upvote him, while you're at it).

How do you remove the title text from the Android ActionBar?

as a workaround just add this line incase you have custom action/toolbars

this.setTitle("");

in your Activity

Print the data in ResultSet along with column names

1) Instead of PreparedStatement use Statement

2) After executing query in ResultSet, extract values with the help of rs.getString() as :

Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
    rs.getString(1); //or rs.getString("column name");
}

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

My requirement is to display 10 digit phone number in the jsp. So here's the setup for me.
MySQL: numeric(10)

Java Side:

@NumberFormat(pattern = "#")  
private long mobileNumber;

and it worked!

How to create a Restful web service with input parameters?

You can. Try something like this:

@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
    @PathParam("varY") String varY) {
        Todo todo = new Todo();
        todo.setSummary(varX);
        todo.setDescription(varY);
        return todo;
}

Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description

Eloquent ->first() if ->exists()

Note: The first() method doesn't throw an exception as described in the original question. If you're getting this kind of exception, there is another error in your code.

The correct way to user first() and check for a result:

$user = User::where('mobile', Input::get('mobile'))->first(); // model or null
if (!$user) {
   // Do stuff if it doesn't exist.
}

Other techniques (not recommended, unnecessary overhead):

$user = User::where('mobile', Input::get('mobile'))->get();

if (!$user->isEmpty()){
    $firstUser = $user->first()
}

or

try {
    $user = User::where('mobile', Input::get('mobile'))->firstOrFail();
    // Do stuff when user exists.
} catch (ErrorException $e) {
    // Do stuff if it doesn't exist.
}

or

// Use either one of the below. 
$users = User::where('mobile', Input::get('mobile'))->get(); //Collection

if (count($users)){
    // Use the collection, to get the first item use $users->first().
    // Use the model if you used ->first();
}

Each one is a different way to get your required result.

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

Check if IIS Express is installed. If IIS Express is missing, Visual Studio might discard the setting <UseIISExpress>false</UseIISExpress> and still look for the express.

Angular : Manual redirect to route

You may have enough correct answers for your question but in case your IDE gives you the warning

Promise returned from navigate is ignored

you may either ignore that warning or use this.router.navigate(['/your-path']).then().

"Cannot update paths and switch to branch at the same time"

You should go the submodule dir and run git status.

You may see a lot of files were deleted. You may run

  1. git reset .

  2. git checkout .

  3. git fetch -p

  4. git rm --cached submodules //submoudles is your name

  5. git submoudle add ....

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

How do I diff the same file between two different commits on the same branch?

All the other responses are more complete, so upvote them. This one is just to remember that you can avoid knowing the id of the recent commit. Usually, I set my self in the branch that I want to compare and run diff tools knowing the old commit uid (You can use other notations):

git checkout master
git difftool 6f8bba my/file/relative/path.py

Also, check this other response here to set the tool you want git open to compare the file: Configuring diff tool with .gitconfig And to learn more about difftool, go to the difftool doc

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

You need to do this in transaction to ensure two simultaneous clients won't insert same fieldValue twice:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
    DECLARE @id AS INT
    SELECT @id = tableId FROM table WHERE fieldValue=@newValue
    IF @id IS NULL
    BEGIN
       INSERT INTO table (fieldValue) VALUES (@newValue)
       SELECT @id = SCOPE_IDENTITY()
    END
    SELECT @id
COMMIT TRANSACTION

you can also use Double-checked locking to reduce locking overhead

DECLARE @id AS INT
SELECT @id = tableID FROM table (NOLOCK) WHERE fieldValue=@newValue
IF @id IS NULL
BEGIN
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
    BEGIN TRANSACTION
        SELECT @id = tableID FROM table WHERE fieldValue=@newValue
        IF @id IS NULL
        BEGIN
           INSERT INTO table (fieldValue) VALUES (@newValue)
           SELECT @id = SCOPE_IDENTITY()
        END
    COMMIT TRANSACTION
END
SELECT @id

As for why ISOLATION LEVEL SERIALIZABLE is necessary, when you are inside a serializable transaction, the first SELECT that hits the table creates a range lock covering the place where the record should be, so nobody else can insert the same record until this transaction ends.

Without ISOLATION LEVEL SERIALIZABLE, the default isolation level (READ COMMITTED) would not lock the table at read time, so between SELECT and UPDATE, somebody would still be able to insert. Transactions with READ COMMITTED isolation level do not cause SELECT to lock. Transactions with REPEATABLE READS lock the record (if found) but not the gap.

Python safe method to get value of nested dictionary

Little improvement to reduce approach to make it work with list. Also using data path as string divided by dots instead of array.

def deep_get(dictionary, path):
    keys = path.split('.')
    return reduce(lambda d, key: d[int(key)] if isinstance(d, list) else d.get(key) if d else None, keys, dictionary)

Passing data from controller to view in Laravel

In Laravel 5.6:

$variable = model_name::find($id);
return view('view')->with ('variable',$variable);

ComboBox: Adding Text and Value to an Item (no Binding Source)

This is one of the ways that just came to mind:

combo1.Items.Add(new ListItem("Text", "Value"))

And to change text of or value of an item, you can do it like this:

combo1.Items[0].Text = 'new Text';

combo1.Items[0].Value = 'new Value';

There is no class called ListItem in Windows Forms. It only exists in ASP.NET, so you will need to write your own class before using it, the same as @Adam Markowitz did in his answer.

Also check these pages, they may help:

jQuery Ajax PUT with parameters

Can you provide an example, because put should work fine as well?

Documentation -

The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url) -

$.ajax({
  url: '/echo/html/',
  type: 'PUT',
  data: "name=John&location=Boston",
  success: function(data) {
    alert('Load was performed.');
  }
});

Demo tested from jQuery 1.3.2 onwards on Chrome.

How to make several plots on a single page using matplotlib?

This works also:

for i in range(19):
    plt.subplot(5,4,i+1) 

It plots 19 total graphs on one page. The format is 5 down and 4 across..

Want to make Font Awesome icons clickable

You can wrap those elements in anchor tag

like this

<a href="your link here"> <i class="fa fa-dribbble fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-behance-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-linkedin-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-twitter-square fa-4x"></i></a>
<a href="your link here"> <i class="fa fa-facebook-square fa-4x"></i></a>

Note: Replace href="your link here" with your desired link e.g. href="https://www.stackoverflow.com".

JavaScript get window X/Y position for scroll

The method jQuery (v1.10) uses to find this is:

var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

That is:

  • It tests for window.pageXOffset first and uses that if it exists.
  • Otherwise, it uses document.documentElement.scrollLeft.
  • It then subtracts document.documentElement.clientLeft if it exists.

The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.

Split string in JavaScript and detect line break

You should try detect the first line.

Then the:

if(n == 0){
  line = words[n]+"\n";
}

I'm not sure, but maybe it helps.

How to override the properties of a CSS class using another CSS class

There are different ways in which properties can be overridden. Assuming you have

.left { background: blue }

e.g. any of the following would override it:

a.background-none { background: none; }
body .background-none { background: none; }
.background-none { background: none !important; }

The first two “win” by selector specificity; the third one wins by !important, a blunt instrument.

You could also organize your style sheets so that e.g. the rule

.background-none { background: none; }

wins simply by order, i.e. by being after an otherwise equally “powerful” rule. But this imposes restrictions and requires you to be careful in any reorganization of style sheets.

These are all examples of the CSS Cascade, a crucial but widely misunderstood concept. It defines the exact rules for resolving conflicts between style sheet rules.

P.S. I used left and background-none as they were used in the question. They are examples of class names that should not be used, since they reflect specific rendering and not structural or semantic roles.

Export a graph to .eps file with R

Another way is to use Cairographics-based SVG, PDF and PostScript Graphics Devices. This way you don't need to setEPS()

cairo_ps("image.eps")
plot(1, 10)
dev.off()

What does the question mark operator mean in Ruby?

It is a code style convention; it indicates that a method returns a boolean value.

The question mark is a valid character at the end of a method name.

Symbol for any number of any characters in regex?

I would use .*. . matches any character, * signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with ..

Python pandas: fill a dataframe row by row

My approach was, but I can't guarantee that this is the fastest solution.

df = pd.DataFrame(columns=["firstname", "lastname"])
df = df.append({
     "firstname": "John",
     "lastname":  "Johny"
      }, ignore_index=True)

Regular Expression to match only alphabetic characters

This will match one or more alphabetical characters:

/^[a-z]+$/

You can make it case insensitive using:

/^[a-z]+$/i

or:

/^[a-zA-Z]+$/

Oracle ORA-12154: TNS: Could not resolve service name Error?

We resolved our issues by re-installing the Oracle Database Client. Somehow the installation wasn't successful on 1 of the workstations (even though there was no logging), however when comparing size/files/folders of the Oracle directory to a working client workstation, there was a significant amount of files that were missing. Once we performed a clean install, everything worked perfectly.

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

Click toggle with jQuery

Another approach would be to extended jquery like this:

$.fn.toggleCheckbox = function() {
    this.attr('checked', !this.attr('checked'));
}

Then call:

$('.offer').find(':checkbox').toggleCheckbox();

How to calculate age (in years) based on Date of Birth and getDate()

We used something like here, but then taking the average age:

ROUND(avg(CONVERT(int,DATEDIFF(hour,DOB,GETDATE())/8766.0)),0) AS AverageAge

Notice, the ROUND is outside rather than inside. This will allow for the AVG to be more accurate and we ROUND only once. Making it faster too.

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

In my case I had to enable virtualization in the BIOS setting.

  1. Restart PC
  2. While you are on the 'restart' screen press any of these keys and you enter the bios settings in windows: esc, f1, f2, f3, f4, f8 or delete
  3. For intel based systems:
    • press f7 (advanced mode)
    • go to advanced
    • cpa configuration
    • enable virtualization

And after all above steps, it finally works :-)

How to remove the querystring and get only the url?

You can try:

<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>

Bitwise operation and usage

Whilst manipulating bits of an integer is useful, often for network protocols, which may be specified down to the bit, one can require manipulation of longer byte sequences (which aren't easily converted into one integer). In this case it is useful to employ the bitstring library which allows for bitwise operations on data - e.g. one can import the string 'ABCDEFGHIJKLMNOPQ' as a string or as hex and bit shift it (or perform other bitwise operations):

>>> import bitstring
>>> bitstring.BitArray(bytes='ABCDEFGHIJKLMNOPQ') << 4
BitArray('0x142434445464748494a4b4c4d4e4f50510')
>>> bitstring.BitArray(hex='0x4142434445464748494a4b4c4d4e4f5051') << 4
BitArray('0x142434445464748494a4b4c4d4e4f50510')

git replace local version with remote version

This is the safest solution:

git stash

Now you can do whatever you want without fear of conflicts.

For instance:

git checkout origin/master

If you want to include the remote changes in the master branch you can do:

git reset --hard origin/master

This will make you branch "master" to point to "origin/master".

Foreach loop in java for a custom object list

for(Room room : rooms) {
  //room contains an element of rooms
}

jQuery: enabling/disabling datepicker

I have a single-page app in our company intranet where certain date fields need to be "blocked" under certain circumstances. Those date fields have a datepicker binding.

Making the fields read-only wasn't enough to block the fields, as datepicker still triggers when the field receives focus.

Disabling the field (or disabling datepicker) have side effects with serialize() or serializeArray().

One of the options was to unbind datepicker from those fields and making them "normal" fields. But one easiest solution is to make the field (or fields) read-only and to avoid datepicker from acting when receive focus.

$('#datefield').attr('readonly',true).datepicker("option", "showOn", "off");

How to create a new component in Angular 4 using CLI

ng g c --dry-run so you can see what you are about to do before you actually do it will save some frustration. Just shows you what it is going to do without actually doing it.

Create XML file using java

package com.server;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;


import org.w3c.dom.*;

import com.gwtext.client.data.XmlReader;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;  

public class XmlServlet extends HttpServlet
{ 

  NodeList list;
  Connection con=null;
  Statement st=null;
  ResultSet rs = null;
  String xmlString ;
  BufferedWriter bw;
  String displayTo;
  String displayFrom;
  String addressto;
  String addressFrom;
  Date send;
  String Subject;
  String body;
  String category;
  Document doc1;
  public void doGet(HttpServletRequest request,HttpServletResponse response)
   throws ServletException,IOException{

    System.out.print("on server");  

  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  System.out.print("on server");
  try
  {


    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
    //creating a new instance of a DOM to build a DOM tree.
    doc1 = docBuilder.newDocument();
    new XmlServlet().createXmlTree(doc1);

    System.out.print("on server");

  }
  catch(Exception e)
  {
  System.out.println(e.toString());
  }

   }

  public void createXmlTree(Document doc) throws Exception {
  //This method creates an element node

    System.out.println("ruchipaliwal111");

    try
    {

      System.out.println("ruchi111");
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://localhost:3308/plz","root","root1");
      st = con.createStatement();

      rs = st.executeQuery("select * from data");


      Element root = doc.createElement("message");
      doc.appendChild(root);

        while(rs.next())
        {



       displayTo=rs.getString(1).toString();
       System.out.println(displayTo+"getdataname");

       displayFrom=rs.getString(2).toString();
       System.out.println(displayFrom +"getdataname");

         addressto=rs.getString(3).toString();
         System.out.println(addressto +"getdataname");

       addressFrom=rs.getString(4).toString();
       System.out.println(addressFrom +"getdataname");

       send=rs.getDate(5);
       System.out.println(send +"getdataname");

       Subject=rs.getString(6).toString();
       System.out.println(Subject +"getdataname");

       body=rs.getString(7).toString();
       System.out.println(body+"getdataname");

      category=rs.getString(8).toString();
       System.out.println(category +"getdataname");


       //adding a node after the last child node of ssthe specified node.


        Element element1 = doc.createElement("Header");
        root.appendChild(element1);


        Element child1 = doc.createElement("To");
        element1.appendChild(child1);

        child1.setAttribute("displayNameTo",displayTo);
        child1.setAttribute("addressTo",addressto);

        Element child2 = doc.createElement("From");
        element1.appendChild(child2);

        child2.setAttribute("displayNameFrom",displayFrom);
        child2.setAttribute("addressFrom",addressFrom);

        Element child3 = doc.createElement("Send");
        element1.appendChild(child3);

        Text text2 = doc.createTextNode(send.toString());
        child3.appendChild(text2);

        Element child4 = doc.createElement("Subject");
        element1.appendChild(child4);

        Text text3 = doc.createTextNode(Subject);
        child4.appendChild(text3);

        Element child5 = doc.createElement("category");
        element1.appendChild(child5);

        Text text44 = doc.createTextNode(category);
        child5.appendChild(text44);


        Element element2 = doc.createElement("Body");
        root.appendChild(element2);

        Text text1 = doc.createTextNode(body);
        element2.appendChild(text1);

       /*
        Element child1 = doc.createElement("name");
        root.appendChild(child1);
        Text text = doc.createTextNode(getdataname);
        child1.appendChild(text);
        Element element = doc.createElement("address");
        root.appendChild(element);
        Text text1 = doc.createTextNode( getdataaddress);
        element.appendChild(text1); 
     */
      } 






//TransformerFactory instance is used to create Transformer objects. 
  TransformerFactory factory = TransformerFactory.newInstance();
  Transformer transformer = factory.newTransformer();

  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.setOutputProperty(OutputKeys.METHOD,"xml");
  // transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");


  // create string from xml tree
  StringWriter sw = new StringWriter();
  StreamResult result = new StreamResult(sw);
  DOMSource source = new DOMSource(doc);
  transformer.transform(source, result);

  xmlString = sw.toString();


  File file = new File("./war/ds/newxml.xml");
  bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
  bw.write(xmlString);
   }

    catch(Exception e)
    {
      System.out.print("after while loop exception"+e.toString());
    }

  bw.flush();
  bw.close();
  System.out.println("successfully done.....");
  }
}

How to get an enum value from a string value in Java?

Here's a method that can do it for any Enum, and is case insensitive.

/** 
 * Finds the value of the given enumeration by name, case-insensitive. 
 * Throws an IllegalArgumentException if no match is found.  
 **/
public static <T extends Enum<T>> T valueOfIgnoreCase(
        Class<T> enumeration, String name) {

    for (T enumValue : enumeration.getEnumConstants()) {
        if (enumValue.name().equalsIgnoreCase(name)) {
            return enumValue;
        }
    }

    throw new IllegalArgumentException(String.format(
        "There is no value with name '%s' in Enum %s",
        name, enumeration.getName()
    ));
}

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

How do I change the default schema in sql developer?

When a new user is created in ORACLE, an empty work area for tables and views is also automatically created. That work area is called a 'Schema'. Because of the tightly coupled relationship between users and schemas, the terms are often used synonymously. SQL Developer will, by default, show the empty schema that belongs to the user you connected with if it is indeed empty.

However, if you click to expand the part of the tree titled 'Other Users', you'll see other users/schemas that your user has access to. In there, you may find the tables and views you are seeking if you select the correct user/schema. An object only lives in the schema that owns it.

Still, it would be nice if the application allowed us to pick our desired schema closer to the root of the tree instead of forcing us to go searching for it. Other answers have offered workarounds such as:

  1. Logging in as the desired user/schema to begin with.
  2. Using a different Tool.
  3. Ignoring the tree and just executing: alter session set current_schema = otheruser;
  4. Creating a startup script to set the schema every time the application loads.

In the end, I searched and found another free tool that seems to solve this particular usability issue called DBeaver.

It's all a bit confusing because the word schema is overloaded. Schema could also be used to describe the database of your application. To get more clarity, read more about the term schema as it is used in the ORACLE context.

Parse date string and change format

>>> from_date="Mon Feb 15 2010"
>>> import time                
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'

How to get file path from OpenFileDialog and FolderBrowserDialog?

Create this class as Extension:

public static class Extensiones
{
    public static string FolderName(this OpenFileDialog ofd)
    {
            string resp = "";
            resp = ofd.FileName.Substring(0, 3);
            var final = ofd.FileName.Substring(3);
            var info = final.Split('\\');
            for (int i = 0; i < info.Length - 1; i++)
            {
                resp += info[i] + "\\";
            }
            return resp;
    }
}

Then, you could use in this way:

        //ofdSource is an OpenFileDialog 
        if (ofdSource.ShowDialog(this) == DialogResult.OK)
        {
            MessageBox.Show(ofdSource.FolderName());
        }

Replacing NULL and empty string within Select statement

An alternative way can be this: - recommended as using just one expression -

case when address.country <> '' then address.country
else 'United States'
end as country

Note: Result of checking null by <> operator will return false.
And as documented: NULLIF is equivalent to a searched CASE expression
and COALESCE expression is a syntactic shortcut for the CASE expression.
So, combination of those are using two time of case expression.

Using the Web.Config to set up my SQL database connection string?

http://www.connectionstrings.com is a site where you can find a lot of connection strings. All that you need to do is copy-paste and modify it to suit your needs. It is sure to have all the connection strings for all of your needs.

Remove all classes that begin with a certain string

With jQuery, the actual DOM element is at index zero, this should work

$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');

"Too many values to unpack" Exception

Most likely there is an error somewhere in the get_profile() call. In your view, before you return the request object, put this line:

request.user.get_profile()

It should raise the error, and give you a more detailed traceback, which you can then use to further debug.

Why is an OPTIONS request sent and can I disable it?

You can't but you could avoid CORS using JSONP.

How to check if an element is off-screen

There's a jQuery plugin here which allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.

$('#element').visible();

You can also check for partial visibility:

$('#element').visible( true);

One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.

Java Returning method which returns arraylist?

If Foo is the class enclose this method

class Foo{
  public ArrayList<Integer> myNumbers()    {
     //code code code
  }
}

then

new Foo().myNumbers();

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

For me the culprit is int value assigned to salary

Insert into Employees(ID,FirstName,LastName,Gender,Salary) values(3,'Canada', 'pa', 'm',15,000)

in salary column When we assign 15,000 the compiler understand 15 and 000.

This correction works fine for me. Insert into Employees(ID,FirstName,LastName,Gender,Salary) values(4,'US', 'sam', 'm',15000)

Calling a php function by onclick event

onclick event to call a function

  <strike> <input type="button" value="NEXT"  onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />    </strike>

it will surely help you

it take a little more time than normal but wait it will work

XDocument or XmlDocument

Also, note that XDocument is supported in Xbox 360 and Windows Phone OS 7.0. If you target them, develop for XDocument or migrate from XmlDocument.

When to catch java.lang.Error?

An Error usually shouldn't be caught, as it indicates an abnormal condition that should never occur.

From the Java API Specification for the Error class:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. [...]

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

As the specification mentions, an Error is only thrown in circumstances that are Chances are, when an Error occurs, there is very little the application can do, and in some circumstances, the Java Virtual Machine itself may be in an unstable state (such as VirtualMachineError)

Although an Error is a subclass of Throwable which means that it can be caught by a try-catch clause, but it probably isn't really needed, as the application will be in an abnormal state when an Error is thrown by the JVM.

There's also a short section on this topic in Section 11.5 The Exception Hierarchy of the Java Language Specification, 2nd Edition.

What is Join() in jQuery?

join is not a jQuery function .Its a javascript function.

The join() method joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).

http://www.w3schools.com/jsref/jsref_join.asp

How can I reverse a NSArray in Objective-C?

Try this:

for (int i = 0; i < [arr count]; i++)
{
    NSString *str1 = [arr objectAtIndex:[arr count]-1];
    [arr insertObject:str1 atIndex:i];
    [arr removeObjectAtIndex:[arr count]-1];
}

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

Capturing standard out and error with Start-Process

In the code given in the question, I think that reading the ExitCode property of the initiation variable should work.

$process = Start-Process -FilePath ping -ArgumentList localhost -NoNewWindow -PassThru -Wait
$process.ExitCode

Note that (as in your example) you need to add the -PassThru and -Wait parameters (this caught me out for a while).

Batch script: how to check for admin rights

Another way to do this.

REM    # # # #      CHECKING OR IS STARTED AS ADMINISTRATOR     # # # # #

FSUTIL | findstr /I "volume" > nul&if not errorlevel 1  goto Administrator_OK

cls
echo *******************************************************
echo ***    R U N    A S    A D M I N I S T R A T O R    ***
echo *******************************************************
echo.
echo.
echo Call up just as the Administrator. Abbreviation can be done to the script and set:
echo.
echo      Shortcut ^> Advanced ^> Run as Administrator
echo.
echo.
echo Alternatively, a single run "Run as Administrator"
echo or in the Schedule tasks with highest privileges
pause > nul
goto:eof
:Administrator_OK

REM Some next lines code ...

Android device chooser - My device seems offline

I've seen this happen a few times on my HTC Desire. I've never figured out whether the problem is in adb or the device but I usually do the following:

  • Restart adb by issuing 'adb kill-server' followed by 'adb start-server' at a cmd prompt
  • Disable and re-enable USB debugging on the phone
  • Rebooting the phone if it still doesn't work.

99% of my issues have been resolved with these steps.

How to compare two List<String> to each other?

If you want to check that the elements inside the list are equal and in the same order, you can use SequenceEqual:

if (a1.SequenceEqual(a2))

See it working online: ideone

How to format string to money

decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450

Console output:

Graphical user interface Tutorial in C

You can also have a look at FLTK (C++ and not plain C though)

FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX®/Linux® (X11), Microsoft® Windows®, and MacOS® X. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via OpenGL® and its built-in GLUT emulation.

FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.

Here are some quickstart screencasts

[Happy New Year!]

Parse JSON with R

RJSONIO from Omegahat is another package which provides facilities for reading and writing data in JSON format.

rjson does not use S4/S3 methods and so is not readily extensible, but still useful. Unfortunately, it does not used vectorized operations and so is too slow for non-trivial data. Similarly, for reading JSON data into R, it is somewhat slow and so does not scale to large data, should this be an issue.

Update (new Package 2013-12-03):

jsonlite: This package is a fork of the RJSONIO package. It builds on the parser from RJSONIO but implements a different mapping between R objects and JSON strings. The C code in this package is mostly from the RJSONIO Package, the R code has been rewritten from scratch. In addition to drop-in replacements for fromJSON and toJSON, the package has functions to serialize objects. Furthermore, the package contains a lot of unit tests to make sure that all edge cases are encoded and decoded consistently for use with dynamic data in systems and applications.

PHP Adding 15 minutes to Time value

You can use below code also.It quite simple.

$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));

UIScrollView scroll to bottom programmatically

For Horizontal ScrollView

If you like me has a Horizontal ScrollView and want to scroll to end of it (in my case to most right of it), you need to change some parts of the accepted answer:

Objective-C

CGPoint rightOffset = CGPointMake(self.scrollView.contentSize.width - self.scrollView.bounds.size.width + self.scrollView.contentInset.right, 0 );
[self.scrollView setContentOffset:rightOffset animated:YES];

Swift

let rightOffset: CGPoint = CGPoint(x: self.scrollView.contentSize.width - self.scrollView.bounds.size.width + self.scrollView.contentInset.right, y: 0)
self.scrollView.setContentOffset(rightOffset, animated: true)

How to get the PYTHONPATH in shell?

The environment variable PYTHONPATH is actually only added to the list of locations Python searches for modules. You can print out the full list in the terminal like this:

python -c "import sys; print(sys.path)"

Or if want the output in the UNIX directory list style (separated by :) you can do this:

python -c "import sys; print(':'.join(x for x in sys.path if x))"

Which will output something like this:

/usr/local/lib/python2.7/dist-packages/feedparser-5.1.3-py2.7.egg:/usr/local/lib/
python2.7/dist-packages/stripogram-1.5-py2.7.egg:/home/qiime/lib:/home/debian:/us
r/lib/python2.7:/usr/lib/python2.7/plat-linux2:/usr/lib/python2.7/lib-tk:/usr/lib
/python2.7/lib-old:/usr/lib/python2.7/lib- dynload:/usr/local/lib/python2.7/dist-
packages:/usr/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages/PIL:/u
sr/lib/python2.7/dist-packages/gst-0.10:/usr/lib/python2.7/dist-packages/gtk-2.0:
/usr/lib/pymodules/python2.7

Show git diff on file in staging area

You can also use git diff HEAD file to show the diff for a specific file.

See the EXAMPLE section under git-diff(1)

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

TLS 1.0 and 1.1 are now End of Life. A package on our Amazon web server updated, and we started getting this error.

The answer is above, but you shouldn't use tls or tls11 anymore.

Specifically for ASP.Net, add this to one of your startup methods.

        public Startup()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;

but I'm sure that something like this will work in many other cases.

Unit testing void methods?

Test its side-effects. This includes:

  • Does it throw any exceptions? (If it should, check that it does. If it shouldn't, try some corner cases which might if you're not careful - null arguments being the most obvious thing.)
  • Does it play nicely with its parameters? (If they're mutable, does it mutate them when it shouldn't and vice versa?)
  • Does it have the right effect on the state of the object/type you're calling it on?

Of course, there's a limit to how much you can test. You generally can't test with every possible input, for example. Test pragmatically - enough to give you confidence that your code is designed appropriately and implemented correctly, and enough to act as supplemental documentation for what a caller might expect.

How can I create and style a div using JavaScript?

create div with id name

var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}

add text to div

var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}

test code

divCreator("div1");
textAdder("div1", "this is paragraph 1");

output

this is paragraph 1

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

How to cache data in a MVC application

I will say implementing Singleton on this persisting data issue can be a solution for this matter in case you find previous solutions much complicated

 public class GPDataDictionary
{
    private Dictionary<string, object> configDictionary = new Dictionary<string, object>();

    /// <summary>
    /// Configuration values dictionary
    /// </summary>
    public Dictionary<string, object> ConfigDictionary
    {
        get { return configDictionary; }
    }

    private static GPDataDictionary instance;
    public static GPDataDictionary Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new GPDataDictionary();
            }
            return instance;
        }
    }

    // private constructor
    private GPDataDictionary() { }

}  // singleton

JavaScript: changing the value of onclick with or without jQuery

Note that following gnarf's idea you can also do:

var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;

That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).

How to check for changes on remote (origin) Git repository

git remote update && git status 

Found this on the answer to Check if pull needed in Git

git remote update to bring your remote refs up to date. Then you can do one of several things, such as:

  1. git status -uno will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.

  2. git show-branch *master will show you the commits in all of the branches whose names end in master (eg master and origin/master).

If you use -v with git remote update you can see which branches got updated, so you don't really need any further commands.

Permanently hide Navigation Bar in an activity

From Google documentation:

You can hide the navigation bar on Android 4.0 and higher using the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag. This snippet hides both the navigation bar and the status bar:

View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
              | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

http://developer.android.com/training/system-ui/navigation.html

Loop structure inside gnuplot?

I wanted to use wildcards to plot multiple files often placed in different directories, while working from any directory. The solution i found was to create the following function in ~/.bashrc

plo () {
local arg="w l"
local str="set term wxt size 900,500 title 'wild plotting'
set format y '%g'
set logs
plot"
while [ $# -gt 0 ]
        do str="$str '$1' $arg,"
        shift
done
echo "$str" | gnuplot -persist
}

and use it e.g. like plo *.dat ../../dir2/*.out, to plot all .dat files in the current directory and all .out files in a directory that happens to be a level up and is called dir2.

Is it possible to play music during calls so that the partner can hear it ? Android

No, It is not possible. But if you want to dig it more, then you can visit Using Android phone as GSM Gateway for VoIP where author has concluded that

It's not possible to use Android as a GSM Gateway in its current form. Even after flashing custom ROM because they also depends on proprietary RIL (Radio Interface Layer) firmwares. Hurdles 1 and 2 (API limitation) can be removed because the source code is available for the open source community to make it possible. However, the hurdle 3 (proprietary RIL) is dependent on the hardware vendors. Hardware vendors do not usually make their device drivers code available.

How to pad a string to a fixed length with spaces in Python?

I know this is a bit of an old question, but I've ended up making my own little class for it.

Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
    if overwriteFlag:
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want to overwrite the previous line, or

consolePrinter.writeline("text here",False)

if you don't.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

Find unused npm packages in package.json

As other answer mentioned depcheck is good for check unused dependecies in your porject. Use npm outdated command to check the outdated library.

enter image description here

JavaScript is in array

a little bit code from my side (custom function for Array):

    Array.prototype.in_array = function (array) {
        var $i = 0;
        var type = typeof array;
        while (this[$i]) {
            if ((type == ('number') || type == ('string'))  && array == this[$i]) {
                return true;
            } else if (type == 'object' && array instanceof Array && array.in_array(this[$i])) {
                return true
            }
            $i++;
        }
        return false;
    };


    var array = [1, 2, 3, "a", "b", "c"];

    //if string in array
    if (array.in_array('b')) {
        console.log("in array");
    }

    //if number in array
    if (array.in_array(3)) {
        console.log("in array");
    }

    // if one from array in array
    if (array.in_array([1, 'b'])) {
        console.log("in array");
    }

Split string in Lua?

I used the above examples to craft my own function. But the missing piece for me was automatically escaping magic characters.

Here is my contribution:

function split(text, delim)
    -- returns an array of fields based on text and delimiter (one character only)
    local result = {}
    local magic = "().%+-*?[]^$"

    if delim == nil then
        delim = "%s"
    elseif string.find(delim, magic, 1, true) then
        -- escape magic
        delim = "%"..delim
    end

    local pattern = "[^"..delim.."]+"
    for w in string.gmatch(text, pattern) do
        table.insert(result, w)
    end
    return result
end

How do I set the background color of my main screen in Flutter?

Scaffold(
      backgroundColor: Constants.defaulBackground,
      body: new Container(
      child: Center(yourtext)

      )
)

How to convert string to string[]?

In case you are just a beginner and want to split a string into an array of letters but didn't know the right terminology for that is a char[];

String myString = "My String";
char[] characters = myString.ToCharArray();

If this is not what you were looking for, sorry for wasting your time :P

MVVM Passing EventArgs As Command Parameter

I know this is a fairly old question, but I ran into the same problem today and wasn't too interested in referencing all of MVVMLight just so I can use event triggers with event args. I have used MVVMLight in the past and it's a great framework, but I just don't want to use it for my projects any more.

What I did to resolve this problem was create an ULTRA minimal, EXTREMELY adaptable custom trigger action that would allow me to bind to the command and provide an event args converter to pass on the args to the command's CanExecute and Execute functions. You don't want to pass the event args verbatim, as that would result in view layer types being sent to the view model layer (which should never happen in MVVM).

Here is the EventCommandExecuter class I came up with:

public class EventCommandExecuter : TriggerAction<DependencyObject>
{
    #region Constructors

    public EventCommandExecuter()
        : this(CultureInfo.CurrentCulture)
    {
    }

    public EventCommandExecuter(CultureInfo culture)
    {
        Culture = culture;
    }

    #endregion

    #region Properties

    #region Command

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommandExecuter), new PropertyMetadata(null));

    #endregion

    #region EventArgsConverterParameter

    public object EventArgsConverterParameter
    {
        get { return (object)GetValue(EventArgsConverterParameterProperty); }
        set { SetValue(EventArgsConverterParameterProperty, value); }
    }

    public static readonly DependencyProperty EventArgsConverterParameterProperty =
        DependencyProperty.Register("EventArgsConverterParameter", typeof(object), typeof(EventCommandExecuter), new PropertyMetadata(null));

    #endregion

    public IValueConverter EventArgsConverter { get; set; }

    public CultureInfo Culture { get; set; }

    #endregion

    protected override void Invoke(object parameter)
    {
        var cmd = Command;

        if (cmd != null)
        {
            var param = parameter;

            if (EventArgsConverter != null)
            {
                param = EventArgsConverter.Convert(parameter, typeof(object), EventArgsConverterParameter, CultureInfo.InvariantCulture);
            }

            if (cmd.CanExecute(param))
            {
                cmd.Execute(param);
            }
        }
    }
}

This class has two dependency properties, one to allow binding to your view model's command, the other allows you to bind the source of the event if you need it during event args conversion. You can also provide culture settings if you need to (they default to the current UI culture).

This class allows you to adapt the event args so that they may be consumed by your view model's command logic. However, if you want to just pass the event args on verbatim, simply don't specify an event args converter.

The simplest usage of this trigger action in XAML is as follows:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="NameChanged">
        <cmd:EventCommandExecuter Command="{Binding Path=Update, Mode=OneTime}" EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

If you needed access to the source of the event, you would bind to the owner of the event

<i:Interaction.Triggers>
    <i:EventTrigger EventName="NameChanged">
        <cmd:EventCommandExecuter 
            Command="{Binding Path=Update, Mode=OneTime}" 
            EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"
            EventArgsConverterParameter="{Binding ElementName=SomeEventSource, Mode=OneTime}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

(this assumes that the XAML node you're attaching the triggers to has been assigned x:Name="SomeEventSource"

This XAML relies on importing some required namespaces

xmlns:cmd="clr-namespace:MyProject.WPF.Commands"
xmlns:c="clr-namespace:MyProject.WPF.Converters"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

and creating an IValueConverter (called NameChangedArgsToStringConverter in this case) to handle the actual conversion logic. For basic converters I usually create a default static readonly converter instance, which I can then reference directly in XAML as I have done above.

The benefit of this solution is that you really only need to add a single class to any project to use the interaction framework much the same way that you would use it with InvokeCommandAction. Adding a single class (of about 75 lines) should be much more preferable to an entire library to accomplish identical results.

NOTE

this is somewhat similar to the answer from @adabyron but it uses event triggers instead of behaviours. This solution also provides an event args conversion ability, not that @adabyron's solution could not do this as well. I really don't have any good reason why I prefer triggers to behaviours, just a personal choice. IMO either strategy is a reasonable choice.

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

I personally use Visual Leak Detector, though it can cause large delays when large blocks are leaked (it displays the contents of the entire leaked block).

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

Do I need to explicitly call the base virtual destructor?

No you don't need to call the base destructor, a base destructor is always called for you by the derived destructor. Please see my related answer here for order of destruction.

To understand why you want a virtual destructor in the base class, please see the code below:

class B
{
public:
    virtual ~B()
    {
        cout<<"B destructor"<<endl;
    }
};


class D : public B
{
public:
    virtual ~D()
    {
        cout<<"D destructor"<<endl;
    }
};

When you do:

B *pD = new D();
delete pD;

Then if you did not have a virtual destructor in B, only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().

regular expression for anything but an empty string

Assertions are not necessary for this. \S should work by itself as it matches any non-whitespace.

How do I find the location of Python module sources?

datetime is a builtin module, so there is no (Python) source file.

For modules coming from .py (or .pyc) files, you can use mymodule.__file__, e.g.

> import random
> random.__file__
'C:\\Python25\\lib\\random.pyc'

Escape Character in SQL Server

You can escape quotation like this:

select 'it''s escaped'

result will be

it's escaped

Iterating over every property of an object in javascript using Prototype?

You should iterate over the keys and get the values using square brackets.

See: How do I enumerate the properties of a javascript object?

EDIT: Obviously, this makes the question a duplicate.

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

how to get yesterday's date in C#

The code you posted is wrong.

You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".

Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.

string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");

Integrating MySQL with Python in Windows

On Python 3.4 I've installed mysqlclient from http://www.lfd.uci.edu/~gohlke/pythonlibs/ with pip install mysqlclient and it's working.

Getting around the Max String size in a vba function?

Are you sure? This forum thread suggests it might be your watch window. Try outputting the string to a MsgBox, which can display a maximum of 1024 characters:

MsgBox RunMacros

Django: save() vs update() to update the database?

Update only works on updating querysets. If you want to update multiple fields at the same time, say from a dict for a single object instance you can do something like:

obj.__dict__.update(your_dict)
obj.save()

Bear in mind that your dictionary will have to contain the correct mapping where the keys need to be your field names and the values the values you want to insert.

Memory address of variables in Java

That is the class name and System.identityHashCode() separated by the '@' character. What the identity hash code represents is implementation-specific. It often is the initial memory address of the object, but the object can be moved in memory by the VM over time. So (briefly) you can't rely on it being anything.

Getting the memory addresses of variables is meaningless within Java, since the JVM is at liberty to implement objects and move them as it seems fit (your objects may/will move around during garbage collection etc.)

Integer.toBinaryString() will give you an integer in binary form.

How to check if user input is not an int value

Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }

How to view user privileges using windows cmd?

Use whoami /priv command to list all the user privileges.

Visual Studio Post Build Event - Copy to Relative Directory Location

Would it not make sense to use msbuild directly? If you are doing this with every build, then you can add a msbuild task at the end? If you would just like to see if you can’t find another macro value that is not showed on the Visual Studio IDE, you could switch on the msbuild options to diagnostic and that will show you all of the variables that you could use, as well as their current value.

To switch this on in visual studio, go to Tools/Options then scroll down the tree view to the section called Projects and Solutions, expand that and click on Build and Run, at the right their is a drop down that specify the build output verbosity, setting that to diagnostic, will show you what other macro values you could use.

Because I don’t quite know to what level you would like to go, and how complex you want your build to be, this might give you some idea. I have recently been doing build scripts, that even execute SQL code as part of the build. If you would like some more help or even some sample build scripts, let me know, but if it is just a small process you want to run at the end of the build, the perhaps going the full msbuild script is a bit of over kill.

Hope it helps Rihan

Data at the root level is invalid

I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was

<?xmlversion="1.0"encoding="utf-8"?>

which was causing the error. When I removed that line, so that the stylesheet started with the line

<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:

    <xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="utf-8" />
    <xsl:template match="/">
    <xsl:text>From,To~</xsl:text>
    <xsl:text>
</xsl:text>
    <xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
      <xsl:value-of select="@DTS:From"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="@DTS:To"/>
       <xsl:text>~</xsl:text>
      <xsl:text>
</xsl:text>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.

Where are the recorded macros stored in Notepad++?

If you install Notepad++ on Linux system by wine (In my case desktop Ubuntu 14.04-LTS_X64) the file "shortcuts.xml" is under :

$/home/[USER-NAME]/.wine/drive_c/users/[USER-NAME]/My Documents/.wine/drive_c/Program Files (x86)/Notepad++/shortcuts.xml

Thanks to Harrison and all that have suggestions for that isssue.

Write a number with two decimal places SQL Server

If you only need two decimal places, simplest way is..

SELECT CAST(12 AS DECIMAL(16,2))

OR

SELECT CAST('12' AS DECIMAL(16,2))

Output

12.00

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Spring Data JPA Update @Query not updating?

The underlying problem here is the 1st level cache of JPA. From the JPA spec Version 2.2 section 3.1. emphasise is mine:

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance.

This is important because JPA tracks changes to that entity in order to flush them to the database. As a side effect it also means within a single persistence context an entity gets only loaded once. This why reloading the changed entity doesn't have any effect.

You have a couple of options how to handle this:

  1. Evict the entity from the EntityManager. This may be done by calling EntityManager.detach, annotating the updating method with @Modifying(clearAutomatically = true) which evicts all entities. Make sure changes to these entities get flushed first or you might end up loosing changes.

  2. Use EntityManager.refresh().

  3. Use a different persistence context to load the entity. The easiest way to do this is to do it in a separate transaction. With Spring this can be done by having separate methods annotated with @Transactional on beans called from a bean not annotated with @Transactional. Another way is to use a TransactionTemplate which works especially nicely in tests where it makes transaction boundaries very visible.

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

How to sort a list of strings numerically?

If you want to use strings of the numbers better take another list as shown in my code it will work fine.

list1=["1","10","3","22","23","4","2","200"]

k=[]    
for item in list1:    
    k.append(int(item))

k.sort()
print(k)
# [1, 2, 3, 4, 10, 22, 23, 200]

What does the following Oracle error mean: invalid column index

I had this problem using a prepared statement. I didn't add enough "?" for the "VALUES" My eclipse had crashed after I did add the proper amount, and lost those changes. But that didn't occur to me to be the error until I started combing through the SQL as p.campbell suggested.

Sublime Text 3 how to change the font size of the file sidebar?

You need to change it at "class": "sidebar_label" Example, in your .sublime-theme file:

// Sidebar entry
{
    "class": "sidebar_label",
    "color": [212, 212, 213],
    "shadow_offset": [0, 0],
    "font.size":13
}

Credit

Python memory leaks

Not sure about "Best Practices" for memory leaks in python, but python should clear it's own memory by it's garbage collector. So mainly I would start by checking for circular list of some short, since they won't be picked up by the garbage collector.

CSS text-transform capitalize on all caps

all wrong it does exist --> font-variant: small-caps;

text-transform:capitalize; just the first letter cap

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

On a Mac, I had to do the following:

sudo chown -R $USER /data/db
sudo chown -R $USER /tmp/

because there was also a file inside /tmp which Mongo also needed access

Java Swing revalidate() vs repaint()

Any time you do a remove() or a removeAll(), you should call

  validate();
  repaint();

after you have completed add()'ing the new components.

Calling validate() or revalidate() is mandatory when you do a remove() - see the relevant javadocs.

My own testing indicates that repaint() is also necessary. I'm not sure exactly why.

Node.js Mongoose.js string to ObjectId function

You can do it like this:

var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");

EDIT: New standard has fromHexString rather than fromString

Shell script to capture Process ID and kill it if exist

#!/bin/sh

#Find the Process ID for syncapp running instance

PID=`ps -ef | grep syncapp 'awk {print $2}'`

if [[ -z "$PID" ]] then
--->    Kill -9 PID
fi

Not sure if this helps, but 'kill' is not spelled correctly. It's capitalized.

Try 'kill' instead.

Failure during conversion to COFF: file invalid or corrupt

I am using Visual Studio 2010.

This happened to me when I installed .NET 4.5. Uninstall of .NET 4.5 and install of .NET 4.0 helped me and error messages disappeared.

Rename Pandas DataFrame Index

In Pandas version 0.13 and greater the index level names are immutable (type FrozenList) and can no longer be set directly. You must first use Index.rename() to apply the new index level names to the Index and then use DataFrame.reindex() to apply the new index to the DataFrame. Examples:

For Pandas version < 0.13

df.index.names = ['Date']

For Pandas version >= 0.13

df = df.reindex(df.index.rename(['Date']))

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

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

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

Looping each row in datagridview

You could loop through DataGridView using Rows property, like:

foreach (DataGridViewRow row in datagridviews.Rows)
{
   currQty += row.Cells["qty"].Value;
   //More code here
}

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

How to calculate a time difference in C++

just in case you are on Unix, you can use time to get the execution time:

$ g++ myprog.cpp -o myprog
$ time ./myprog

Accessing Redux state in an action creator?

When your scenario is simple you can use

import store from '../store';

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return {
    type: SOME_ACTION,
    items: store.getState().otherReducer.items,
  }
}

But sometimes your action creator need to trigger multi actions

for example async request so you need REQUEST_LOAD REQUEST_LOAD_SUCCESS REQUEST_LOAD_FAIL actions

export const [REQUEST_LOAD, REQUEST_LOAD_SUCCESS, REQUEST_LOAD_FAIL] = [`REQUEST_LOAD`
    `REQUEST_LOAD_SUCCESS`
    `REQUEST_LOAD_FAIL`
]
export function someAction() {
    return (dispatch, getState) => {
        const {
            items
        } = getState().otherReducer;
        dispatch({
            type: REQUEST_LOAD,
            loading: true
        });
        $.ajax('url', {
            success: (data) => {
                dispatch({
                    type: REQUEST_LOAD_SUCCESS,
                    loading: false,
                    data: data
                });
            },
            error: (error) => {
                dispatch({
                    type: REQUEST_LOAD_FAIL,
                    loading: false,
                    error: error
                });
            }
        })
    }
}

Note: you need redux-thunk to return function in action creator

How do I find the current directory of a batch file, and then use it for the path?

There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:

.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt

And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:

@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit

Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:

@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit

How do I redirect to the previous action in ASP.NET MVC?

In Mvc using plain html in View Page with java script onclick

<input type="button" value="GO BACK" class="btn btn-primary" 
onclick="location.href='@Request.UrlReferrer'" />

This works great. hope helps someone.

@JuanPieterse has already answered using @Html.ActionLink so if possible someone can comment or answer using @Url.Action

Remove local git tags that are no longer on the remote repository

From Git v1.7.8 to v1.8.5.6, you can use this:

git fetch <remote> --prune --tags

Update

This doesn't work on newer versions of git (starting with v1.9.0) because of commit e66ef7ae6f31f2. I don't really want to delete it though since it did work for some people.

As suggested by "Chad Juliano", with all Git version since v1.7.8, you can use the following command:

git fetch --prune <remote> +refs/tags/*:refs/tags/*

You may need to enclose the tags part with quotes (on Windows for example) to avoid wildcard expansion:

git fetch --prune <remote> "+refs/tags/*:refs/tags/*"

How do I export (and then import) a Subversion repository?

If you do not have file access to the repository, I prefer rsvndump (remote Subversion repository dump) to make the dump file.

Styling input buttons for iPad and iPhone

Please add this css code

input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}

How to print float to n decimal places including trailing 0s?

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

>>> print('{0:.16f}'.format(1.6))
1.6000000000000001

>>> print('{0:.15f}'.format(1.6))
1.600000000000000

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

For Python versions prior to 2.6 (at least back to 2.0)

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

How to extend / inherit components?

Let us understand some key limitations & features on Angular’s component inheritance system.

The component only inherits the class logic:

  • All meta-data in the @Component decorator is not inherited.
  • Component @Input properties and @Output properties are inherited.
  • Component lifecycle is not inherited.

These features are very important to have in mind so let us examine each one independently.

The Component only inherits the class logic

When you inherit a Component, all logic inside is equally inherited. It is worth noting that only public members are inherited as private members are only accessible in the class that implements them.

All meta-data in the @Component decorator is not inherited

The fact that no meta-data is inherited might seem counter-intuitive at first but, if you think about this it actually makes perfect sense. If you inherit from a Component say (componentA), you would not want the selector of ComponentA, which you are inheriting from to replace the selector of ComponentB which is the class that is inheriting. The same can be said for the template/templateUrl as well as the style/styleUrls.

Component @Input and @Output properties are inherited

This is another feature that I really love about component Inheritance in Angular. In a simple sentence, whenever you have a custom @Input and @Output property, these properties get inherited.

Component lifecycle is not inherited

This part is the one that is not so obvious especially to people who have not extensively worked with OOP principles. For example, say you have ComponentA which implements one of Angular’s many lifecycle hooks like OnInit. If you create ComponentB and inherit ComponentA, the OnInit lifecycle from ComponentA won't fire until you explicitly call it even if you do have this OnInit lifecycle for ComponentB.

Calling Super/Base Component Methods

In order to have the ngOnInit() method from ComponentA fire, we need to use the super keyword and then call the method we need which in this case is ngOnInit. The super keyword refers to the instance of the component that is being inherited from which in this case will be ComponentA.

How to get `DOM Element` in Angular 2?

Angular 2.0.0 Final:

I have found that using a ViewChild setter is most reliable way to set the initial form control focus:

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => {
            this._renderer.invokeElementMethod(_input.nativeElement, "focus");
        }, 0);
    }
}

The setter is first called with an undefined value followed by a call with an initialized ElementRef.

Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview

Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).

UPDATE for Angular 4+

Renderer has been deprecated in favor of Renderer2, but Renderer2 does not have the invokeElementMethod. You will need to access the DOM directly to set the focus as in input.nativeElement.focus().

I'm still finding that the ViewChild setter approach works best. When using AfterViewInit I sometimes get read property 'nativeElement' of undefined error.

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => { //This setTimeout call may not be necessary anymore.
            _input.nativeElement.focus();
        }, 0);
    }
}

How to restart Postgresql

Try this as root (maybe you can use sudo or su):

/etc/init.d/postgresql restart

Without any argument the script also gives you a hint on how to restart a specific version

[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]

Similarly, in case you have it, you can also use the service tool:

[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]

Please, pay attention to the optional [version ...] trailing argument. That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.

Finally, in case you are running systemd, then you can use systemctl like this:

[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...

You can replace status with stop, start or restart as well as other actions. Please refer to the documentation for full details. In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12 and reload v13 you can run:

systemctl stop postgresql-12.service
systemctl reload postgresql-13.service

Thanks to @Jojo for pointing me to this very one. Finally Keep in mind that root permissions may be needed for non-informative tasks as in the other cases seen earlier.

Creating a "Hello World" WebSocket example

(Posted answer on behalf of the OP).

I am able to send data now. This is my new version of the program thanks to your answers and the code of @Maksims Mihejevs.

Server

using System;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static Socket serverSocket = new Socket(AddressFamily.InterNetwork, 
        SocketType.Stream, ProtocolType.IP);
        static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

        static void Main(string[] args)
        {            
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
            serverSocket.Listen(128);
            serverSocket.BeginAccept(null, 0, OnAccept, null);            
            Console.Read();
        }

        private static void OnAccept(IAsyncResult result)
        {
            byte[] buffer = new byte[1024];
            try
            {
                Socket client = null;
                string headerResponse = "";
                if (serverSocket != null && serverSocket.IsBound)
                {
                    client = serverSocket.EndAccept(result);
                    var i = client.Receive(buffer);
                    headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0,i);
                    // write received data to the console
                    Console.WriteLine(headerResponse);

                }
                if (client != null)
                {
                    /* Handshaking and managing ClientSocket */

                    var key = headerResponse.Replace("ey:", "`")
                              .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                              .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                              .Trim();

                    // key should now equal dGhlIHNhbXBsZSBub25jZQ==
                    var test1 = AcceptKey(ref key);

                    var newLine = "\r\n";

                    var response = "HTTP/1.1 101 Switching Protocols" + newLine
                         + "Upgrade: websocket" + newLine
                         + "Connection: Upgrade" + newLine
                         + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                         //+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
                         //+ "Sec-WebSocket-Version: 13" + newLine
                         ;

                    // which one should I use? none of them fires the onopen method
                    client.Send(System.Text.Encoding.UTF8.GetBytes(response));

                    var i = client.Receive(buffer); // wait for client to send a message

                    // once the message is received decode it in different formats
                    Console.WriteLine(Convert.ToBase64String(buffer).Substring(0, i));                    

                    Console.WriteLine("\n\nPress enter to send data to client");
                    Console.Read();

                    var subA = SubArray<byte>(buffer, 0, i);
                    client.Send(subA);
                    Thread.Sleep(10000);//wait for message to be send


                }
            }
            catch (SocketException exception)
            {
                throw exception;
            }
            finally
            {
                if (serverSocket != null && serverSocket.IsBound)
                {
                    serverSocket.BeginAccept(null, 0, OnAccept, null);
                }
            }
        }

        public static T[] SubArray<T>(T[] data, int index, int length)
        {
            T[] result = new T[length];
            Array.Copy(data, index, result, 0, length);
            return result;
        }

        private static string AcceptKey(ref string key)
        {
            string longKey = key + guid;
            byte[] hashBytes = ComputeHash(longKey);
            return Convert.ToBase64String(hashBytes);
        }

        static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        private static byte[] ComputeHash(string str)
        {
            return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
        }
    }
}

JavaScript:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript">
        function connect() {
            var ws = new WebSocket("ws://localhost:8080/service");
            ws.onopen = function () {
                alert("About to send data");
                ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
                alert("Message sent!");
            };

            ws.onmessage = function (evt) {
                alert("About to receive data");
                var received_msg = evt.data;
                alert("Message received = "+received_msg);
            };
            ws.onclose = function () {
                // websocket is closed.
                alert("Connection is closed...");
            };
        };


    </script>
</head>
<body style="font-size:xx-large" >
    <div>
    <a href="#" onclick="connect()">Click here to start</a></div>
</body>
</html>

When I run that code I am able to send and receive data from both the client and the server. The only problem is that the messages are encrypted when they arrive to the server. Here are the steps of how the program runs:

enter image description here

Note how the message from the client is encrypted.

MySQL error code: 1175 during UPDATE in MySQL Workbench

It looks like your MySql session has the safe-updates option set. This means that you can't update or delete records without specifying a key (ex. primary key) in the where clause.

Try:

SET SQL_SAFE_UPDATES = 0;

Or you can modify your query to follow the rule (use primary key in where clause).

Text editor to open big (giant, huge, large) text files

Free read-only viewers:

  • Large Text File Viewer (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.
  • klogg (Windows, macOS, Linux) – A maintained fork of glogg, its main feature is regular expression search. It can also watch files, allows the user to mark lines, and has serious optimizations built in. But from a UI standpoint, it's ugly and clunky.
  • LogExpert (Windows) – "A GUI replacement for tail." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.
  • Lister (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.
  • loxx (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.

Free editors:

  • Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, Vim (Windows, macOS, Linux), Emacs (Windows, macOS, Linux), Notepad++ (Windows), Sublime Text (Windows, macOS, Linux), and VS Code (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.
  • Large File Editor (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.
  • GigaEdit (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.

Builtin programs (no installation required):

  • less (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.
  • Notepad (Windows) – Decent with large files, especially with word wrap turned off.
  • MORE (Windows) – This refers to the Windows MORE, not the Unix more. A console program that allows you to view a file, one screen at a time.

Web viewers:

Paid editors:

  • 010 Editor (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.
  • SlickEdit (Windows, macOS, Linux) – Opens large files.
  • UltraEdit (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...
  • EmEditor (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).
  • BssEditor (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.

HTML - Display image after selecting filename

This can be done using HTML5, but will only work in browsers that support it. Here's an example.

Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.

Can I use multiple versions of jQuery on the same page?

Taken from http://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page:

  • Original page loads his "jquery.versionX.js" -- $ and jQuery belong to versionX.
  • You call your "jquery.versionY.js" -- now $ and jQuery belong to versionY, plus _$ and _jQuery belong to versionX.
  • my_jQuery = jQuery.noConflict(true); -- now $ and jQuery belong to versionX, _$ and _jQuery are probably null, and my_jQuery is versionY.

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

Spring Boot Adding Http Request Interceptors

Below is an implementation I use to intercept each HTTP request before it goes out and the response which comes back. With this implementation, I also have a single point where I can pass any header value with the request.

public class HttpInterceptor implements ClientHttpRequestInterceptor {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public ClientHttpResponse intercept(
        HttpRequest request, byte[] body,
        ClientHttpRequestExecution execution
) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    traceRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    traceResponse(response);
    return response;
}

private void traceRequest(HttpRequest request, byte[] body) throws IOException {
    logger.info("===========================Request begin======================================");
    logger.info("URI         : {}", request.getURI());
    logger.info("Method      : {}", request.getMethod());
    logger.info("Headers     : {}", request.getHeaders() );
    logger.info("Request body: {}", new String(body, StandardCharsets.UTF_8));
    logger.info("==========================Request end=========================================");
}

private void traceResponse(ClientHttpResponse response) throws IOException {
    logger.info("============================Response begin====================================");
    logger.info("Status code  : {}", response.getStatusCode());
    logger.info("Status text  : {}", response.getStatusText());
    logger.info("Headers      : {}", response.getHeaders());
    logger.info("=======================Response end===========================================");
}}

Below is the Rest Template Bean

@Bean
public RestTemplate restTemplate(HttpClient httpClient)
{
    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate=  new RestTemplate(requestFactory);
    List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
    if (CollectionUtils.isEmpty(interceptors))
    {
        interceptors = new ArrayList<>();
    }
    interceptors.add(new HttpInterceptor());
    restTemplate.setInterceptors(interceptors);

    return restTemplate;
}

Place input box at the center of div

Here's a rather unconventional way of doing it:

#inputcontainer
{
    display:table-cell; //display like a <td> to make the vertical-align work
    text-align:center; //centre the input horizontally
    vertical-align:middle; //centre the input vertically


    width:200px; //widen the div for demo purposes
    height:200px; //make the div taller for demo purposes
    background:green; //change the background of the div for demo purposes
}

It might not be the best way to do it, and margin? won't work, but it does the job. If you need to use margin, then you could wrap the div that displays as a table cell in another 'normal' div.

JSFiddle: http://jsfiddle.net/qw4QW/