Programs & Examples On #Delimited text

Save current directory in variable using Bash?

This saves the absolute path of the current working directory to the variable cwd:

cwd=$(pwd)

In your case you can just do:

export PATH=$PATH:$(pwd)+somethingelse

Do you use NULL or 0 (zero) for pointers in C++?

Well I argue for not using 0 or NULL pointers at all whenever possible.

Using them will sooner or later lead to segmentation faults in your code. In my experience this, and pointers in gereral is one of the biggest source of bugs in C++

also, it leads to "if-not-null" statements all over your code. Much nicer if you can rely on always a valid state.

There is almost always a better alternative.

Initialising mock objects - MockIto

A little example for JUnit 5 Jupiter, the "RunWith" was removed you now need to use the Extensions using the "@ExtendWith" Annotation.

@ExtendWith(MockitoExtension.class)
class FooTest {

  @InjectMocks
  ClassUnderTest test = new ClassUnderTest();

  @Spy
  SomeInject bla = new SomeInject();
}

What's the difference between '$(this)' and 'this'?

$() is the jQuery constructor function.

this is a reference to the DOM element of invocation.

So basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

XPath using starts-with function

Try this

//ITEM/*[starts-with(text(),'2552')]/following-sibling::*

How to get all keys with their values in redis

I have written a small code for this particular requirement using hiredis , please find the code with a working example at http://rachitjain1.blogspot.in/2013/10/how-to-get-all-keyvalue-in-redis-db.html

Here is the code that I have written,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hiredis.h"

int main(void)
{
        unsigned int i,j=0;char **str1;
        redisContext *c; char *t;
        redisReply *reply, *rep;

        struct timeval timeout = { 1, 500000 }; // 1.5 seconds
        c = redisConnectWithTimeout((char*)"127.0.0.2", 6903, timeout);
        if (c->err) {
                printf("Connection error: %s\n", c->errstr);
                exit(1);
        }

        reply = redisCommand(c,"keys *");
        printf("KEY\t\tVALUE\n");
        printf("------------------------\n");
        while ( reply->element[j]->str != NULL)
        {
                rep = redisCommand(c,"GET  %s", reply->element[j]->str);
                if (strstr(rep->str,"ERR Operation against a key holding"))
                {
                        printf("%s\t\t%s\n",  reply->element[j]->str,rep->str);
                        break;
                }
                printf("%s\t\t%s\n",  reply->element[j]->str,rep->str);
                j++;
                freeReplyObject(rep);
        }
}

Android: Internet connectivity change listener

I have noticed that no one mentioned WorkManger solution which is better and support most of android devices.

You should have a Worker with network constraint AND it will fired only if network available, i.e:

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints).build()

And in worker you do whatever you want once connection back, you may fire the worker periodically .

i.e:

inside dowork() callback:

notifierLiveData.postValue(info)

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

ENOENT means it's not there.

Just update your code to:

File.open(File.dirname(__FILE__) + '/text.txt').each {|line| puts line}

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

Faced the issue when reinstalled Windows on C: Drive, but my Visual Studio projects were intact on E: drive after the installation. I have resolved the issue by removing .vs folder in the visual studio project folder.

Change / Add syntax highlighting for a language in Sublime 2/3

I finally found a way to customize the given Themes.

Go to C:\Program Files\Sublime Text 3\Packages and copy + rename Color Scheme - Default.sublime-package to Color Scheme - Default.zip. Afterwards unzip it and copy the Theme, you want to change to %APPDATA%\Sublime Text 3\Packages\User. (In my case, All Hallow's Eve.tmTheme).

Then you can open it with any Text Editor and change / add something, for example for changing this in JavaScript:

<dict>
    <key>name</key>
    <string>Lang Variable</string>
    <key>scope</key>
    <string>variable.language</string>
    <key>settings</key>
    <dict>
        <key>foreground</key>
        <string>#FF0000</string>
    </dict>
</dict>

This will mark this in JavaScript Files red. You can select your Theme under Preferences -> Color Scheme -> User -> <Your Name>.

fork and exec in bash

Use the ampersand just like you would from the shell.

#!/usr/bin/bash
function_to_fork() {
   ...
}

function_to_fork &
# ... execution continues in parent process ...

C# try catch continue execution

Or you can encapsulate the looping logic itself in a try catch e.g.

for(int i = function2(); i < 100 /*where 100 is the end or another function call to get the end*/; i = function2()){

    try{
     //ToDo
    }
    catch { continue; }    

}

Or...

try{ 
    for(int i = function2(); ; ;) {
        try { i = function2(); return; } 
        finally { /*decide to break or not :P*/continue; } }
} catch { /*failed on first try*/ } finally{ /*afterwardz*/ }

How to read PDF files using Java?

with Apache PDFBox it goes like this:

PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(document);
    System.out.println("Text:" + text);
}
document.close();

Load dimension value from res/values/dimension.xml from source code

The Resource class also has a method getDimensionPixelSize() which I think will fit your needs.

*ngIf else if in template

Or maybe just use conditional chains with ternary operator. if … else if … else if … else chain.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator#Conditional_chains

<ng-container *ngIf="isFirst ? first: isSecond ? second : third"></ng-container>

<ng-template #first></ng-template>
<ng-template #second></ng-template>
<ng-template #third></ng-template>

I like this aproach better.

Print array elements on separate lines in Bash?

Using for:

for each in "${alpha[@]}"
do
  echo "$each"
done

Using history; note this will fail if your values contain !:

history -p "${alpha[@]}"

Using basename; note this will fail if your values contain /:

basename -a "${alpha[@]}"

Using shuf; note that results might not come out in order:

shuf -e "${alpha[@]}"

How can I make git accept a self signed certificate?

You can set GIT_SSL_NO_VERIFY to true:

GIT_SSL_NO_VERIFY=true git clone https://example.com/path/to/git

or alternatively configure Git not to verify the connection on the command line:

git -c http.sslVerify=false clone https://example.com/path/to/git

Note that if you don't verify SSL/TLS certificates, then you are susceptible to MitM attacks.

What is the difference between URI, URL and URN?

Uniform Resource Identifier (URI) is a string of characters used to identify a name or a resource on the Internet

A URI identifies a resource either by location, or a name, or both. A URI has two specializations known as URL and URN.

A Uniform Resource Locator (URL) is a subset of the Uniform Resource Identifier (URI) that specifies where an identified resource is available and the mechanism for retrieving it. A URL defines how the resource can be obtained. It does not have to be HTTP URL (http://), a URL can also be (ftp://) or (smb://).

A Uniform Resource Name (URN) is a Uniform Resource Identifier (URI) that uses the URN scheme, and does not imply availability of the identified resource. Both URNs (names) and URLs (locators) are URIs, and a particular URI may be both a name and a locator at the same time.

The URNs are part of a larger Internet information architecture which is composed of URNs, URCs and URLs.

bar.html is not a URN. A URN is similar to a person's name, while a URL is like a street address. The URN defines something's identity, while the URL provides a location. Essentially, "what" vs. "where". A URN has to be of this form <URN> ::= "urn:" <NID> ":" <NSS> where <NID> is the Namespace Identifier, and <NSS> is the Namespace Specific String.

To put it differently:

  • A URL is a URI that identifies a resource and also provides the means of locating the resource by describing the way to access it
  • A URL is a URI
  • A URI is not necessarily a URL

I'd say the only thing left to make it 100% clear would be to have an example of an URI that is not an URL. We can use the examples in the RFC3986:

URL: ftp://ftp.is.co.za/rfc/rfc1808.txt
URL: http://www.ietf.org/rfc/rfc2396.txt
URL: ldap://[2001:db8::7]/c=GB?objectClass?one
URL: mailto:[email protected]
URL: news:comp.infosystems.www.servers.unix
URL: telnet://192.0.2.16:80/
URN (not URL): urn:oasis:names:specification:docbook:dtd:xml:4.1.2
URN (not URL): tel:+1-816-555-1212 (?)

Also check this out - https://quintupledev.wordpress.com/2016/02/29/difference-between-uri-url-and-urn/

How do I get the latest version of my code?

By Running this command you'll get the most recent tag that usually is the version of your project:

git describe --abbrev=0 --tags

How can I close a dropdown on click outside?

The correct answer has a problem, if you have a clicakble component in your popover, the element will no longer on the contain method and will close, based on @JuHarm89 i created my own:

export class PopOverComponent implements AfterViewInit {
 private parentNode: any;

  constructor(
    private _element: ElementRef
  ) { }

  ngAfterViewInit(): void {
    this.parentNode = this._element.nativeElement.parentNode;
  }

  @HostListener('document:click', ['$event.path'])
  onClickOutside($event: Array<any>) {
    const elementRefInPath = $event.find(node => node === this.parentNode);
    if (!elementRefInPath) {
      this.closeEventEmmit.emit();
    }
  }
}

Thanks for the help!

Creating a list of dictionaries results in a list of copies of the same dictionary

You have misunderstood the Python list object. It is similar to a C pointer-array. It does not actually "copy" the object which you append to it. Instead, it just store a "pointer" to that object.

Try the following code:

>>> d={}
>>> dlist=[]
>>> for i in xrange(0,3):
    d['data']=i
    dlist.append(d)
    print(d)

{'data': 0}
{'data': 1}
{'data': 2}
>>> print(dlist)
[{'data': 2}, {'data': 2}, {'data': 2}]

So why is print(dlist) not the same as print(d)?

The following code shows you the reason:

>>> for i in dlist:
    print "the list item point to object:", id(i)

the list item point to object: 47472232
the list item point to object: 47472232
the list item point to object: 47472232

So you can see all the items in the dlist is actually pointing to the same dict object.

The real answer to this question will be to append the "copy" of the target item, by using d.copy().

>>> dlist=[]
>>> for i in xrange(0,3):
    d['data']=i
    dlist.append(d.copy())
    print(d)

{'data': 0}
{'data': 1}
{'data': 2}
>>> print dlist
[{'data': 0}, {'data': 1}, {'data': 2}]

Try the id() trick, you can see the list items actually point to completely different objects.

>>> for i in dlist:
    print "the list item points to object:", id(i)

the list item points to object: 33861576
the list item points to object: 47472520
the list item points to object: 47458120

Prevent form redirect OR refresh on submit?

Here:

function submitClick(e)
{
     e.preventDefault();
     $("#messageSent").slideDown("slow");
     setTimeout('$("#messageSent").slideUp();
     $("#contactForm").slideUp("slow")', 2000);
}

$(document).ready(function() {
    $('#contactSend').click(submitClick);
});

Instead of using the onClick event, you'll use bind an 'click' event handler using jQuery to the submit button (or whatever button), which will take submitClick as a callback. We pass the event to the callback to call preventDefault, which is what will prevent the click from submitting the form.

How to replace NA values in a table for selected columns

You can do:

x[, 1:2][is.na(x[, 1:2])] <- 0

or better (IMHO), use the variable names:

x[c("a", "b")][is.na(x[c("a", "b")])] <- 0

In both cases, 1:2 or c("a", "b") can be replaced by a pre-defined vector.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

In my case, I found that I set the post method as private mistakenly. after changing private to public.

[HttpPost]
private async Task<ActionResult> OnPostRemoveForecasting(){}

change to

[HttpPost]
public async Task<ActionResult> OnPostRemoveForecasting(){}

Now works fine.

How to tell if UIViewController's view is visible

I found those function in UIViewController.h.

/*
  These four methods can be used in a view controller's appearance callbacks to determine if it is being
  presented, dismissed, or added or removed as a child view controller. For example, a view controller can
  check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:
  method by checking the expression ([self isBeingDismissed] || [self isMovingFromParentViewController]).
*/

- (BOOL)isBeingPresented NS_AVAILABLE_IOS(5_0);
- (BOOL)isBeingDismissed NS_AVAILABLE_IOS(5_0);

- (BOOL)isMovingToParentViewController NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingFromParentViewController NS_AVAILABLE_IOS(5_0);

Maybe the above functions can detect the ViewController is appeared or not.

Android 5.0 - Add header/footer to a RecyclerView

I haven't tried this, but I would simply add 1 (or 2, if you want both a header and footer) to the integer returned by getItemCount in your adapter. You can then override getItemViewType in your adapter to return a different integer when i==0: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemViewType(int)

createViewHolder is then passed the integer you returned from getItemViewType, allowing you to create or configure the view holder differently for the header view: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#createViewHolder(android.view.ViewGroup, int)

Don't forget to subtract one from the position integer passed to bindViewHolder.

Check if a string isn't nil or empty in Lua

Can this code be simplified in one if test instead two?

nil and '' are different values. If you need to test that s is neither, IMO you should just compare against both, because it makes your intent the most clear.

That and a few alternatives, with their generated bytecode:

if not foo or foo == '' then end
     GETGLOBAL       0 -1    ; foo
     TEST            0 0 0
     JMP             3       ; to 7
     GETGLOBAL       0 -1    ; foo
     EQ              0 0 -2  ; - ""
     JMP             0       ; to 7

if foo == nil or foo == '' then end
    GETGLOBAL       0 -1    ; foo
    EQ              1 0 -2  ; - nil
    JMP             3       ; to 7
    GETGLOBAL       0 -1    ; foo
    EQ              0 0 -3  ; - ""
    JMP             0       ; to 7

if (foo or '') == '' then end
   GETGLOBAL       0 -1    ; foo
   TEST            0 0 1
   JMP             1       ; to 5
   LOADK           0 -2    ; ""
   EQ              0 0 -2  ; - ""
   JMP             0       ; to 7

The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

How to get absolute path to file in /resources folder of your project

Create the classLoader instance of the class you need, then you can access the files or resources easily. now you access path using getPath() method of that class.

 ClassLoader classLoader = getClass().getClassLoader();
 String path  = classLoader.getResource("chromedriver.exe").getPath();
 System.out.println(path);

Android WebView style background-color:transparent ignored on android 2.2

Following code work for me, though i have multiple webviews and scrolling between them is bit sluggish.

v.setBackgroundColor(Color.TRANSPARENT);
Paint p = new Paint();
v.setLayerType(LAYER_TYPE_SOFTWARE, p); 

Javascript callback when IFRAME is finished loading?

I wanted to hide the waiting spinner div when the i frame content is fully loaded on IE, i tried literally every solution mentioned in Stackoverflow.Com, but with nothing worked as i wanted.

Then i had an idea, that when the i frame content is fully loaded, the $(Window ) load event might be fired. And that exactly what happened. So, i wrote this small script, and worked like magic:

     $(window).load(function () {
     //alert("Done window ready ");
     var lblWait = document.getElementById("lblWait");
     if (lblWait != null ) {
         lblWait.style.visibility = "false";
         document.getElementById("divWait").style.display = "none";
     }
 });

Hope this helps.

ng is not recognized as an internal or external command

Adding C:\Users\DELL\AppData\Roaming\npm to System Variable Path worked for me. Please find your appropriate file path to 'npm'

Also, check if you have added your angular-cli\bin path to the path variable.

Creating a constant Dictionary in C#

Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.

There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:

switch (myString)
{
   case "cat": return 0;
   case "dog": return 1;
   case "elephant": return 3;
}

This is exactly what you want. And yes, I know, it's ugly.

Simulating Slow Internet Connection

Also, for simulating a slow connection on some *nixes, you can try using ipfw. More information is provided by Ben Newman's answer on this Quora question

Search All Fields In All Tables For A Specific Value (Oracle)

I did some modification to the above code to make it work faster if you are searching in only one owner. You just have to change the 3 variables v_owner, v_data_type and v_search_string to fit what you are searching for.

SET SERVEROUTPUT ON SIZE 100000

DECLARE
  match_count INTEGER;
-- Type the owner of the tables you are looking at
  v_owner VARCHAR2(255) :='ENTER_USERNAME_HERE';

-- Type the data type you are look at (in CAPITAL)
-- VARCHAR2, NUMBER, etc.
  v_data_type VARCHAR2(255) :='VARCHAR2';

-- Type the string you are looking at
  v_search_string VARCHAR2(4000) :='string to search here...';

BEGIN
  FOR t IN (SELECT table_name, column_name FROM all_tab_cols where owner=v_owner and data_type = v_data_type) LOOP

    EXECUTE IMMEDIATE 
    'SELECT COUNT(*) FROM '||t.table_name||' WHERE '||t.column_name||' = :1'
    INTO match_count
    USING v_search_string;

    IF match_count > 0 THEN
      dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );
    END IF;

  END LOOP;
END;
/

get current date with 'yyyy-MM-dd' format in Angular 4

In Controller ,

 var DateObj = new Date();

 $scope.YourParam = DateObj.getFullYear() + '-' + ('0' + (DateObj.getMonth() + 1)).slice(-2) + '-' + ('0' + DateObj.getDate()).slice(-2);

python list by value not by reference

To create a copy of a list do this:

b = a[:]

Convert JSON array to an HTML table in jQuery

I found a duplicate over here: Convert json data to a html table

Well, there are many plugins exists, including commercial one (Make this as commercial project?! Kinda overdone... but you can checkout over here: https://github.com/alfajango/jquery-dynatable)

This one has more fork: https://github.com/afshinm/Json-to-HTML-Table

//Example data, Object 
var objectArray = [{
    "Total": "34",
    "Version": "1.0.4",
    "Office": "New York"
}, {
    "Total": "67",
    "Version": "1.1.0",
    "Office": "Paris"
}];

//Example data, Array
var stringArray = ["New York", "Berlin", "Paris", "Marrakech", "Moscow"];

//Example data, nested Object. This data will create nested table also.
var nestedTable = [{
    key1: "val1",
    key2: "val2",
    key3: {
        tableId: "tblIdNested1",
        tableClassName: "clsNested",
        linkText: "Download",
        data: [{
            subkey1: "subval1",
            subkey2: "subval2",
            subkey3: "subval3"
        }]
    }
}];

Apply the code

//Only first parameter is required
var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download');

Or you might want to checkout this jQuery plugins as well: https://github.com/jongha/jquery-jsontotable

I think jongha's plugins is easier to use

<div id="jsontotable" class="jsontotable"></div>

var data = [[1, 2, 3], [1, 2, 3]];
$.jsontotable(data, { id: '#jsontotable', header: false });

DD/MM/YYYY Date format in Moment.js

This worked for me

var dateToFormat = "2018-05-16 12:57:13"; //TIMESTAMP

moment(dateToFormat).format("DD/MM/YYYY"); // you get "16/05/2018"

initializing a boolean array in java

I just need to initialize all the array elements to Boolean false.

Either use boolean[] instead so that all values defaults to false:

boolean[] array = new boolean[size];

Or use Arrays#fill() to fill the entire array with Boolean.FALSE:

Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.FALSE);

Also note that the array index is zero based. The freq[Global.iParameter[2]] = false; line as you've there would cause ArrayIndexOutOfBoundsException. To learn more about arrays in Java, consult this basic Oracle tutorial.

How to replace a character from a String in SQL?

Are you sure that the data stored in the database is actually a question mark? I would tend to suspect from the sample data that the problem is one of character set conversion where ? is being used as the replacement character when the character can't be represented in the client character set. Possibly, the database is actually storing Microsoft "smart quote" characters rather than simple apostrophes.

What does the DUMP function show is actually stored in the database?

SELECT column_name,
       dump(column_name,1016)
  FROM your_table
 WHERE <<predicate that returns just the sample data you posted>>

What application are you using to view the data? What is the client's NLS_LANG set to?

What is the database and national character set? Is the data stored in a VARCHAR2 column? Or NVARCHAR2?

SELECT parameter, value
  FROM v$nls_parameters
 WHERE parameter LIKE '%CHARACTERSET';

If all the problem characters are stored in the database as 0x19 (decimal 25), your REPLACE would need to be something like

UPDATE table_name
   SET column1 = REPLACE(column1, chr(25), q'[']'),
       column2 = REPLACE(column2, chr(25), q'[']'),
       ...
       columnN = REPLACE(columnN, chr(25), q'[']')
 WHERE INSTR(column1,chr(25)) > 0
    OR INSTR(column2,chr(25)) > 0 
    ...
    OR INSTR(columnN,chr(25)) > 0

'Source code does not match the bytecode' when debugging on a device

Probably this error message can have more than one cause, my case was not like the one from the OP, in my case this was due to a 3rd party library that required additional libraries.

For example: you manually add X.jar to your LIB, but this X.jar requires Z.jar to work.

It took me sometime to figure out, the message was not helping at all. I had to debug the app until I reached the crashing class, and in that class make sure that all imports were satisfied.

(Particualry: I added MercadoLibre-0.3.4.jar, which required commons-httpclient.jar)

Hope this helps!

Remove characters from C# string

Old School in place copy/stomp:

  private static string RemoveDirtyCharsFromString(string in_string)
     {
        int index = 0;
        int removed = 0;

        byte[] in_array = Encoding.UTF8.GetBytes(in_string);

        foreach (byte element in in_array)
        {
           if ((element == ' ') ||
               (element == '-') ||
               (element == ':'))
           {
              removed++;
           }
           else
           {
              in_array[index] = element;
              index++;
           }
        }

        Array.Resize<byte>(ref in_array, (in_array.Length - removed));
        return(System.Text.Encoding.UTF8.GetString(in_array, 0, in_array.Length));
     }

Not sure about the efficiency w.r.t. other methods (i.e. the overhead of all the function calls and instantiations that happen as a side effect in C# execution).

Replace transparency in PNG images with white background

It appears that your command is correct so the problem might be due to missing support for PNG (). You can check with convert -list configure or just try the following:

sudo yum install libpng libpng-devel

FPDF utf-8 encoding (HOW-TO)

None of the above solutions are going to work.

Try this:

function filter_html($value){
    $value = mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
    return $value;
}

Internet Explorer 11- issue with security certificate error prompt

If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.

For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11

To edit the Compatibility View list:

Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.

Angular 2 TypeScript how to find element in Array

Assume I have below array:

Skins[
    {Id: 1, Name: "oily skin"}, 
    {Id: 2, Name: "dry skin"}
];

If we want to get item with Id = 1 and Name = "oily skin", We'll try as below:

var skinName = skins.find(x=>x.Id == "1").Name;

The result will return the skinName is "Oily skin".

enter image description here

Mockito How to mock and assert a thrown exception?

Unrelated to mockito, one can catch the exception and assert its properties. To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.

Best way to check if column returns a null value (from database to .net application)

Use DBNull.Value.Equals on the object without converting it to a string.

Here's an example:

   if (! DBNull.Value.Equals(row[fieldName])) 
   {
      //not null
   }
   else
   {
      //null
   }

Can you recommend a free light-weight MySQL GUI for Linux?

Why not try MySQL GUI Tools? It's light, and does its job well.

What is the difference between an interface and abstract class?

Not really the answer to the original question, but once you have the answer to the difference between them, you will enter the when-to-use-each dilemma: When to use interfaces or abstract classes? When to use both?

I've limited knowledge of OOP, but seeing interfaces as an equivalent of an adjective in grammar has worked for me until now (correct me if this method is bogus!). For example, interface names are like attributes or capabilities you can give to a class, and a class can have many of them: ISerializable, ICountable, IList, ICacheable, IHappy, ...

stdcall and cdecl

It's specified in the function type. When you have a function pointer, it's assumed to be cdecl if not explicitly stdcall. This means that if you get a stdcall pointer and a cdecl pointer, you can't exchange them. The two function types can call each other without issues, it's just getting one type when you expect the other. As for speed, they both perform the same roles, just in a very slightly different place, it's really irrelevant.

Stop Visual Studio from launching a new browser window when starting debug?

Updated answer for a .NET Core Web Api project...

Right-click on your project, select "Properties," go to "Debug" and untick the "Launch browser" checkbox (enabled by default).

enter image description here

How can I convert a string to a float in mysql?

mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
|                   4.000 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
|                        4.500 |
+------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
|                         0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)

How do I install TensorFlow's tensorboard?

The pip package you are looking for is tensorflow-tensorboard developed by Google.

dplyr change many data types

From the bottom of the ?mutate_each (at least in dplyr 0.5) it looks like that function, as in @docendo discimus's answer, will be deprecated and replaced with more flexible alternatives mutate_if, mutate_all, and mutate_at. The one most similar to what @hadley mentions in his comment is probably using mutate_at. Note the order of the arguments is reversed, compared to mutate_each, and vars() uses select() like semantics, which I interpret to mean the ?select_helpers functions.

dat %>% mutate_at(vars(starts_with("fac")),funs(factor)) %>%   
  mutate_at(vars(starts_with("dbl")),funs(as.numeric))

But mutate_at can take column numbers instead of a vars() argument, and after reading through this page, and looking at the alternatives, I ended up using mutate_at but with grep to capture many different kinds of column names at once (unless you always have such obvious column names!)

dat %>% mutate_at(grep("^(fac|fctr|fckr)",colnames(.)),funs(factor)) %>%
  mutate_at(grep("^(dbl|num|qty)",colnames(.)),funs(as.numeric))

I was pretty excited about figuring out mutate_at + grep, because now one line can work on lots of columns.

EDIT - now I see matches() in among the select_helpers, which handles regex, so now I like this.

dat %>% mutate_at(vars(matches("fac|fctr|fckr")),funs(factor)) %>%
  mutate_at(vars(matches("dbl|num|qty")),funs(as.numeric))

Another generally-related comment - if you have all your date columns with matchable names, and consistent formats, this is powerful. In my case, this turns all my YYYYMMDD columns, which were read as numbers, into dates.

  mutate_at(vars(matches("_DT$")),funs(as.Date(as.character(.),format="%Y%m%d")))

ActionController::InvalidAuthenticityToken

I had this issue with javascript calls. I fixed that with just requiring jquery_ujs into application.js file.

Integer ASCII value to character in BASH using printf

If you convert 65 to hexadecimal it's 0x41:

$ echo -e "\x41" A

Convert 4 bytes to int

try something like this:

a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];

this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).

basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

Custom circle button

For a FAB looking button this style on a MaterialButton:

<com.google.android.material.button.MaterialButton
    style="@style/Widget.MaterialComponents.ExtendedFloatingActionButton"
    app:cornerRadius="28dp"
    android:layout_width="56dp"
    android:layout_height="56dp"
    android:text="1" />

Result:

enter image description here

If you change the size be careful to use half of the button size as app:cornerRadius.

File tree view in Notepad++

Tree like structure in Notepad++ without plugin

Download Notepad++ 6.8.8 & then follow step below :

Notepad++ -> View-> Project-> choose Panel 1 OR Panel 2 OR Panel 3 ->

It will create a sub part Wokspace on the left side -> Right click on Workspace & click Add Project -> Again right click on Project which is created recently -> And click on Add Files From Directory.

This is it. Enjoy

Reading and writing value from a textfile by using vbscript code

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("listfile.txt")
Dim inFile: Set inFile = obj.OpenTextFile("listfile.txt")

' read file
data = inFile.ReadAll
inFile.Close

' write file
outFile.write (data)
outFile.Close

Centering floating divs within another div

In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.

All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!

The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.

Ex.(each element has 2 sides so border, margin and padding get multiplied x2)

So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32

Then add all of your element's totaled widths together.

Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24

In this example the width for the "outer" div would be 112.

_x000D_
_x000D_
.outer {_x000D_
  /* floats + margins + borders = 270 */_x000D_
  max-width: 270px;_x000D_
  margin: auto;_x000D_
  height: 80px;_x000D_
  border: 1px;_x000D_
  border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
    /* 3 floats x 50px = 150px */_x000D_
    width: 50px;_x000D_
    /* 6 margins x 10px = 60 */_x000D_
    margin: 10px;_x000D_
    /* 6 borders x 10px = 60 */_x000D_
    border: 10px solid #6B6B6B;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="myFloat">Float 1</div>_x000D_
  <div class="myFloat">Float 2</div>_x000D_
  <div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Vim: How to insert in visual block mode?

  1. press ctrl and v // start select
  2. press shift and i // then type in any text
  3. press esc esc // press esc twice

Javascript code for showing yesterday's date and todays date

Yesterday Date can be calculated as:-

let now = new Date();
    var defaultDate = now - 1000 * 60 * 60 * 24 * 1;
    defaultDate = new Date(defaultDate);

get number of columns of a particular row in given excel using Java

Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.

private int getLastFilledCellPosition(Row row) {
        int columnIndex = -1;

        for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
            Cell cell = row.getCell(i);

            if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                continue;
            } else {
                columnIndex = cell.getColumnIndex();
                break;
            }
        }

        return columnIndex;
    }

ASP.NET GridView RowIndex As CommandArgument

I think this will work.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

tl;dr

Instant.now()
       .toString() 

2018-02-02T00:28:02.487114Z

Instant.parse(
    "2018-02-02T00:28:02.487114Z"
)

java.time

The accepted Answer by ppeterka is correct. Your abuse of the formatting pattern results in an erroneous display of data, while the internal value is always limited milliseconds.

The troublesome SimpleDateFormat and Date classes you are using are now legacy, supplanted by the java.time classes. The java.time classes handle nanoseconds resolution, much finer than the milliseconds limit of the legacy classes.

The equivalent to java.util.Date is java.time.Instant. You can even convert between them using new methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant() ;

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Capture the current moment in UTC. Java 8 captures the current moment in milliseconds, while a new Clock implementation in Java 9 captures the moment in finer granularity, typically microseconds though it depends on the capabilities of your computer hardware clock & OS & JVM implementation.

Instant instant = Instant.now() ;

Generate a String in standard ISO 8601 format.

String output = instant.toString() ;

2018-02-02T00:28:02.487114Z

To generate strings in other formats, search Stack Overflow for DateTimeFormatter, already covered many times.

To adjust into a time zone other than UTC, use ZonedDateTime.

ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Displaying one div on top of another

Here is the jsFiddle

#backdrop{
    border: 2px solid red;
    width: 400px;
    height: 200px;
    position: absolute;
}

#curtain {
    border: 1px solid blue;
    width: 400px;
    height: 200px;
    position: absolute;
}

Use Z-index to move the one you want on top.

getDate with Jquery Datepicker

You can format the jquery date with this line:

moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");

http://momentjs.com

C# RSA encryption/decryption with transmission

I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference. My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications. Here is main part used for signature verification:

        ...
        var signature = Get(url); // base64_encoded signature received from server
        var inputtext= "inputtext"; // this is main text signature was created for
        bool result = VerifySignature(inputtext, signature);
        ...

    private bool VerifySignature(string input, string signature)
    {
        var result = false;
        using (var cps=new RSACryptoServiceProvider())
        {
            // converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
            byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
            byte[] signatureBytes  = Convert.FromBase64String(signature);

            cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
            result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes  );
        }

        return result;
    }

How to determine if OpenSSL and mod_ssl are installed on Apache2

If you have PHP installed on your server, you can create a php file, let's called it phpinfo.php and add this <?php echo phpinfo();?>, and open the file in your browser, this shows information about your system environment, to quickly find info about your Apache loaded modules, locate 'Loaded Modules' on the resulting page.

External VS2013 build error "error MSB4019: The imported project <path> was not found"

You should copy folder WebApplications from C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\ to C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\

Why are primes important in cryptography?

I think what are important in cryptography are not primes itself, but it is the difficulty of prime factorization problem

Suppose you have very very large integer which is known to be product of two primes m and n, it is not easy to find what are m and n. Algorithm such as RSA depends on this fact.

By the way, there is a published paper on algorithm which can "solve" this prime factorization problem in acceptable time using quantum computer. So newer algorithms in cryptography may not rely on this "difficulty" of prime factorization anymore when quantum computer comes to town :)

How can I resize an image dynamically with CSS as the browser width/height changes?

Just use this code. What most are forgeting is to specify max-width as the max-width of the image

img {   
    height: auto;
    width: 100%;
    max-width: 300px;
}

Check this demonstration http://shorturl.at/nBKVY

How to remove "disabled" attribute using jQuery?

Thought this you can easily setup

$(function(){
$("input[name^=radio_share]").click
(
    function()
    {
        if($(this).attr("id")=="radio_share_dependent")
        {
            $(".share_dependent_block input, .share_dependent_block select").prop("disabled",false);   
        }
        else
        {
            $(".share_dependent_block input, .share_dependent_block select").prop("disabled",true);   
        }
    }
 );
});

How to automatically start a service when running a docker container?

In my case, I have a PHP web application being served by Apache2 within the docker container that connects to a MYSQL backend database. Larry Cai's solution worked with minor modifications. I created a entrypoint.sh file within which I am managing my services. I think creating an entrypoint.sh when you have more than one command to execute when your container starts up is a cleaner way to bootstrap docker.

#!/bin/sh

set -e

echo "Starting the mysql daemon"
service mysql start

echo "navigating to volume /var/www"
cd /var/www
echo "Creating soft link"
ln -s /opt/mysite mysite

a2enmod headers
service apache2 restart

a2ensite mysite.conf
a2dissite 000-default.conf
service apache2 reload

if [ -z "$1" ]
then
    exec "/usr/sbin/apache2 -D -foreground"
else
    exec "$1"
fi

What are allowed characters in cookies?

I think it's generally browser specific. To be on the safe side, base64 encode a JSON object, and store everything in that. That way you just have to decode it and parse the JSON. All the characters used in base64 should play fine with most, if not all browsers.

How to pass a value to razor variable from javascript variable?

But it would be possible if one were used in place of the variable in @html.Hidden field. As in this example.

@Html.Hidden("myVar", 0);

set the field per script:

<script>
function setMyValue(value) {
     $('#myVar').val(value);       
}
</script>

I hope I can at least offer no small Workaround.

Calling JavaScript Function From CodeBehind

IIRC Code Behind is compiled serverside and javascript is interpreted client side. This means there is no direct link between the two.

What you can do on the other hand is have the client and server communicate through a nifty tool called AJAX. http://en.wikipedia.org/wiki/Asynchronous_JavaScript_and_XML

CSS: How can I set image size relative to parent height?

Original Answer:

If you are ready to opt for CSS3, you can use css3 translate property. Resize based on whatever is bigger. If your height is bigger and width is smaller than container, width will be stretch to 100% and height will be trimmed from both side. Same goes for larger width as well.

Your need, HTML:

<div class="img-wrap">
  <img src="http://lorempixel.com/300/160/nature/" />
</div>
<div class="img-wrap">
  <img src="http://lorempixel.com/300/200/nature/" />
</div>
<div class="img-wrap">
  <img src="http://lorempixel.com/200/300/nature/" />
</div>

And CSS:

.img-wrap {
  width: 200px;
  height: 150px;
  position: relative;
  display: inline-block;
  overflow: hidden;
  margin: 0;
}

div > img {
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  min-height: 100%;
  min-width: 100%;
  transform: translate(-50%, -50%);
}

Voila! Working: http://jsfiddle.net/shekhardesigner/aYrhG/

Explanation

DIV is set to the relative position. This means all the child elements will get the starting coordinates (origins) from where this DIV starts.

The image is set as a BLOCK element, min-width/height both set to 100% means to resize the image no matter of its size to be the minimum of 100% of it's parent. min is the key. If by min-height, the image height exceeded the parent's height, no problem. It will look for if min-width and try to set the minimum height to be 100% of parents. Both goes vice-versa. This ensures there are no gaps around the div but image is always bit bigger and gets trimmed by overflow:hidden;

Now image, this is set to an absolute position with left:50% and top:50%. Means push the image 50% from the top and left making sure the origin is taken from DIV. Left/Top units are measured from the parent.

Magic moment:

transform: translate(-50%, -50%);

Now, this translate function of CSS3 transform property moves/repositions an element in question. This property deals with the applied element hence the values (x, y) OR (-50%, -50%) means to move the image negative left by 50% of image size and move to the negative top by 50% of image size.

Eg. if Image size was 200px × 150px, transform:translate(-50%, -50%) will calculated to translate(-100px, -75px). % unit helps when we have various size of image.

This is just a tricky way to figure out centroid of the image and the parent DIV and match them.

Apologies for taking too long to explain!

Resources to read more:

How to simulate a button click using code?

Android's callOnClick() (added in API 15) can sometimes be a better choice in my experience than performClick(). If a user has selection sounds enabled, then performClick() could cause the user to hear two continuous selection sounds that are somewhat layered on top of each other which can be jarring. (One selection sound for the user's first button click, and then another for the other button's OnClickListener that you're calling via code.)

Regular Expressions and negating a whole character group

Using a regex as you described is the simple way (as far as I am aware). If you want a range you could use [^a-f].

How to send file contents as body entity using cURL

I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:

curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX

How do I restrict an input to only accept numbers?

SOLUTION: I make a directive for all inputs, number, text, or any, in the app, so you can input a value and change the event. Make for angular 6

 import { Directive, ElementRef, HostListener, Input } from '@angular/core';

 @Directive({
// tslint:disable-next-line:directive-selector
selector: 'input[inputType]'
})
  export class InputTypeDirective {
 constructor(private _el: ElementRef) {}

 @Input() inputType: string;
 // tipos: number, letter, cuit, tel

@HostListener('input', ['$event']) onInputChange(event) {
if (!event.data) {
  return;
}

switch (this.inputType) {
  case 'number': {
    const initalValue = this._el.nativeElement.value;
    this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
    if (initalValue !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
     break;
          }
       case 'text': {
        const result = event.data.match(/[^a-zA-Z Ññ]*/g);
        if (result[0] !== '') {
           const initalValue = this._el.nativeElement.value;
           this._el.nativeElement.value = initalValue.replace(
          /[^a-zA-Z Ññ]*/g,
           ''
         );
           event.stopPropagation();
        }
        break;
    }
        case 'tel':
          case 'cuit': {
         const initalValue = this._el.nativeElement.value;
      this._el.nativeElement.value = initalValue.replace(/[^0-9-]*/g, '');
       if (initalValue !== this._el.nativeElement.value) {
         event.stopPropagation();
       }
     }
   }
  }
   }

HTML

     <input matInput inputType="number" [formControlName]="field.name" [maxlength]="field.length" [placeholder]="field.label | translate"  type="text" class="filter-input">

unable to set private key file: './cert.pem' type PEM

I had the same issue, eventually I found a solution that works without splitting the file, by following Petter Ivarrson's answer

My problem was when converting .p12 certificate to .pem. I used:

openssl pkcs12 -in cert.p12 -out cert.pem

This converts and exports all certificates (CA + CLIENT) together with a private key into one file.

The problem was when I tried to verify if the hashes of certificate and key are matching by running:

// Get certificate HASH
openssl x509 -noout -modulus -in cert.pem | openssl md5

// Get private key HASH
openssl rsa -noout -modulus -in cert.pem | openssl md5

This displayed different hashes and that was the reason CURL failed. See here: https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/

I guess that was because all certificates are inside a file (CA + CLIENT) and CURL takes CA certificate instead of CLIENT one. Because CA is first in the list.

So the solution was to export only CLIENT certificate together with private key:

openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
``

Now when I re-run the verification:
```sh
openssl x509 -noout -modulus -in cert.pem | openssl md5
openssl rsa -noout -modulus -in cert.pem | openssl md5

HASHES MATCHED !!!

So I was able to make a curl request by running

curl -ivk --cert ./cert.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

without problems!!!

That being said... I think the best solution is to split the certificates into separate file and use them separately like Petter Ivarsson wrote:

curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

I think this will work perfectly. I used the same:

For Android Studio:

  1. Click on Build > Generate Signed APK.
  2. You will get a message box, just click OK.
  3. Now there will be another window just copy Key Store Path.
  4. Now open a command prompt and go to C:\Program Files\Java\jdk1.6.0_39\bin> (or any installed jdk version).
  5. Type keytool -list -v -keystore and then paste your Key Store Path (Eg. C:\Program Files\Java\jdk1.6.0_39\bin>keytool -list -v -keystore "E:\My Projects \Android\android studio\signed apks\Hello World\HelloWorld.jks").
  6. Now it will Ask Key Store Password, provide yours and press Enter to get your SHA1 and MD5 Certificate keys.

How to make a redirection on page load in JSF 1.x

Edit 2

I finally found a solution by implementing my forward action like that:

private void applyForward() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    // Find where to redirect the user.
    String redirect = getTheFromOutCome();

    // Change the Navigation context.
    NavigationHandler myNav = facesContext.getApplication().getNavigationHandler();
    myNav.handleNavigation(facesContext, null, redirect);

    // Update the view root
    UIViewRoot vr = facesContext.getViewRoot();
    if (vr != null) {
        // Get the URL where to redirect the user
        String url = facesContext.getExternalContext().getRequestContextPath();
        url = url + "/" + vr.getViewId().replace(".xhtml", ".jsf");
        Object obj = facesContext.getExternalContext().getResponse();
        if (obj instanceof HttpServletResponse) {
            HttpServletResponse response = (HttpServletResponse) obj;
            try {
                // Redirect the user now.
                response.sendRedirect(response.encodeURL(url));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

It works (at least regarding my first tests), but I still don't like the way it is implemented... Any better idea?


Edit This solution does not work. Indeed, when the doForward() function is called, the JSF lifecycle has already been started, and then recreate a new request is not possible.


One idea to solve this issue, but I don't really like it, is to force the doForward() action during one of the setBindedInputHidden() method:

private boolean actionDefined = false;
private boolean actionParamDefined = false;

public void setHiddenActionParam(HtmlInputHidden hiddenActionParam) {
    this.hiddenActionParam = hiddenActionParam;
    String actionParam = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("actionParam");
    this.hiddenActionParam.setValue(actionParam);
    actionParamDefined = true;
    forwardAction();
}

public void setHiddenAction(HtmlInputHidden hiddenAction) {
    this.hiddenAction = hiddenAction;
    String action = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("action");
    this.hiddenAction.setValue(action);
    actionDefined = true;
    forwardAction();
}

private void forwardAction() {
    if (!actionDefined || !actionParamDefined) {
        // As one of the inputHidden was not binded yet, we do nothing...
        return;
    }
    // Now, both action and actionParam inputHidden are binded, we can execute the forward...
    doForward(null);
}

This solution does not involve any Javascript call, and works does not work.

Node/Express file upload

Another option is to use multer, which uses busboy under the hood, but is simpler to set up.

var multer = require('multer');

Use multer and set the destination for the upload:

app.use(multer({dest:'./uploads/'}));

Create a form in your view, enctype='multipart/form-data is required for multer to work:

form(role="form", action="/", method="post", enctype="multipart/form-data")
    div(class="form-group")
        label Upload File
        input(type="file", name="myfile", id="myfile")

Then in your POST you can access the data about the file:

app.post('/', function(req, res) {
  console.dir(req.files);
});

A full tutorial on this can be found here.

Turn off auto formatting in Visual Studio

I doubt that you can disable re-formatting after refactoring. Refactoring changes code and since it's only text I doubt what you'd want is that it just dumps unformatted text into your source. Wouldn't it be a little easier to just set the code style VS adheres to to the style you like and follow?

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

How to run Rake tasks from within Rake tasks?

If you want each task to run regardless of any failures, you can do something like:

task :build_all do
  [:debug, :release].each do |t| 
    ts = 0
    begin  
      Rake::Task["build"].invoke(t)
    rescue
      ts = 1
      next
    ensure
      Rake::Task["build"].reenable # If you need to reenable
    end
    return ts # Return exit code 1 if any failed, 0 if all success
  end
end

load json into variable

<input  class="pull-right" id="currSpecID" name="currSpecID" value="">

   $.get("http://localhost:8080/HIS_API/rest/MriSpecimen/getMaxSpecimenID", function(data, status){
       alert("Data: " + data + "\nStatus: " + status);
    $("#currSpecID").val(data);
    });

enter image description here enter image description here

get the value of DisplayName attribute

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(foo);

foreach (PropertyDescriptor property in properties)
{
    if (property.Name == "Name")
    {
        Console.WriteLine(property.DisplayName); // Something To Name
    }
}

where foo is an instance of Class1

Read and write a text file in typescript

First you will need to install node definitions for Typescript. You can find the definitions file here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

Once you've got file, just add the reference to your .ts file like this:

/// <reference path="path/to/node.d.ts" />

Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:

/// <reference path="path/to/node.d.ts" />

class MyClass {

    // Here we import the File System module of node
    private fs = require('fs');

    constructor() { }

    createFile() {

        this.fs.writeFile('file.txt', 'I am cool!',  function(err) {
            if (err) {
                return console.error(err);
            }
            console.log("File created!");
        });
    }

    showFile() {

        this.fs.readFile('file.txt', function (err, data) {
            if (err) {
                return console.error(err);
            }
            console.log("Asynchronous read: " + data.toString());
        });
    }
}

// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();

Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:

> node myClass.js

Is there any difference between "!=" and "<>" in Oracle Sql?

At university we were taught 'best practice' was to use != when working for employers, though all the operators above have the same functionality.

Ant if else condition?

<project name="Build" basedir="." default="clean">
    <property name="default.build.type" value ="Release"/>

    <target name="clean">
    <echo>Value Buld is now  ${PARAM_BUILD_TYPE} is set</echo>
        <condition property="build.type" value="${PARAM_BUILD_TYPE}" else="${default.build.type}">
            <isset property="PARAM_BUILD_TYPE"/>
        </condition>

       <echo>Value Buld is now  ${PARAM_BUILD_TYPE} is set</echo>
       <echo>Value Buld is now  ${build.type} is set</echo>
    </target>
</project>

In my Case DPARAM_BUILD_TYPE=Debug if it is supplied than, I need to build for for Debug otherwise i need to go for building Release build. I write like above condition it worked and i have tested as below it is working fine for me.

And property ${build.type} we can pass this to other target or macrodef for processing which i am doing in my other ant macrodef.

D:\>ant -DPARAM_BUILD_TYPE=Debug
Buildfile: D:\build.xml
clean:
     [echo] Value Buld is now  Debug is set
     [echo] Value Buld is now  Debug is set
     [echo] Value Buld is now  Debug is set
main:
BUILD SUCCESSFUL
Total time: 0 seconds
D:\>ant
Buildfile: D:\build.xml
clean:
     [echo] Value Buld is now  ${PARAM_BUILD_TYPE} is set
     [echo] Value Buld is now  ${PARAM_BUILD_TYPE} is set
     [echo] Value Buld is now  Release is set
main:
BUILD SUCCESSFUL
Total time: 0 seconds

It work for me to implement condition so posted hope it will helpful.

Getting the first character of a string with $str[0]

Speaking as a mere mortal, I would stick with $str[0]. As far as I'm concerned, it's quicker to grasp the meaning of $str[0] at a glance than substr($str, 0, 1). This probably boils down to a matter of preference.

As far as performance goes, well, profile profile profile. :) Or you could peer into the PHP source code...

How to re-create database for Entity Framework?

My solution is best suited for :
- deleted your mdf file
- want to re-create your db.

In order to recreate your database you need add the connection using Visual Studio.

Step 1 : Go to Server Explorer add new connection( or look for a add db icon).

Step 2 : Change Datasource to Microsoft SQL Server Database File.

Step 3 : add any database name you desire in the Database file name field.(preferably the same name you have in the web.config AttachDbFilename attribute)

Step 4 : click browse and navigate to where you will like it to be located.

Step 5 : in the package manager console run command update-database

Simple C example of doing an HTTP POST and consuming the response

Jerry's answer is great. However, it doesn't handle large responses. A simple change to handle this:

memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
    printf("RESPONSE: %s\n", response);
    // HANDLE RESPONSE CHUCK HERE BY, FOR EXAMPLE, SAVING TO A FILE.
    memset(response, 0, sizeof(response));
    bytes = recv(sockfd, response, 1024, 0);
    if (bytes < 0)
        printf("ERROR reading response from socket");
    if (bytes == 0)
        break;
    received+=bytes;
} while (1); 

How to add an image to the "drawable" folder in Android Studio?

Android Studio 3.0:

1) Right click directory 'drawable'.
2) Click on: Show in Explorer

Now you have an explorer opent with a few directories in it, one of then is 'drawable'.

3) Go in the directory 'drawable'.
4) Place the image you want in there.
5) Close the explorer again.

Now the image is in Android Studio under 'res/drawable'.

Alternative to iFrames with HTML5

Basically there are 4 ways to embed HTML into a web page:

  • <iframe> An iframe's content lives entirely in a separate context than your page. While that's mostly a great feature and it's the most compatible among browser versions, it creates additional challenges (shrink wrapping the size of the frame to its content is tough, insanely frustrating to script into/out of, nearly impossible to style).
  • AJAX. As the solutions shown here prove, you can use the XMLHttpRequest object to retrieve data and inject it to your page. It is not ideal because it depends on scripting techniques, thus making the execution slower and more complex, among other drawbacks.
  • Hacks. Few mentioned in this question and not very reliable.
  • HTML5 Web Components. HTML Imports, part of the Web Components, allows to bundle HTML documents in other HTML documents. That includes HTML, CSS, JavaScript or anything else an .html file can contain. This makes it a great solution with many interesting use cases: split an app into bundled components that you can distribute as building blocks, better manage dependencies to avoid redundancy, code organization, etc. Here is a trivial example:

    <!-- Resources on other origins must be CORS-enabled. -->
    <link rel="import" href="http://example.com/elements.html">
    

Native compatibility is still an issue, but you can use a polyfill to make it work in evergreen browsers Today.

You can learn more here and here.

Use CSS3 transitions with gradient backgrounds

I use this at work :) IE6+ https://gist.github.com/GrzegorzPerko/7183390

Don't forget about <element class="ahover"><span>Text</span></a> if you use a text element.

.ahover {
    display: block;
    /** text-indent: -999em; ** if u use only only img **/
    position: relative;
}
.ahover:after {
    content: "";
    height: 100%;
    left: 0;
    opacity: 0;
    position: absolute;
    top: 0;
    transition: all 0.5s ease 0s;
    width: 100%;
    z-index: 1;
}
.ahover:hover:after {
    opacity: 1;
}
.ahover span {
    display: block;
    position: relative;
    z-index: 2;
}

How do you refresh the MySQL configuration file without restarting?

You were so close! The kill -HUP method wasn't working for me either.

You were calling:

select @@global.max_connections;

All you needed was to set instead of select:

set @@global.max_connections = 400;

See:

http://www.netadmintools.com/art573.html

http://www.electrictoolbox.com/update-max-connections-mysql/

Warning as error - How to get rid of these

Each project in Visual Studio has a "treat warnings as errors" option. Go through each of your projects and change that setting:

  1. Right-click on your project, select "Properties".
  2. Click "Build".
  3. Switch "Treat warnings as errors" from "All" to "Specific warnings" or "None".

The location of this switch varies, depending on the type of project (class library vs. web application, for example).

How to parse XML using vba

You can use a XPath Query:

Dim objDom As Object        '// DOMDocument
Dim xmlStr As String, _
    xPath As String

xmlStr = _
    "<PointN xsi:type='typens:PointN' " & _
    "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " & _
    "xmlns:xs='http://www.w3.org/2001/XMLSchema'> " & _
    "    <X>24.365</X> " & _
    "    <Y>78.63</Y> " & _
    "</PointN>"

Set objDom = CreateObject("Msxml2.DOMDocument.3.0")     '// Using MSXML 3.0

'/* Load XML */
objDom.LoadXML xmlStr

'/*
' * XPath Query
' */        

'/* Get X */
xPath = "/PointN/X"
Debug.Print objDom.SelectSingleNode(xPath).text

'/* Get Y */
xPath = "/PointN/Y"
Debug.Print objDom.SelectSingleNode(xPath).text

How to store a list in a column of a database table

I was very reluctant to choose the path I finally decide to take because of many answers. While they add more understanding to what is SQL and its principles, I decided to become an outlaw. I was also hesitant to post my findings as for some it's more important to vent frustration to someone breaking the rules rather than understanding that there are very few universal truthes.

I have tested it extensively and, in my specific case, it was way more efficient than both using array type (generously offered by PostgreSQL) or querying another table.

Here is my answer: I have successfully implemented a list into a single field in PostgreSQL, by making use of the fixed length of each item of the list. Let say each item is a color as an ARGB hex value, it means 8 char. So you can create your array of max 10 items by multiplying by the length of each item:

ALTER product ADD color varchar(80)

In case your list items length differ you can always fill the padding with \0

NB: Obviously this is not necessarily the best approach for hex number since a list of integers would consume less storage but this is just for the purpose of illustrating this idea of array by making use of a fixed length allocated to each item.

The reason why: 1/ Very convenient: retrieve item i at substring i*n, (i +1)*n. 2/ No overhead of cross tables queries. 3/ More efficient and cost-saving on the server side. The list is like a mini blob that the client will have to split.

While I respect people following rules, many explanations are very theoretical and often fail to acknowledge that, in some specific cases, especially when aiming for cost optimal with low-latency solutions, some minor tweaks are more than welcome.

"God forbid that it is violating some holy sacred principle of SQL": Adopting a more open-minded and pragmatic approach before reciting the rules is always the way to go. Else you might end up like a candid fanatic reciting the Three Laws of Robotics before being obliterated by Skynet

I don't pretend that this solution is a breakthrough, nor that it is ideal in term of readability and database flexibility, but it can certainly give you an edge when it comes to latency.

Create a date time with month and day only, no year

How about creating a timer with the next date?

In your timer callback you create the timer for the following year? DateTime has always a year value. What you want to express is a recurring time specification. This is another type which you would need to create. DateTime is always represents a specific date and time but not a recurring date.

JAVA_HOME and PATH are set but java -version still shows the old one

check available Java versions on your Linux system by using update-alternatives command:

 $ sudo update-alternatives --display java

Now that there are suitable candidates to change to, you can switch the default Java version among available Java JREs by running the following command:

 $ sudo update-alternatives --config java

When prompted, select the Java version you would like to use.1 or 2 or 3 or etc..

Now you can verify the default Java version changed as follows.

 $ java -version

Owl Carousel Won't Autoplay

Your Javascript should be

<script>
$("#intro").owlCarousel({

// Most important owl features

//Autoplay
autoplay: false,
autoplayTimeout: 5000,
autoplayHoverPause: true
)}
</script>

Using CSS in Laravel views?

To my opinion the best option to route to css & js use the following code:

<link rel="stylesheet" type="text/css" href="{{ URL::to('route/to/css') }}">

So if you have css file called main.css inside of css folder in public folder it should be the following:

<link rel="stylesheet" type="text/css" href="{{ URL::to('css/main.css') }}">

Stored Procedure error ORA-06550

create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS)  from PLAYERREGULARSEASON  where TEAM    = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)

LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;

END;
/

keypress, ctrl+c (or some combo like that)

I am a little late to the party but here is my part

$(document).on('keydown', function ( e ) {
    // You may replace `c` with whatever key you want
    if ((e.metaKey || e.ctrlKey) && ( String.fromCharCode(e.which).toLowerCase() === 'c') ) {
        console.log( "You pressed CTRL + C" );
    }
});

ES6 export default with multiple functions referring to each other

The export default {...} construction is just a shortcut for something like this:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { foo(); bar() }
}

export default funcs

It must become obvious now that there are no foo, bar or baz functions in the module's scope. But there is an object named funcs (though in reality it has no name) that contains these functions as its properties and which will become the module's default export.

So, to fix your code, re-write it without using the shortcut and refer to foo and bar as properties of funcs:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { funcs.foo(); funcs.bar() } // here is the fix
}

export default funcs

Another option is to use this keyword to refer to funcs object without having to declare it explicitly, as @pawel has pointed out.

Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:

function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }

export default {foo, bar, baz}

And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:

// util.js

export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }

export default {foo, bar, baz}

// a.js, using default export

import util from './util'
util.foo()

// b.js, using named exports

import {bar} from './util'
bar()

Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util' to get all named exports in one object.

Using BETWEEN in CASE SQL statement

Take out the MONTHS from your case, and remove the brackets... like this:

CASE 
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

You can think of this as being equivalent to:

CASE TRUE
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

How do I set cell value to Date and apply default Excel date format?

This code sample can be used to change date format. Here I want to change from yyyy-MM-dd to dd-MM-yyyy. Here pos is position of column.

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class Test{ 
public static void main( String[] args )
{
String input="D:\\somefolder\\somefile.xlsx";
String output="D:\\somefolder\\someoutfile.xlsx"
FileInputStream file = new FileInputStream(new File(input));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=5; // 5th column is date.
while(iterator.hasNext())
{
    row=iterator.next();

    cell=row.getCell(pos-1);
    //CellStyle cellStyle = wb.createCellStyle();
    XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
    CreationHelper createHelper = wb.getCreationHelper();
    cellStyle.setDataFormat(
        createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date d=null;
    try {
        d= sdf.parse(cell.getStringCellValue());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        d=null;
        e.printStackTrace();
        continue;
    }
    cell.setCellValue(d);
    cell.setCellStyle(cellStyle);
   }

file.close();
FileOutputStream outFile =new FileOutputStream(new File(output));
workbook.write(outFile);
workbook.close();
outFile.close();
}}

Removing multiple keys from a dictionary safely

Some timing tests for cpython 3 shows that a simple for loop is the fastest way, and it's quite readable. Adding in a function doesn't cause much overhead either:

timeit results (10k iterations):

  • all(x.pop(v) for v in r) # 0.85
  • all(map(x.pop, r)) # 0.60
  • list(map(x.pop, r)) # 0.70
  • all(map(x.__delitem__, r)) # 0.44
  • del_all(x, r) # 0.40
  • <inline for loop>(x, r) # 0.35
def del_all(mapping, to_remove):
      """Remove list of elements from mapping."""
      for key in to_remove:
          del mapping[key]

For small iterations, doing that 'inline' was a bit faster, because of the overhead of the function call. But del_all is lint-safe, reusable, and faster than all the python comprehension and mapping constructs.

Any easy way to use icons from resources?

On Form_Load:

this.Icon = YourProjectNameSpace.Resources.YourResourceName.YouAppIconName;

Wait for shell command to complete

Use the WScript.Shell instead, because it has a waitOnReturn option:

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

(Idea copied from Wait for Shell to finish, then format cells - synchronously execute a command)

Android fastboot waiting for devices

Just use sudo, fast boot needs Root Permission

How to make a custom LinkedIn share button

LinkedIn has updated their api and the sharing url's no longer works. Now you can only use the url query parameter. Any other parameter is going to be removed from the url by LinkedIn.

Now you're forced to use oAuth and interact with the linkedin API to share content on behalf of a user.

open() in Python does not create a file if it doesn't exist

The advantage of the following approach is that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

with open("file.dat","a+") as f:
    f.write(...)
    ...

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. -Python file modes

seek() method sets the file's current position.

f.seek(pos [, (0|1|2)])
pos .. position of the r/w pointer
[] .. optionally
() .. one of ->
  0 .. absolute position
  1 .. relative position to current
  2 .. relative position from end

Only "rwab+" characters are allowed; there must be exactly one of "rwa" - see Stack Overflow question Python file modes detail.

How to git-cherry-pick only changes to certain files?

Cherry pick is to pick changes from a specific "commit". The simplest solution is to pick all changes of certain files is to use

 git checkout source_branch <paths>...

In example:

$ git branch
* master
  twitter_integration
$ git checkout twitter_integration app/models/avatar.rb db/migrate/20090223104419_create_avatars.rb test/unit/models/avatar_test.rb test/functional/models/avatar_test.rb
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   app/models/avatar.rb
#   new file:   db/migrate/20090223104419_create_avatars.rb
#   new file:   test/functional/models/avatar_test.rb
#   new file:   test/unit/models/avatar_test.rb
#
$ git commit -m "'Merge' avatar code from 'twitter_integration' branch"
[master]: created 4d3e37b: "'Merge' avatar code from 'twitter_integration' branch"
4 files changed, 72 insertions(+), 0 deletions(-)
create mode 100644 app/models/avatar.rb
create mode 100644 db/migrate/20090223104419_create_avatars.rb
create mode 100644 test/functional/models/avatar_test.rb
create mode 100644 test/unit/models/avatar_test.rb

Sources and full explanation http://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/

UPDATE:

With this method, git will not MERGE the file, it will just override any other change done on the destination branch. You will need to merge the changes manually:

$ git diff HEAD filename

How to enable external request in IIS Express?

Nothing worked for me until I found iisexpress-proxy.

Open command prompt as administrator, then run

npm install -g iisexpress-proxy

then

iisexpress-proxy 51123 to 81

assuming your Visual Studio project opens on localhost:51123 and you want to access on external IP address x.x.x.x:81

Edit: I am currently using ngrok

SQL: sum 3 columns when one column has a null value?

I would try this:

select sum (case when TotalHousM is null then 0 else TotalHousM end)
       + (case when TotalHousT is null then 0 else TotalHousT end)
       + (case when TotalHousW is null then 0 else TotalHousW end)
       + (case when TotalHousTH is null then 0 else TotalHousTH end)
       + (case when TotalHousF is null then 0 else TotalHousF end)
       as Total
From LeaveRequest

PHP - Redirect and send data via POST

A better and neater solution would be to use $_SESSION:

Using the session:

$_SESSION['POST'] = $_POST;

and for the redirect header request use:

header('Location: http://www.provider.com/process.jsp?id=12345&name=John', true, 307;)

307 is the http_response_code you can use for the redirection request with submitted POST values.

How do I tell if an object is a Promise?

ES6:

const promise = new Promise(resolve => resolve('olá'));

console.log(promise.toString().includes('Promise')); //true

?: operator (the 'Elvis operator') in PHP

See the docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
    switch (requestCode) {
        case PERMISSIONS_REQUEST_EXTERNAL_STORAGE: {
            if (grantResults.length > 0) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    // Denied
                } else {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        // To what you want
                    } else {
                       // Bob never checked click
                    }
                }
            }
        }
    }
}

Javascript: Fetch DELETE and PUT requests

Here is a fetch POST example. You can do the same for DELETE.

function createNewProfile(profile) {
    const formData = new FormData();
    formData.append('first_name', profile.firstName);
    formData.append('last_name', profile.lastName);
    formData.append('email', profile.email);

    return fetch('http://example.com/api/v1/registration', {
        method: 'POST',
        body: formData
    }).then(response => response.json())
}

createNewProfile(profile)
   .then((json) => {
       // handle success
    })
   .catch(error => error);

Test if string is URL encoded in PHP

send a variable that flags the decode when you already getting data from an url.

?path=folder/new%20file.txt&decode=1

Footnotes for tables in LaTeX

\begin{figure}[H]
\centering
{\includegraphics[width=1.0\textwidth]{image}}
\caption{captiontext\protect\footnotemark}
\label{fig:}
\end{figure}
\footnotetext{Footnotetext} 

Auto line-wrapping in SVG text

Here's an alternative:

<svg ...>
  <switch>
    <g requiredFeatures="http://www.w3.org/Graphics/SVG/feature/1.2/#TextFlow">
      <textArea width="200" height="auto">
       Text goes here
      </textArea>
    </g>
    <foreignObject width="200" height="200" 
     requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
      <p xmlns="http://www.w3.org/1999/xhtml">Text goes here</p>
    </foreignObject>
    <text x="20" y="20">No automatic linewrapping.</text>
  </switch>
</svg>

Noting that even though foreignObject may be reported as being supported with that featurestring, there's no guarantee that HTML can be displayed because that's not required by the SVG 1.1 specification. There is no featurestring for html-in-foreignobject support at the moment. However, it is still supported in many browsers, so it's likely to become required in the future, perhaps with a corresponding featurestring.

Note that the 'textArea' element in SVG Tiny 1.2 supports all the standard svg features, e.g advanced filling etc, and that you can specify either of width or height as auto, meaning that the text can flow freely in that direction. ForeignObject acts as clipping viewport.

Note: while the above example is valid SVG 1.1 content, in SVG 2 the 'requiredFeatures' attribute has been removed, which means the 'switch' element will try to render the first 'g' element regardless of having support for SVG 1.2 'textArea' elements. See SVG2 switch element spec.

std::string to char*

It won't automatically convert (thank god). You'll have to use the method c_str() to get the C string version.

std::string str = "string";
const char *cstr = str.c_str();

Note that it returns a const char *; you aren't allowed to change the C-style string returned by c_str(). If you want to process it you'll have to copy it first:

std::string str = "string";
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
// do stuff
delete [] cstr;

Or in modern C++:

std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1);

Adding external library into Qt Creator project

The error you mean is due to missing additional include path. Try adding it with: INCLUDEPATH += C:\path\to\include\files\ Hope it works. Regards.

Joining pairs of elements of a list

Well I would do it this way as I am no good with Regs..

CODE

t = '1. eat, food\n\
7am\n\
2. brush, teeth\n\
8am\n\
3. crack, eggs\n\
1pm'.splitlines()

print [i+j for i,j in zip(t[::2],t[1::2])]

output:

['1. eat, food   7am', '2. brush, teeth   8am', '3. crack, eggs   1pm']  

Hope this helps :)

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

The Function adds gaussian , salt-pepper , poisson and speckle noise in an image

Parameters
----------
image : ndarray
    Input image data. Will be converted to float.
mode : str
    One of the following strings, selecting the type of noise to add:

    'gauss'     Gaussian-distributed additive noise.
    'poisson'   Poisson-distributed noise generated from the data.
    's&p'       Replaces random pixels with 0 or 1.
    'speckle'   Multiplicative noise using out = image + n*image,where
                n is uniform noise with specified mean & variance.


import numpy as np
import os
import cv2
def noisy(noise_typ,image):
   if noise_typ == "gauss":
      row,col,ch= image.shape
      mean = 0
      var = 0.1
      sigma = var**0.5
      gauss = np.random.normal(mean,sigma,(row,col,ch))
      gauss = gauss.reshape(row,col,ch)
      noisy = image + gauss
      return noisy
   elif noise_typ == "s&p":
      row,col,ch = image.shape
      s_vs_p = 0.5
      amount = 0.004
      out = np.copy(image)
      # Salt mode
      num_salt = np.ceil(amount * image.size * s_vs_p)
      coords = [np.random.randint(0, i - 1, int(num_salt))
              for i in image.shape]
      out[coords] = 1

      # Pepper mode
      num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
      coords = [np.random.randint(0, i - 1, int(num_pepper))
              for i in image.shape]
      out[coords] = 0
      return out
  elif noise_typ == "poisson":
      vals = len(np.unique(image))
      vals = 2 ** np.ceil(np.log2(vals))
      noisy = np.random.poisson(image * vals) / float(vals)
      return noisy
  elif noise_typ =="speckle":
      row,col,ch = image.shape
      gauss = np.random.randn(row,col,ch)
      gauss = gauss.reshape(row,col,ch)        
      noisy = image + image * gauss
      return noisy

How can I run a function from a script in command line?

I have a situation where I need a function from bash script which must not be executed before (e.g. by source) and the problem with @$ is that myScript.sh is then run twice, it seems... So I've come up with the idea to get the function out with sed:

sed -n "/^func ()/,/^}/p" myScript.sh

And to execute it at the time I need it, I put it in a file and use source:

sed -n "/^func ()/,/^}/p" myScript.sh > func.sh; source func.sh; rm func.sh

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

This is all you need to:

  1. Add the id column
  2. Populate it with a sequence from 1 to count(*).
  3. Set it as primary key / not null.

Credit is given to @resnyanskiy who gave this answer in a comment.

SVN repository backup strategies

I have compiled the steps I followed for the purpose of taking a backup of the remote SVN repository of my project.

install svk (http://svk.bestpractical.com/view/SVKWin32)

install svn (http://sourceforge.net/projects/win32svn/files/1.6.16/Setup-Subversion-1.6.16.msi/download)

svk mirror //local <remote repository URL>

svk sync //local

This takes time and says that it is fetching the logs from repository. It creates a set of files inside C:\Documents and Settings\nverma\.svk\local.

To update this local repository with the latest set of changes from the remote one, just run the previous command from time to time.

Now you can play with your local repository (/home/user/.svk/local in this example) as if it were a normal SVN repository!

The only problem with this approach is that the local repository is created with a revision increments by the actual revision in the remote repository. As someone wrote:

The svk miror command generates a commit in the just created repository. So all the commits created by the subsequent sync will have revision numbers incremented by one as compared to the remote public repository.

But, this was OK for me as I only wanted some backup of the remote repository time to time, nothing else.

Verification:

To verify, use the SVN client with the local repository like this:

svn checkout "file:///C:/Documents and Settings\nverma/.svk/local/"  <local-dir-path-to-checkout-onto>

This command then goes to checkout the latest revision from the local repository. At the end it says Checked out revision N. This N was one more than the actual revision found in the remote repository (due to the problem mentioned above).

To verify that svk also brought all the history, the SVN checkout was run with various older revisions using -r with 2, 10, 50 etc. Then the files in <local-dir-path-to-checkout-onto> were confirmed to be from that revision.

At the end, zip the directory C:/Documents and Settings\nverma/.svk/local/ and store the zip somewhere. Keep doing this regularly.

What happens if you mount to a non-empty mount point with fuse?

For me the error message goes away if I unmount the old mount before mounting it again:

fusermount -u /mnt/point

If it's not already mounted you get a non-critical error:

$ fusermount -u /mnt/point

fusermount: entry for /mnt/point not found in /etc/mtab

So in my script I just put unmount it before mounting it.

PHP: cannot declare class because the name is already in use

You should use require_once and include_once. Inside parent.php use

include_once 'database.php';

And inside child1.php and child2.php use

include_once 'parent.php';

Group by with multiple columns using lambda

I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:

var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
                                    .Select(r => new ResultGrouping {
                                        IdObj1= r.Key.IdObj1,
                                        IdObj2= r.Key.IdObj2,
                                        IdObj3= r.Key.IdObj3,
                                        Results = r.ToArray(),
                                        Count = r.Count()
                                    });



private class ResultGrouping
        {
            public short IdObj1{ get; set; }
            public short IdObj2{ get; set; }
            public int IdObj3{ get; set; }

            public ResultCsvImport[] Results { get; set; }
            public int Count { get; set; }
        }

Where resultRecords is my initial list I'm grouping, and its a List<ResultCsvImport>. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3

How do I get the absolute directory of a file in bash?

Take a look at realpath which is available on GNU/Linux, FreeBSD and NetBSD, but not OpenBSD 6.8. I use something like:

CONTAININGDIR=$(realpath ${FILEPATH%/*})

to do what it sounds like you're trying to do.

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

using System.Drawing;
using System.Drawing.Imaging;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

public void ScreenshotByElement()
{
    IWebDriver driver = new FirefoxDriver();
    String baseURL = "www.google.com/"; //url link
    String filePath = @"c:\\img1.png";      

    driver.Navigate().GoToUrl(baseURL);
    var remElement = driver.FindElement(By.Id("Butterfly"));
    Point location = remElement.Location;

    var screenshot = (driver as FirefoxDriver).GetScreenshot();
    using (MemoryStream stream = new MemoryStream(screenshot.AsByteArray))
    {
        using (Bitmap bitmap = new Bitmap(stream))
        {
            RectangleF part = new RectangleF(location.X, location.Y, remElement.Size.Width, remElement.Size.Height);
            using (Bitmap bn = bitmap.Clone(part, bitmap.PixelFormat))
            {
                bn.Save(filePath, ImageFormat.Png);                        
            }
        }
    }
}

Detect WebBrowser complete page loading

I had the same issue of multiple DocumentCompleted fired events and tried out all the suggestions above. Finally, seems that in my case neither IsBusy property works right nor Url property, but the ReadyState seems to be what I needed, because it has the status 'Interactive' while loading the multiple frames and it gets the status 'Complete' only after loading the last one. Thus, I know when the page is fully loaded with all its components.

I hope this may help others too :)

bool to int conversion

You tagged your question [C] and [C++] at the same time. The results will be consistent between the languages, but the structure of the the answer is different for each of these languages.

In C language your examples has no relation to bool whatsoever (that applies to C99 as well). In C language relational operators do not produce bool results. Both 4 > 5 and 4 < 5 are expressions that produce results of type int with values 0 or 1. So, there's no "bool to int conversion" of any kind taking place in your examples in C.

In C++ relational operators do indeed produce bool results. bool values are convertible to int type, with true converting to 1 and false converting to 0. This is guaranteed by the language.

P.S. C language also has a dedicated boolean type _Bool (macro-aliased as bool), and its integral conversion rules are essentially the same as in C++. But nevertheless this is not relevant to your specific examples in C. Once again, relational operators in C always produce int (not bool) results regardless of the version of the language specification.

How do I make an HTTP request in Swift?

In Swift 4.1 and Xcode 9.4.1.

JSON POST approach example. To check internet connection add Reachability.h & .m files from https://developer.apple.com/library/archive/samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2

func yourFunctionName {
    //Check internet connection
    let networkReachability = Reachability.forInternetConnection()
    let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
    print(networkStatus)
    if networkStatus == NotReachable.rawValue {
        let msg = SharedClass.sharedInstance.noNetMsg//Message
        //Call alert from shared class
        SharedClass.sharedInstance.alert(view: self, title: "", message: msg)
    } else {
        //Call spinner from shared class
        SharedClass.sharedInstance.activityIndicator(view: self.view)//Play spinner

        let parameters = "Your parameters here"
        var request = URLRequest(url: URL(string: url)!)

        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"

        print("URL : \(request)")

        request.httpBody = parameters.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
            //Stop spinner
            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner
            //Print error in alert
            SharedClass.sharedInstance.alert(view: self, title: "", message: "\(String(describing: error!.localizedDescription))")
            return
            }

            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            do {
                let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
                print(response!)
                //Your code here                    
            } catch let error as NSError {
                print(error)
            }
        }

        task.resume()

    }

}

If you have interest to use this function in SharedClass

//My shared class
import UIKit
class SharedClass: NSObject {

static let sharedInstance = SharedClass()

func postRequestFunction(apiName: String , parameters: String, onCompletion: @escaping (_ success: Bool, _ error: Error?, _ result: [String: Any]?)->()) {

    var URL =  "your URL here/index.php/***?"

    URL = URL.replacingOccurrences(of: "***", with: apiName)

    var request = URLRequest(url: URL(string: URL)!)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    print("shared URL : \(request)")
    request.httpBody = parameters.data(using: .utf8)

    var returnRes:[String:Any] = [:]
    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        if let error = error {
            onCompletion(false, error, nil)
        } else {
            guard let data = data else {
                onCompletion(false, error, nil)
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
                do {
                   returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
                    onCompletion(true, nil, returnRes)

                } catch let error as NSError {
                   onCompletion(false, error, nil)
                }
            } else {
                onCompletion(false, error, nil)
            }
        }
    }
    task.resume()
}


private override init() {

}

And finally call this function like this....

SharedClass.sharedInstance.postRequestFunction(apiName: "Your API name", parameters: parameters) { (success, error, result) in
    print(result!)
    if success {
        //Your code here
    } else {
        print(error?.localizedDescription ?? "")
    }
}

Remove characters except digits from string using Python?

A fast version for Python 3:

# xx3.py
from collections import defaultdict
import string
_NoneType = type(None)

def keeper(keep):
    table = defaultdict(_NoneType)
    table.update({ord(c): c for c in keep})
    return table

digit_keeper = keeper(string.digits)

Here's a performance comparison vs. regex:

$ python3.3 -mtimeit -s'import xx3; x="aaa12333bb445bb54b5b52"' 'x.translate(xx3.digit_keeper)'
1000000 loops, best of 3: 1.02 usec per loop
$ python3.3 -mtimeit -s'import re; r = re.compile(r"\D"); x="aaa12333bb445bb54b5b52"' 'r.sub("", x)'
100000 loops, best of 3: 3.43 usec per loop

So it's a little bit more than 3 times faster than regex, for me. It's also faster than class Del above, because defaultdict does all its lookups in C, rather than (slow) Python. Here's that version on my same system, for comparison.

$ python3.3 -mtimeit -s'import xx; x="aaa12333bb445bb54b5b52"' 'x.translate(xx.DD)'
100000 loops, best of 3: 13.6 usec per loop

How can I remove all objects but one from the workspace in R?

This takes advantage of ls()'s pattern option, in the case you have a lot of objects with the same pattern that you don't want to keep:

> foo1 <- "junk"; foo2 <- "rubbish"; foo3 <- "trash"; x <- "gold"  
> ls()
[1] "foo1" "foo2" "foo3" "x"   
> # Let's check first what we want to remove
> ls(pattern = "foo")
[1] "foo1" "foo2" "foo3"
> rm(list = ls(pattern = "foo"))
> ls()
[1] "x"

How do I remove trailing whitespace using a regular expression?

Regex to find trailing and leading whitespaces:

^[ \t]+|[ \t]+$

Difference between "enqueue" and "dequeue"

Enqueue and Dequeue tend to be operations on a queue, a data structure that does exactly what it sounds like it does.

You enqueue items at one end and dequeue at the other, just like a line of people queuing up for tickets to the latest Taylor Swift concert (I was originally going to say Billy Joel but that would date me severely).

There are variations of queues such as double-ended ones where you can enqueue and dequeue at either end but the vast majority would be the simpler form:

           +---+---+---+
enqueue -> | 3 | 2 | 1 | -> dequeue
           +---+---+---+

That diagram shows a queue where you've enqueued the numbers 1, 2 and 3 in that order, without yet dequeuing any.


By way of example, here's some Python code that shows a simplistic queue in action, with enqueue and dequeue functions. Were it more serious code, it would be implemented as a class but it should be enough to illustrate the workings:

import random

def enqueue(lst, itm):
    lst.append(itm)        # Just add item to end of list.
    return lst             # And return list (for consistency with dequeue).

def dequeue(lst):
    itm = lst[0]           # Grab the first item in list.
    lst = lst[1:]          # Change list to remove first item.
    return (itm, lst)      # Then return item and new list.

# Test harness. Start with empty queue.

myList = []

# Enqueue or dequeue a bit, with latter having probability of 10%.

for _ in range(15):
    if random.randint(0, 9) == 0 and len(myList) > 0:
        (itm, myList) = dequeue(myList)
        print(f"Dequeued {itm} to give {myList}")
    else:
        itm = 10 * random.randint(1, 9)
        myList = enqueue(myList, itm)
        print(f"Enqueued {itm} to give {myList}")

# Now dequeue remainder of list.

print("========")
while len(myList) > 0:
    (itm, myList) = dequeue(myList)
    print(f"Dequeued {itm} to give {myList}")

A sample run of that shows it in operation:

Enqueued 70 to give [70]
Enqueued 20 to give [70, 20]
Enqueued 40 to give [70, 20, 40]
Enqueued 50 to give [70, 20, 40, 50]
Dequeued 70 to give [20, 40, 50]
Enqueued 20 to give [20, 40, 50, 20]
Enqueued 30 to give [20, 40, 50, 20, 30]
Enqueued 20 to give [20, 40, 50, 20, 30, 20]
Enqueued 70 to give [20, 40, 50, 20, 30, 20, 70]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20, 20]
Dequeued 20 to give [40, 50, 20, 30, 20, 70, 20, 20]
Enqueued 80 to give [40, 50, 20, 30, 20, 70, 20, 20, 80]
Dequeued 40 to give [50, 20, 30, 20, 70, 20, 20, 80]
Enqueued 90 to give [50, 20, 30, 20, 70, 20, 20, 80, 90]
========
Dequeued 50 to give [20, 30, 20, 70, 20, 20, 80, 90]
Dequeued 20 to give [30, 20, 70, 20, 20, 80, 90]
Dequeued 30 to give [20, 70, 20, 20, 80, 90]
Dequeued 20 to give [70, 20, 20, 80, 90]
Dequeued 70 to give [20, 20, 80, 90]
Dequeued 20 to give [20, 80, 90]
Dequeued 20 to give [80, 90]
Dequeued 80 to give [90]
Dequeued 90 to give []

How to read/write arbitrary bits in C/C++

You have to do a shift and mask (AND) operation. Let b be any byte and p be the index (>= 0) of the bit from which you want to take n bits (>= 1).

First you have to shift right b by p times:

x = b >> p;

Second you have to mask the result with n ones:

mask = (1 << n) - 1;
y = x & mask;

You can put everything in a macro:

#define TAKE_N_BITS_FROM(b, p, n) ((b) >> (p)) & ((1 << (n)) - 1)

Getting all file names from a folder using C#

It depends on what you want to do.

ref: http://www.csharp-examples.net/get-files-from-directory/

This will bring back ALL the files in the specified directory

string[] fileArray = Directory.GetFiles(@"c:\Dir\");

This will bring back ALL the files in the specified directory with a certain extension

string[] fileArray = Directory.GetFiles(@"c:\Dir\", "*.jpg");

This will bring back ALL the files in the specified directory AS WELL AS all subdirectories with a certain extension

string[] fileArray = Directory.GetFiles(@"c:\Dir\", "*.jpg", SearchOption.AllDirectories);

Hope this helps

Timestamp Difference In Hours for PostgreSQL

Michael Krelin's answer is close is not entirely safe, since it can be wrong in rare situations. The problem is that intervals in PostgreSQL do not have context with regards to things like daylight savings. Intervals store things internally as months, days, and seconds. Months aren't an issue in this case since subtracting two timestamps just use days and seconds but 'days' can be a problem.

If your subtraction involves daylight savings change-overs, a particular day might be considered 23 or 25 hours respectively. The interval will take that into account, which is useful for knowing the amount of days that passed in the symbolic sense but it would give an incorrect number of the actual hours that passed. Epoch on the interval will just multiply all days by 24 hours.

For example, if a full 'short' day passes and an additional hour of the next day, the interval will be recorded as one day and one hour. Which converted to epoch/3600 is 25 hours. But in reality 23 hours + 1 hour should be a total of 24 hours.

So the safer method is:

(EXTRACT(EPOCH FROM current_timestamp) - EXTRACT(EPOCH FROM somedate))/3600

As Michael mentioned in his follow-up comment, you'll also probably want to use floor() or round() to get the result as an integer value.

proper hibernate annotation for byte[]

i fixed My issue by adding the annotation of @Lob which will create the byte[] in oracle as blob , but this annotation will create the field as oid which not work properly , To make byte[] created as bytea i made customer Dialect for postgres as below

Public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {
    public PostgreSQLDialectCustom() {
        System.out.println("Init PostgreSQLDialectCustom");
        registerColumnType( Types.BLOB, "bytea" );

      }

    @Override
    public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
      return BinaryTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
 }

Also need to override parameter for the Dialect

spring.jpa.properties.hibernate.dialect=com.ntg.common.DBCompatibilityHelper.PostgreSQLDialectCustom

more hint can be found her : https://dzone.com/articles/postgres-and-oracle

How to add element to C++ array?

int arr[] = new int[15];

The variable arr holds a memory address. At the memory address, there are 15 consecutive ints in a row. They can be referenced with index 0 to 14 inclusive.

In php i can just do this arr[]=22; this will automatically add 22 to the next empty index of array.

There is no concept of 'next' when dealing with arrays.
One important thing that I think you are missing is that as soon as the array is created, all elements of the array already exist. They are uninitialized, but they all do exist already. So you aren't 'filling' the elements of the array as you go, they are already filled, just with uninitialized values. There is no way to test for an uninitialized element in an array.

It sounds like you want to use a data structure such as a queue or stack or vector.

Auto-increment primary key in SQL tables

  1. Presumably you are in the design of the table. If not: right click the table name - "Design".
  2. Click the required column.
  3. In "Column properties" (at the bottom), scroll to the "Identity Specification" section, expand it, then toggle "(Is Identity)" to "Yes".

enter image description here

How to label scatterplot points by name?

Well I did not think this was possible until I went and checked. In some previous version of Excel I could not do this. I am currently using Excel 2013.

This is what you want to do in a scatter plot:

  1. right click on your data point

  2. select "Format Data Labels" (note you may have to add data labels first)

  3. put a check mark in "Values from Cells"
  4. click on "select range" and select your range of labels you want on the points

Example Graph

UPDATE: Colouring Individual Labels

In order to colour the labels individually use the following steps:

  1. select a label. When you first select, all labels for the series should get a box around them like the graph above.
  2. Select the individual label you are interested in editing. Only the label you have selected should have a box around it like the graph below.
  3. On the right hand side, as shown below, Select "TEXT OPTIONS".
  4. Expand the "TEXT FILL" category if required.
  5. Second from the bottom of the category list is "COLOR", select the colour you want from the pallet.

If you have the entire series selected instead of the individual label, text formatting changes should apply to all labels instead of just one.

Colouring

string sanitizer for filename

Making a small adjustment to Tor Valamo's solution to fix the problem noticed by Dominic Rodger, you could use:

// Remove anything which isn't a word, whitespace, number
// or any of the following caracters -_~,;[]().
// If you don't need to handle multi-byte characters
// you can use preg_replace rather than mb_ereg_replace
// Thanks @Lukasz Rysiak!
$file = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $file);
// Remove any runs of periods (thanks falstro!)
$file = mb_ereg_replace("([\.]{2,})", '', $file);

Extracting substrings in Go

WARNING: operating on strings alone will only work with ASCII and will count wrong when input is a non-ASCII UTF-8 encoded character, and will probably even corrupt characters since it cuts multibyte chars mid-sequence.

Here's a UTF-8-aware version:

// NOTE: this isn't multi-Unicode-codepoint aware, like specifying skintone or
//       gender of an emoji: https://unicode.org/emoji/charts/full-emoji-modifiers.html
func substr(input string, start int, length int) string {
    asRunes := []rune(input)
    
    if start >= len(asRunes) {
        return ""
    }
    
    if start+length > len(asRunes) {
        length = len(asRunes) - start
    }
    
    return string(asRunes[start : start+length])
}

Converting milliseconds to minutes and seconds with Javascript

Best is this!

function msToTime(duration) {
var milliseconds = parseInt((duration%1000))
    , seconds = parseInt((duration/1000)%60)
    , minutes = parseInt((duration/(1000*60))%60)
    , hours = parseInt((duration/(1000*60*60))%24);

hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;

return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

It will return 00:04:21.223 You can format this string then as you wish.

Change the Textbox height?

May be it´s a little late. But you can do this.

txtFoo.Multiline = true;
txtFoo.MinimumSize = new Size(someWith,someHeight);

I solved it that way.

Flutter - Layout a Grid

Please visit this repo.

Widget _gridView() {
    return GridView.count(
      crossAxisCount: 4,
      padding: EdgeInsets.all(4.0),
      childAspectRatio: 8.0 / 9.0,
      children: itemList
          .map(
            (Item) => ItemList(item: Item),
          )
          .toList(),
    );
  }

Below screenshot contains crossAxisCount: 2 this screenshot is for grid count 2

C program to check little vs. big endian

Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:


The following program would determine that:

#include <stdio.h>
#include <stdint.h>

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } e = { 0x01000000 };

    return e.c[0];
}

int main(void)
{
    printf("System is %s-endian.\n",
        is_big_endian() ? "big" : "little");

    return 0;
}

You also have this approach; from Quake II:

byte    swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
    bigendien = false;

And !is_big_endian() is not 100% to be little as it can be mixed/middle.

Believe this can be checked using same approach only change value from 0x01000000 to i.e. 0x01020304 giving:

switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE

But not entirely sure about that one ...

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

I got this error because I declared a variable (above the ConfigureServices method) of type that was my context. I had:

CupcakeContext _ctx

Not sure what I was thinking. I know it's legal to do this if your passing in a parameter to the Configure method.

form with no action and where enter does not reload page

Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.

Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?

Docker CE on RHEL - Requires: container-selinux >= 2.9

To update container-selinux I had to install epel-release first:

Add Centos-7 repository

wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

Install epel-release

yum install epel-release

Update container-selinux

yum install container-selinux

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

Delete the java.exe process in Task Manager and run mvn clean install.It worked for me.

text-overflow: ellipsis not working

For multiple lines

In chrome, you can apply this css if you need to apply ellipsis on multiple lines.

You can also add width in your css to specify element of certain width:

_x000D_
_x000D_
.multi-line-ellipsis {_x000D_
    overflow: hidden;_x000D_
    display: -webkit-box;_x000D_
    -webkit-line-clamp: 3;_x000D_
    -webkit-box-orient: vertical;_x000D_
}
_x000D_
<p class="multi-line-ellipsis">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
_x000D_
_x000D_
_x000D_

Image re-size to 50% of original size in HTML

You can use the x descriptor of the srcset attribute as such:

_x000D_
_x000D_
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />

<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />

<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
_x000D_
_x000D_

Currently supported by all browsers except IE. (caniuse)

MDN documentation

How to convert comma-separated String to List?

ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>(); 
String marray[]= mListmain.split(",");

Are there dictionaries in php?

Normal array can serve as a dictionary data structure. In general it has multipurpose usage: array, list (vector), hash table, dictionary, collection, stack, queue etc.

$names = [
    'bob' => 27,
    'billy' => 43,
    'sam' => 76,
];

$names['bob'];

And because of wide design it gains no full benefits of specific data structure. You can implement your own dictionary by extending an ArrayObject or you can use SplObjectStorage class which is map (dictionary) implementation allowing objects to be assigned as keys.

What is the function of the push / pop instructions used on registers in x86 assembly?

Almost all CPUs use stack. The program stack is LIFO technique with hardware supported manage.

Stack is amount of program (RAM) memory normally allocated at the top of CPU memory heap and grow (at PUSH instruction the stack pointer is decreased) in opposite direction. A standard term for inserting into stack is PUSH and for remove from stack is POP.

Stack is managed via stack intended CPU register, also called stack pointer, so when CPU perform POP or PUSH the stack pointer will load/store a register or constant into stack memory and the stack pointer will be automatic decreased xor increased according number of words pushed or poped into (from) stack.

Via assembler instructions we can store to stack:

  1. CPU registers and also constants.
  2. Return addresses for functions or procedures
  3. Functions/procedures in/out variables
  4. Functions/procedures local variables.

Node.js global proxy setting

replace {userid} and {password} with your id and password in your organization or login to your machine.

npm config set proxy http://{userid}:{password}@proxyip:8080/
npm config set https-proxy http://{userid}:{password}@proxyip:8080/
npm config set http-proxy http://{userid}:{password}@proxyip:8080/
strict-ssl=false

Why do I get a "permission denied" error while installing a gem?

Install rbenv or rvm as your Ruby version manager (I prefer rbenv) via homebrew (ie. brew update & brew install rbenv) but then for example in rbenv's case make sure to add rbenv to your $PATH as instructed here and here.

For a deeper explanation on how rbenv works I recommend this.

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

Redirect after Login on WordPress

This may help. Peter's Login Redirect

Redirect users to different locations after logging in and logging out.

Define a set of redirect rules for specific users, users with specific roles, users with specific capabilities, and a blanket rule for all other users. Also, set a redirect URL for post-registration. This is all managed in Settings > Login/logout redirects.

You can use the syntax [variable]username[/variable] in your URLs so that the system will build a dynamic URL upon each login, replacing that text with the user's username. In addition to username, there is "userslug", "homeurl", "siteurl", "postid-23", "http_referer" and you can also add your own custom URL "variables"...

How to draw border on just one side of a linear layout?

There is no mention about nine-patch files here. Yes, you have to create the file, however it's quite easy job and it's really "cross-version and transparency supporting" solution. If the file is placed to the drawable-nodpi directory, it works px based, and in the drawable-mdpi works approximately as dp base (thanks to resample).

Example file for the original question (border-right:1px solid red;) is here:

http://ge.tt/517ZIFC2/v/3?c

Just place it to the drawable-nodpi directory.

JavaScript isset() equivalent

If you are using underscorejs I always use

if (!_.isUndefined(data) && !_.isNull(data)) {
     //your stuff
}

Tab separated values in awk

You can set the Field Separator:

... | awk 'BEGIN {FS="\t"}; {print $1}'

Excellent read:

https://docs.freebsd.org/info/gawk/gawk.info.Field_Separators.html

jquery select element by xpath

First create an xpath selector function.

function _x(STR_XPATH) {
    var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
    var xnodes = [];
    var xres;
    while (xres = xresult.iterateNext()) {
        xnodes.push(xres);
    }

    return xnodes;
}

To use the xpath selector with jquery, you can do like this:

$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');

Hope this can help.

Changing image size in Markdown

If we just use normal HTML image tag like this it is working. I use this in website made with Jekyll.

<img class="img-fluid" src="./img/face.jpg" alt="img-verification">

If we add bootstrap classes as per this example it works fine.

Increasing (or decreasing) the memory available to R processes

  1. Buy more ram
  2. Switch to a 64-bit OS. Combine with point 1.

Create a symbolic link of directory in Ubuntu

That's what ln is documented to do when the target already exists and is a directory. If you want /etc/nginx to be a symlink rather than contain a symlink, you had better not create it as a directory first!

Bootstrap dropdown not working

you have to import this files into the <head></head> of your html.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Make sure that the column values u added in entity class having get set properties also in the same order which is present in target table.

Angular 6 Material mat-select change method removed

I have this issue today with mat-option-group. The thing which solved me the problem is using in other provided event of mat-select : valueChange

I put here a little code for understanding :

<mat-form-field >
  <mat-label>Filter By</mat-label>
  <mat-select  panelClass="" #choosedValue (valueChange)="doSomething1(choosedValue.value)"> <!-- (valueChange)="doSomething1(choosedValue.value)" instead of (change) or other event-->

    <mat-option >-- None --</mat-option>
      <mat-optgroup  *ngFor="let group of filterData" [label]="group.viewValue"
                    style = "background-color: #0c5460">
        <mat-option *ngFor="let option of group.options" [value]="option.value">
          {{option.viewValue}}
        </mat-option>
      </mat-optgroup>
  </mat-select>
</mat-form-field>

Mat Version:

"@angular/material": "^6.4.7",

Batch file to run a command in cmd within a directory

Mine DID execute commands in order. Here's my version of what I was using it for:

START cmd.exe /k "U: & cd U:\Design_stuff\new_lcso_website_2017 & python -m http.server"

I needed to

  1. Change to my U drive
  2. CD to a specific folder containing a website I'm redesigning
  3. Execute python with the http server module (to display the contents in my browser).

If those commands are out of order, it would not display the correct files. I initially forgot to change to U: and, running the batch file on my Desktop, it created a web page in my browser at http://localhost:8000 showing me the contents of my Desktop instead of the folder I wanted.

sort json object in javascript

In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
  var key = sortedKeys[i];
  addObjectToTable(json[key]);
}

Get Month name from month number

This should return month text (January - December) from the month index (1-12)

int monthNumber = 1; //1-12  
string monthName = new DateTimeFormatInfo().GetMonthName(monthNumber);