Programs & Examples On #Directinput

Test credit card numbers for use with PayPal sandbox

In case anyone else comes across this in a search for an answer...

The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.

Go here and get a number generated. Use any expiry date and CVV

https://ppmts.custhelp.com/app/answers/detail/a_id/750/

It's worked every time for me so far...

Why do multiple-table joins produce duplicate rows?

If one of the tables M, S, D, or H has more than one row for a given Id (if just the Id column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).

References:

Related Question on MSDN Forum

simple way to display data in a .txt file on a webpage?

You cannot style a text file, it must be HTML

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

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

According to my research there is no way to do this exactly the way you want. You can manually re-create the table and copy the data, or SSMS can (and will) do this for you (when you drag and drop a column to a different order, it does this). In fact it souldn't matter what order the columns are... As an alternative solution you can select the data you want in the order you desired. For example, instead of using asterisk (*) in select, specify the column names in some order... Lets say MyTable has col1, col2, col3, colNew columns.

Instead of:

SELECT * FROM MyTable

You can use:

SELECT col1, colNew, col2, col3 FROM MyTable

Display PDF within web browser

Have you tried using a simple img tag?

<img scr="https://www.typomania.co.uk/pdfs/lipsum.pdf">

Handle file download from ajax post

If response is an Array Buffer, try this under onsuccess event in Ajax:

 if (event.data instanceof ArrayBuffer) {
          var binary = '';
          var bytes = new Uint8Array(event.data);
          for (var i = 0; i < bytes.byteLength; i++) {
              binary += String.fromCharCode(bytes[i])
          }
          $("#some_id").append("<li><img src=\"data:image/png;base64," + window.btoa(binary) + "\"/></span></li>");
          return;
      }
  • where event.data is response received in success function of xhr event.

Insert data through ajax into mysql database

ajax:

$(document).on('click','#mv_secure_page',function(e) {
    var data = $("#m_form1").serialize();
    $.ajax({
        data: data,
        type: "post",
        url: "adapter.php",
        success: function(data){
        alert("Data: " + data);
        }
    });
});

php code:

<?php
/**
 * Created by PhpStorm.
 * User: Engg Amjad
 * Date: 11/9/16
 * Time: 1:28 PM
 */


if(isset($_REQUEST)){
    include_once('inc/system.php');

    $full_name=$_POST['full_name'];
    $business_name=$_POST['business_name'];
    $email=$_POST['email'];
    $phone=$_POST['phone'];
    $message=$_POST['message'];

    $sql="INSERT INTO mars (f_n,b_n,em,p_n,msg) values('$full_name','$business_name','$email','$phone','$message') ";

    $sql_result=mysqli_query($con,$sql);
    if($sql_result){
       echo "inserted successfully";
    }else{
        echo "Query failed".mysqli_error($con);
    }
}
?>

Javascript Uncaught Reference error Function is not defined

Change the wrapping from "onload" to "No wrap - in <body>"

The function defined has a different scope.

How to implement "Access-Control-Allow-Origin" header in asp.net

1.Install-Package Microsoft.AspNet.WebApi.Cors

2 . Add this code in WebApiConfig.cs.

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes

    config.EnableCors();

    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

3. Add this

using System.Web.Http.Cors; 

4. Add this code in Api Controller (HomeController.cs)

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class HomeController : ApiController
{
    [HttpGet]
    [Route("api/Home/test")]
    public string test()
    {
       return "";
    }
}

PHP: How to get referrer URL?

If $_SERVER['HTTP_REFERER'] variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.

How do I type a TAB character in PowerShell?

TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

How to find elements by class

From the documentation:

As of Beautiful Soup 4.1.2, you can search by CSS class using the keyword argument class_:

soup.find_all("a", class_="sister")

Which in this case would be:

soup.find_all("div", class_="stylelistrow")

It would also work for:

soup.find_all("div", class_="stylelistrowone stylelistrowtwo")

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Instead of thinking of it as 'extracting', I like to think of it as 'isolating'. Once the desired bits are isolated, you can do what you will with them.

To isolate any set of bits, apply an AND mask.

If you want the last X bits of a value, there is a simple trick that can be used.

unsigned  mask;
mask = (1 << X) - 1;
lastXbits = value & mask;

If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...

unsigned  mask;
mask = ((1 << X) - 1) << startBit;
isolatedXbits = value & mask;

Hope this helps.

Python: avoid new line with print command

You simply need to do:

print 'lakjdfljsdf', # trailing comma

However in:

print 'lkajdlfjasd', 'ljkadfljasf'

There is implicit whitespace (ie ' ').

You also have the option of:

import sys
sys.stdout.write('some data here without a new line')

Table with fixed header and fixed column on pure css

Here is another solution I have just build with css grids based on the answers in here:

https://codesandbox.io/s/sweet-resonance-m733i

MySQL Join Where Not Exists

There are three possible ways to do that.

  1. Option

    SELECT  lt.* FROM    table_left lt
    LEFT JOIN
        table_right rt
    ON      rt.value = lt.value
    WHERE   rt.value IS NULL
    
  2. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   lt.value NOT IN
    (
    SELECT  value
    FROM    table_right rt
    )
    
  3. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   NOT EXISTS
    (
    SELECT  NULL
    FROM    table_right rt
    WHERE   rt.value = lt.value
    )
    

Integer to IP Address - C

Hint: break up the 32-bit integer to 4 8-bit integers, and print them out.

Something along the lines of this (not compiled, YMMV):

int i = 0xDEADBEEF; // some 32-bit integer
printf("%i.%i.%i.%i",
          (i >> 24) & 0xFF,
          (i >> 16) & 0xFF,
          (i >> 8) & 0xFF,
          i & 0xFF);

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

Check the below links:

  • Implicit Wait - It instructs the web driver to wait for some time by poll the DOM. Once you declared implicit wait it will be available for the entire life of web driver instance. By default the value will be 0. If you set a longer default, then the behavior will poll the DOM on a periodic basis depending on the browser/driver implementation.

  • Explicit Wait + ExpectedConditions - It is the custom one. It will be used if we want the execution to wait for some time until some condition achieved.

How to get all registered routes in Express?

This gets routes registered directly on the app (via app.VERB) and routes that are registered as router middleware (via app.use). Express 4.11.0

//////////////
app.get("/foo", function(req,res){
    res.send('foo');
});

//////////////
var router = express.Router();

router.get("/bar", function(req,res,next){
    res.send('bar');
});

app.use("/",router);


//////////////
var route, routes = [];

app._router.stack.forEach(function(middleware){
    if(middleware.route){ // routes registered directly on the app
        routes.push(middleware.route);
    } else if(middleware.name === 'router'){ // router middleware 
        middleware.handle.stack.forEach(function(handler){
            route = handler.route;
            route && routes.push(route);
        });
    }
});

// routes:
// {path: "/foo", methods: {get: true}}
// {path: "/bar", methods: {get: true}}

How to present popover properly in iOS 8

This is best explained on the iOS8 Day-by-Day blog

In short, once you've set your UIViewController's modalPresentationStyle to .Popover, you can get hold of a UIPopoverPresentationClass (a new iOS8 class) via the controller's popoverPresentationController property.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

How to create radio buttons and checkbox in swift (iOS)?

The decision of checking or unchecking the checkbox button is something out of the scope of the view. View itself should only take care of drawing the elements, not deciding about the internal state of that. My suggested implementation is as follows:

import UIKit

class Checkbox: UIButton {

    let checkedImage = UIImage(named: "checked")
    let uncheckedImage = UIImage(named: "uncheked")
    var action: ((Bool) -> Void)? = nil

    private(set) var isChecked: Bool = false {
        didSet{
            self.setImage(
                self.isChecked ? self.checkedImage : self.uncheckedImage,
                for: .normal
            )
        }
    }

    override func awakeFromNib() {
        self.addTarget(
            self,
            action:#selector(buttonClicked(sender:)),
            for: .touchUpInside
        )
        self.isChecked = false
    }

    @objc func buttonClicked(sender: UIButton) {
        if sender == self {
            self.action?(!self.isChecked)
        }
    }

    func update(checked: Bool) {
        self.isChecked = checked
    }
}

It can be used with Interface Builder or programmatically. The usage of the view could be as the following example:

let checkbox_field = Checkbox(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
checkbox_field.action = { [weak checkbox_field] checked in
    // any further checks and business logic could be done here
    checkbox_field?.update(checked: checked)
}

How do I wait for an asynchronously dispatched block to finish?

- (void)performAndWait:(void (^)(dispatch_semaphore_t semaphore))perform;
{
  NSParameterAssert(perform);
  dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  perform(semaphore);
  dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
  dispatch_release(semaphore);
}

Example usage:

[self performAndWait:^(dispatch_semaphore_t semaphore) {
  [self someLongOperationWithSuccess:^{
    dispatch_semaphore_signal(semaphore);
  }];
}];

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

To add slightly to the other answers, if you actually want to catch SIGTERM (the default signal sent by the kill command), you can use syscall.SIGTERM in place of os.Interrupt. Beware that the syscall interface is system-specific and might not work everywhere (e.g. on windows). But it works nicely to catch both:

c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
....

Server unable to read htaccess file, denying access to be safe

Set group of your public directory to nobody.

Uploading an Excel sheet and importing the data into SQL Server database

Not sure why the file path is not working, I have some similar code that works fine. But if with two "\" it works, you can always do path = path.Replace(@"\", @"\\");

Trim to remove white space

No need for jQuery

JavaScript does have a native .trim() method.

var name = "    John Smith  ";
name = name.trim();

console.log(name); // "John Smith"

Example Here

String.prototype.trim()

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

Adding values to specific DataTable cells

You mean you want to add a new row and only put data in a certain column? Try the following:

var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);

As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Value instead of whatever data type you imagine it would be.

How do I manage conflicts with git submodules?

I struggled a bit with the answers on this question and didn't have much luck with the answers in a similar SO post either. So this is what worked for me - bearing in mind that in my case, the submodule was maintained by a different team, so the conflict came from different submodule versions in master and my local branch of the project I was working on:

  1. Run git status - make a note of the submodule folder with conflicts
  2. Reset the submodule to the version that was last committed in the current branch:

    git reset HEAD path/to/submodule

  3. At this point, you have a conflict-free version of your submodule which you can now update to the latest version in the submodule's repository:

    cd path/to/submodule
    git submodule foreach git pull origin SUBMODULE-BRANCH-NAME
  4. And now you can commit that and get back to work.

How do you run a .bat file from PHP?

When you use the exec() function, it is as though you have a cmd terminal open and are typing commands straight to it.

Use single quotes like this $str = exec('start /B Path\to\batch.bat');
The /B means the bat will be executed in the background so the rest of the php will continue after running that line, as opposed to $str = exec('start /B /C command', $result); where command is executed and then result is stored for later use.

PS: It works for both Windows and Linux.
More details are here http://www.php.net/manual/en/function.exec.php :)

python pandas convert index to datetime

Doing

df.index = pd.to_datetime(df.index, errors='coerce')

the data type of the index has changed to

dataframe information

Perl: function to trim string leading and trailing whitespace

Here's one approach using a regular expression:

$string =~ s/^\s+|\s+$//g ;     # remove both leading and trailing whitespace

Perl 6 will include a trim function:

$string .= trim;

Source: Wikipedia

Swift error : signal SIGABRT how to solve it

In my case there was no log whatsoever.

My mistake was to push a view controller in a navigation stack that was already part of the navigation stack.

When is the init() function run?

mutil init function in one package execute order:

  1. const and variable defined file init() function execute

  2. init function execute order by the filename asc

How do I use Maven through a proxy?

I also had this problem, and I solved it by editing the settings.xml file in my .m2 folder. My settings.xml is like this now:

<settings>
  <proxies>
    <proxy>
      <id>genproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxyHost</host>
      <port>3128</port>
      <username>username</username>
      <password>password</password>
    </proxy>
 </proxies>
</settings>

how to write procedure to insert data in to the table in phpmyadmin?

This method work for me:

DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
 BEGIN
 INSERT INTO USER VALUES(id,NAME);
 END$$
DELIMITER ;

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How to add users to Docker container?

To avoid the interactive questions by adduser, you can call it with these parameters:

RUN adduser --disabled-password --gecos '' newuser

The --gecos parameter is used to set the additional information. In this case it is just empty.

On systems with busybox (like Alpine), use

RUN adduser -D -g '' newuser

See busybox adduser

Add new field to every document in a MongoDB collection

Same as the updating existing collection field, $set will add a new fields if the specified field does not exist.

Check out this example:

> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }

EDIT:

In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents

db.your_collection.update(
  {},
  { $set: {"new_field": 1} },
  false,
  true
)

EDIT:

In the above example last 2 fields false, true specifies the upsert and multi flags.

Upsert: If set to true, creates a new document when no document matches the query criteria.

Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

This is for Mongo versions prior to 2.2. For latest versions the query is changed a bit

db.your_collection.update({},
                          {$set : {"new_field":1}},
                          {upsert:false,
                          multi:true}) 

Should I use Python 32bit or Python 64bit

In my experience, using the 32-bit version is more trouble-free. Unless you are working on applications that make heavy use of memory (mostly scientific computing, that uses more than 2GB memory), you're better off with 32-bit versions because:

  1. You generally use less memory.
  2. You have less problems using COM (since you are on Windows).
  3. If you have to load DLLs, they most probably are also 32-bit. Python 64-bit can't load 32-bit libraries without some heavy hacks running another Python, this time in 32-bit, and using IPC.
  4. If you have to load DLLs that you compile yourself, you'll have to compile them to 64-bit, which is usually harder to do (specially if using MinGW on Windows).
  5. If you ever use PyInstaller or py2exe, those tools will generate executables with the same bitness of your Python interpreter.

Android customized button; changing text color

Create a stateful color for your button, just like you did for background, for example:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Focused and not pressed -->
    <item android:state_focused="true" 
          android:state_pressed="false" 
          android:color="#ffffff" />

    <!-- Focused and pressed -->
    <item android:state_focused="true" 
          android:state_pressed="true" 
          android:color="#000000" />

    <!-- Unfocused and pressed -->
    <item android:state_focused="false" 
          android:state_pressed="true" 
          android:color="#000000" />

    <!-- Default color -->
    <item android:color="#ffffff" />

</selector>

Place the xml in a file at res/drawable folder i.e. res/drawable/button_text_color.xml. Then just set the drawable as text color:

android:textColor="@drawable/button_text_color"

What are the special dollar sign shell variables?

  • $_ last argument of last command
  • $# number of arguments passed to current script
  • $* / $@ list of arguments passed to script as string / delimited list

off the top of my head. Google for bash special variables.

How can you get the build/version number of your Android application?

If you want to use it on XML content then add the below line in your Gradle file:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

And then use it on your XML content like this:

<TextView
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/versionName" />

Making a mocked method return an argument that was passed to it

With Java 8, Steve's answer can become

public void testMyFunction() throws Exception {
    Application mock = mock(Application.class);
    when(mock.myFunction(anyString())).thenAnswer(
    invocation -> {
        Object[] args = invocation.getArguments();
        return args[0];
    });

    assertEquals("someString", mock.myFunction("someString"));
    assertEquals("anotherString", mock.myFunction("anotherString"));
}

EDIT: Even shorter:

public void testMyFunction() throws Exception {
    Application mock = mock(Application.class);
    when(mock.myFunction(anyString())).thenAnswer(
        invocation -> invocation.getArgument(0));

    assertEquals("someString", mock.myFunction("someString"));
    assertEquals("anotherString", mock.myFunction("anotherString"));
}

How do I break a string across more than one line of code in JavaScript?

The backslash operator is not reliable. Try pasting this function in your browser console:

function printString (){
  const s = "someLongLineOfText\
  ThatShouldNotBeBroken";
  console.log(s);
}

and then run it. Because of the conventional (and correct) indentation within the function, two extra spaces will be included, resulting in someLongLineOfText ThatShouldNotBeBroken.

Even using backticks will not help in this case. Always use the concatenation "+" operator to prevent this type of issue.

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I got this error while upgrading all libs to latest version

in older version following are imports

import { TabViewAnimated, TabViewPagerPan } from 'react-native-tab-view';

but in new version they are replaced with following

import { TabView, PagerPan } from "react-native-tab-view";

So be check proper all your import are available by using control click

How to Migrate to WKWebView?

Swift is not a requirement, everything works fine with Objective-C. UIWebView will continue to be supported, so there is no rush to migrate if you want to take your time. However, it will not get the javascript and scrolling performance enhancements of WKWebView.

For backwards compatibility, I have two properties for my view controller: a UIWebView and a WKWebView. I use the WKWebview only if the class exists:

if ([WKWebView class]) {
    // do new webview stuff
} else {
    // do old webview stuff
}

Whereas I used to have a UIWebViewDelegate, I also made it a WKNavigationDelegate and created the necessary methods.

Pretty git branch graphs

Sourcetree is a really good one. It does print out a good looking and medium size history and branch graph: (the following is done on an experimental Git project just to see some branches). Supports Windows 7+ and Mac OS X 10.6+.

Example output in Sourcetree

How do I check when a UITextField changes?

Swift 3.0.1+ (Some of the other swift 3.0 answers are not up to date)

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
                          for: UIControlEvents.editingChanged)

func textFieldDidChange(_ textField: UITextField) {

}

LINQ Contains Case Insensitive

Using C# 6.0 (which allows expression bodied functions and null propagation), for LINQ to Objects, it can be done in a single line like this (also checking for null):

public static bool ContainsInsensitive(this string str, string value) => str?.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0;

Declare an array in TypeScript

this is how you can create an array of boolean in TS and initialize it with false:

var array: boolean[] = [false, false, false]

or another approach can be:

var array2: Array<boolean> =[false, false, false] 

you can specify the type after the colon which in this case is boolean array

What characters do I need to escape in XML documents?

The accepted answer is not correct. Best is to use a library for escaping xml.

As mentioned in this other question

"Basically, the control characters and characters out of the Unicode ranges are not allowed. This means also that calling for example the character entity is forbidden."

If you only escape the five characters. You can have problems like An invalid XML character (Unicode: 0xc) was found

Jump into interface implementation in Eclipse IDE

Well... well... I hope you use Eclipse Helios, because what you asked is available on Helios.

Put your text cursor again on the method and click menu Navigate ? Open Implementation. Now if you have more than one implementation of the method, you will get choice to pick which implementation to open.

alt text

By defining a keybinding on Preferences ? General ? Keys you can even use the feature easier, but before you do that, see if this shortcut is fast enough for you.

Press Ctrl + click and hold. Now move your mouse over the same method. Tadam… you will get choice.

alt text

If you pick Open Implementation you’ll get the same choice as before.

How/when to generate Gradle wrapper files?

Generating the Gradle Wrapper

Project build gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

// Running 'gradle wrapper' will generate gradlew - Getting gradle wrapper working and using it will save you a lot of pain.
task wrapper(type: Wrapper) {
    gradleVersion = '2.2' 
}

// Look Google doesn't use Maven Central, they use jcenter now.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Then at the command-line run

gradle wrapper

If you're missing gradle on your system install it or the above won't work. On a Mac it is best to install via Homebrew.

brew install gradle

After you have successfully run the wrapper task and generated gradlew, don't use your system gradle. It will save you a lot of headaches.

./gradlew assemble

What about the gradle plugin seen above?

com.android.tools.build:gradle:1.0.1

You should set the version to be the latest and you can check the tools page and edit the version accordingly.

See what Android Studio generates

The addition of gradle and the newest Android Studio have changed project layout dramatically. If you have an older project I highly recommend creating a clean one with the latest Android Studio and see what Google considers the standard project.

Android Studio has facilities for importing older projects which can also help.

'^M' character at end of lines

The cause is the difference between how a Windows-based based OS and a Unix based OS store the end-of-line markers.

Windows based operating systems, thanks to their DOS heritage, store an end-of-line as a pair of characters - 0x0D0A (carriage return + line feed). Unix-based operating systems just use 0x0A (a line feed). The ^M you're seeing is a visual representation of 0x0D (a carriage return).

dos2unix will help with this. You probably also need to adjust the source of the scripts to be 'Unix-friendly'.

How to display gpg key details without importing it?

There are several detail levels you can get when looking at OpenPGP key data: a basic summary, a machine-readable output of this summary or a detailed (and very technical) list of the individual OpenPGP packets.

Basic Key Information

For a brief peak at an OpenPGP key file, you can simply pass the filename as parameter or pipe in the key data through STDIN. If no command is passed, GnuPG tries to guess what you want to do -- and for key data, this is printing a summary on the key:

$ gpg a4ff2279.asc
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub   rsa8192 2012-12-25 [SC]
      0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
uid           Jens Erat (born 1988-01-19 in Stuttgart, Germany)
uid           Jens Erat <[email protected]>
uid           Jens Erat <[email protected]>
uid           Jens Erat <[email protected]>
uid           Jens Erat <[email protected]>
uid           [jpeg image of size 12899]
sub   rsa4096 2012-12-26 [E] [revoked: 2014-03-26]
sub   rsa4096 2012-12-26 [S] [revoked: 2014-03-26]
sub   rsa2048 2013-01-23 [S] [expires: 2023-01-21]
sub   rsa2048 2013-01-23 [E] [expires: 2023-01-21]
sub   rsa4096 2014-03-26 [S] [expires: 2020-09-03]
sub   rsa4096 2014-03-26 [E] [expires: 2020-09-03]
sub   rsa4096 2014-11-22 [A] [revoked: 2016-03-01]
sub   rsa4096 2016-02-24 [A] [expires: 2020-02-23]

By setting --keyid-format 0xlong, long key IDs are printed instead of the insecure short key IDs:

$ gpg a4ff2279.asc                                                                 
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub   rsa8192/0x4E1F799AA4FF2279 2012-12-25 [SC]
      0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
uid                             Jens Erat (born 1988-01-19 in Stuttgart, Germany)
uid                             Jens Erat <[email protected]>
uid                             Jens Erat <[email protected]>
uid                             Jens Erat <[email protected]>
uid                             Jens Erat <[email protected]>
uid                             [jpeg image of size 12899]
sub   rsa4096/0x0F3ED8E6759A536E 2012-12-26 [E] [revoked: 2014-03-26]
sub   rsa4096/0x2D6761A7CC85941A 2012-12-26 [S] [revoked: 2014-03-26]
sub   rsa2048/0x9FF7E53ACB4BD3EE 2013-01-23 [S] [expires: 2023-01-21]
sub   rsa2048/0x5C88F5D83E2554DF 2013-01-23 [E] [expires: 2023-01-21]
sub   rsa4096/0x8E78E44DFB1B55E9 2014-03-26 [S] [expires: 2020-09-03]
sub   rsa4096/0xCC73B287A4388025 2014-03-26 [E] [expires: 2020-09-03]
sub   rsa4096/0x382D23D4C9773A5C 2014-11-22 [A] [revoked: 2016-03-01]
sub   rsa4096/0xFF37A70EDCBB4926 2016-02-24 [A] [expires: 2020-02-23]
pub   rsa1024/0x7F60B22EA4FF2279 2014-06-16 [SCEA] [revoked: 2016-08-16]

Providing -v or -vv will even add some more information. I prefer printing the package details in this case, though (see below).

Machine-Readable Output

GnuPG also has a colon-separated output format, which is easily parsable and has a stable format. The format is documented in GnuPG doc/DETAILS file. The option to receive this format is --with-colons.

$ gpg --with-colons a4ff2279.asc
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub:-:8192:1:4E1F799AA4FF2279:1356475387:::-:
uid:::::::::Jens Erat (born 1988-01-19 in Stuttgart, Germany):
uid:::::::::Jens Erat <[email protected]>:
uid:::::::::Jens Erat <[email protected]>:
uid:::::::::Jens Erat <[email protected]>:
uid:::::::::Jens Erat <[email protected]>:
uat:::::::::1 12921:
sub:-:4096:1:0F3ED8E6759A536E:1356517233:1482747633:::
sub:-:4096:1:2D6761A7CC85941A:1356517456:1482747856:::
sub:-:2048:1:9FF7E53ACB4BD3EE:1358985314:1674345314:::
sub:-:2048:1:5C88F5D83E2554DF:1358985467:1674345467:::
sub:-:4096:1:8E78E44DFB1B55E9:1395870592:1599164118:::
sub:-:4096:1:CC73B287A4388025:1395870720:1599164118:::
sub:-:4096:1:382D23D4C9773A5C:1416680427:1479752427:::
sub:-:4096:1:FF37A70EDCBB4926:1456322829:1582466829:::

Since GnuPG 2.1.23, the gpg: WARNING: no command supplied. Trying to guess what you mean ... warning can be omitted by using the --import-options show-only option together with the --import command (this also works without --with-colons, of course):

$ gpg --with-colons --import-options show-only --import a4ff2279
[snip]

For older versions: the warning message is printed on STDERR, so you could just read STDIN to split apart the key information from the warning.

Technical Details: Listing OpenPGP Packets

Without installing any further packages, you can use gpg --list-packets [file] to view information on the OpenPGP packets contained in the file.

$ gpg --list-packets a4ff2279.asc
:public key packet:
    version 4, algo 1, created 1356475387, expires 0
    pkey[0]: [8192 bits]
    pkey[1]: [17 bits]
    keyid: 4E1F799AA4FF2279
:user ID packet: "Jens Erat (born 1988-01-19 in Stuttgart, Germany)"
:signature packet: algo 1, keyid 4E1F799AA4FF2279
    version 4, created 1356516623, md5len 0, sigclass 0x13
    digest algo 2, begin of digest 18 46
    hashed subpkt 27 len 1 (key flags: 03)
[snip]

The pgpdump [file] tool works similar to gpg --list-packets and provides a similar output, but resolves all those algorithm identifiers to readable representations. It is available for probably all relevant distributions (on Debian derivatives, the package is called pgpdump like the tool itself).

$ pgpdump a4ff2279.asc
Old: Public Key Packet(tag 6)(1037 bytes)
    Ver 4 - new
    Public key creation time - Tue Dec 25 23:43:07 CET 2012
    Pub alg - RSA Encrypt or Sign(pub 1)
    RSA n(8192 bits) - ...
    RSA e(17 bits) - ...
Old: User ID Packet(tag 13)(49 bytes)
    User ID - Jens Erat (born 1988-01-19 in Stuttgart, Germany)
Old: Signature Packet(tag 2)(1083 bytes)
    Ver 4 - new
    Sig type - Positive certification of a User ID and Public Key packet(0x13).
    Pub alg - RSA Encrypt or Sign(pub 1)
    Hash alg - SHA1(hash 2)
    Hashed Sub: key flags(sub 27)(1 bytes)
[snip]

How can I throw CHECKED exceptions from inside Java 8 streams?

I wrote a library that extends the Stream API to allow you to throw checked exceptions. It uses Brian Goetz's trick.

Your code would become

public List<Class> getClasses() throws ClassNotFoundException {     
    Stream<String> classNames = 
        Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String");

    return ThrowingStream.of(classNames, ClassNotFoundException.class)
               .map(Class::forName)
               .collect(Collectors.toList());
}

How to host a Node.Js application in shared hosting

You can run node.js server on a typical shared hosting with Linux, Apache and PHP (LAMP). I have successfully installed it, even with NPM, Express and Grunt working fine. Follow the steps:

1) Create a new PHP file on the server with the following code and run it:

<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');

2) The same way install your node app, e.g. jt-js-sample, using npm:

<?php
exec('node/bin/npm install jt-js-sample');

3) Run the node app from PHP:

<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=49999 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:49999/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
    //If couldn't connect, try increasing usleep
    echo 'Error: ' . curl_error($curl);
} else {
    //Split response headers and body
    list($head, $body) = explode("\r\n\r\n", $resp, 2);
    $headarr = explode("\n", $head);
    //Print headers
    foreach($headarr as $headval) {
        header($headval);
    }
    //Print body
    echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);

Voila! Have a look at the demo of a node app on PHP shared hosting.

EDIT: I started a Node.php project on GitHub.

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

Automating the InvokeRequired code pattern

Here's the form I've been using in all my code.

private void DoGUISwitch()
{ 
    Invoke( ( MethodInvoker ) delegate {
        object1.Visible = true;
        object2.Visible = false;
    });
} 

I've based this on the blog entry here. I have not had this approach fail me, so I see no reason to complicate my code with a check of the InvokeRequired property.

Hope this helps.

Using HTTPS with REST in Java

Here's the painful route:

    SSLContext ctx = null;
    try {
        KeyStore trustStore;
        trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream("C:\\truststore_client"),
                "asdfgh".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance("SunX509");
        tmf.init(trustStore);
        ctx = SSLContext.getInstance("SSL");
        ctx.init(null, tmf.getTrustManagers(), null);
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    ClientConfig config = new DefaultClientConfig();
    config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
            new HTTPSProperties(null, ctx));

    WebResource service = Client.create(config).resource(
            "https://localhost:9999/");
    service.addFilter(new HTTPBasicAuthFilter(username, password));

    // Attempt to view the user's page.
    try {
        service.path("user/" + username).get(String.class);
    } catch (Exception e) {
        e.printStackTrace();
    }

Gotta love those six different caught exceptions :). There are certainly some refactoring to simplify the code a bit. But, I like delfuego's -D options on the VM. I wish there was a javax.net.ssl.trustStore static property that I could just set. Just two lines of code and done. Anyone know where that would be?

This may be too much to ask, but, ideally the keytool would not be used. Instead, the trustedStore would be created dynamically by the code and the cert is added at runtime.

There must be a better answer.

Bootstrap 3 breakpoints and media queries

Bootstrap does not document the media queries very well. Those variables of @screen-sm, @screen-md, @screen-lg are actually referring to LESS variables and not simple CSS.

When you customize Bootstrap you can change the media query breakpoints and when it compiles the @screen-xx variables are changed to whatever pixel width you defined as screen-xx. This is how a framework like this can be coded once and then customized by the end user to fit their needs.

A similar question on here that might provide more clarity: Bootstrap 3.0 Media queries

In your CSS, you will still have to use traditional media queries to override or add to what Bootstrap is doing.

In regards to your second question, that is not a typo. Once the screen goes below 768px the framework becomes completely fluid and resizes at any device width, removing the need for breakpoints. The breakpoint at 480px exists because there are specific changes that occur to the layout for mobile optimization.

To see this in action, go to this example on their site (http://getbootstrap.com/examples/navbar-fixed-top/), and resize your window to see how it treats the design after 768px.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

In my case, I was dealing with a file that was generated by hadoop on a linux box. When I tried to import to sql I had this issue. The fix wound up being to use the hex value for 'line feed' 0x0a. It also worked for bulk insert

bulk insert table from 'file' 
WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '0x0a')

Get the selected value in a dropdown using jQuery.

I have gone through all the answers provided above. This is the easiest way which I used to get the selected value from the drop down list

$('#searchType').val() // for the value

In Java, how do I call a base class's method from the overriding method in a derived class?

Just call it using super.

public void myMethod()
{
    // B stuff
    super.myMethod();
    // B stuff
}

Download JSON object as a file from browser

The download property of links is new and not is supported in Internet Explorer (see the compatibility table here). For a cross-browser solution to this problem I would take a look at FileSaver.js

Is there a JavaScript strcmp()?

What about

str1.localeCompare(str2)

How to fix date format in ASP .NET BoundField (DataFormatString)?

Formatting depends on the server's culture setting. If you use en-US culture, you can use Short Date Pattern like {0:d}

For example, it formats 6/15/2009 1:45:30 to 6/15/2009

You can check more formats from BoundField.DataFormatString

@import vs #import - iOS 7

There is a few benefits of using modules. You can use it only with Apple's framework unless module map is created. @import is a bit similar to pre-compiling headers files when added to .pch file which is a way to tune app the compilation process. Additionally you do not have to add libraries in the old way, using @import is much faster and efficient in fact. If you still look for a nice reference I will highly recommend you reading this article.

Rename Oracle Table or View

To rename a table you can use:

RENAME mytable TO othertable;

or

ALTER TABLE mytable RENAME TO othertable;

or, if owned by another schema:

ALTER TABLE owner.mytable RENAME TO othertable;

Interestingly, ALTER VIEW does not support renaming a view. You can, however:

RENAME myview TO otherview;

The RENAME command works for tables, views, sequences and private synonyms, for your own schema only.

If the view is not in your schema, you can recompile the view with the new name and then drop the old view.

(tested in Oracle 10g)

Repeat string to certain length

Not that there haven't been enough answers to this question, but there is a repeat function; just need to make a list of and then join the output:

from itertools import repeat

def rep(s,n):
  ''.join(list(repeat(s,n))

How to update a record using sequelize for node?

I have not used Sequelize, but after reading its documentation, it's obvious that you are instantiating a new object, that's why Sequelize inserts a new record into the db.

First you need to search for that record, fetch it and only after that change its properties and update it, for example:

Project.find({ where: { title: 'aProject' } })
  .on('success', function (project) {
    // Check if record exists in db
    if (project) {
      project.update({
        title: 'a very different title now'
      })
      .success(function () {})
    }
  })

Validate phone number with JavaScript

My regex of choice is:

/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im

Valid formats:

(123) 456-7890
(123)456-7890
123-456-7890
123.456.7890
1234567890
+31636363634
075-63546725

Is it possible to style a mouseover on an image map using CSS?

You could use Canvas

in HTML, simply add a canva

<canvas id="locations" width="400" height="300" style="border:1px solid #d3d3d3;">
Your browser can't read canvas</canvas>

And in Javascript (only an example, that will draw a rectangle on the picture)

var c = document.getElementById("locations");
var ctx = c.getContext("2d");
var img = new Image(); 
img.src = '{main_photo}';
img.onload = function() {    // after the pic is loaded
    ctx.drawImage(this,0,0); // add the picture
    ctx.beginPath();         // start the rectangle
    ctx.moveTo(50,50);
    ctx.lineTo(200,50);
    ctx.lineTo(200,200);
    ctx.lineTo(50,200);
    ctx.lineTo(50,50);

    ctx.strokeStyle = "sienna"; // set color
    ctx.stroke();               // apply color
    ctx.lineWidth = 5;
    // ctx.closePath();
};

Android Studio - No JVM Installation found

Ok, was having this issue as well and this is what fixed it for me. For the record I'm using Windows 8.1 and Java JDK 1.8.31, all 64-bit.

The problem is with the space between "Program" and "Files" in the path set in JAVA_HOME. I've had this problem before but didn't really realize until I was checking the instructions here for setting JAVA HOME, then it all made sense.

In a nutshell, change the JAVA_HOME path from:

C:\Program Files\Java\jdk1.8.0_31

to

C:\Progra~1\Java\jdk1.8.0_31

Make sure to set the correct JDK version number for your installation. Removing the space from the path fixed everything on my system.

As noted on the page linked above,

use C:\Progra~1\ for C:\Program Files\

and C:\Progra~2\ for C:\Program Files(x86)\

depending on where you have the JDK installed on your system.

Note: Just to be clear, before making this change my system correctly echoed the value of JAVA_HOME to be C:\Program Files\Java\jdk1.8.0_31 in the command window, leading me to believe all was well. However, attempting to run %JAVA_HOME%\bin\javac reported that the path could not be found. After removing the space from the JAVA_HOME path the same command runs perfectly.

How do you right-justify text in an HTML textbox?

Using inline styles:

<input type="text" style="text-align: right"/>

or, put it in a style sheet, like so:

<style>
   .rightJustified {
        text-align: right;
    }
</style>

and reference the class:

<input type="text" class="rightJustified"/>

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

This worked for me:

git reset HEAD <filename>

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

Select Replicate('0',2 - DataLength(Convert(VarChar(2),DatePart(DAY, GetDate()))) + Convert(VarChar(2),DatePart(DAY, GetDate())

Far neater, he says after removing tongue from cheek.

Usually when you have to start doing this sort of thing in SQL, you need switch from can I, to should I.

Check if cookies are enabled

You can make an Ajax Call (Note: This solution requires JQuery):

example.php

<?php
    setcookie('CookieEnabledTest', 'check', time()+3600);
?>

<script type="text/javascript">

    CookieCheck();

    function CookieCheck()
    {
        $.post
        (
            'ajax.php',
            {
                cmd: 'cookieCheck'
            },
            function (returned_data, status)
            {
                if (status === "success")
                {
                    if (returned_data === "enabled")
                    {
                        alert ("Cookies are activated.");
                    }
                    else
                    {
                        alert ("Cookies are not activated.");
                    }
                }
            }
        );
    }
</script>

ajax.php

$cmd = filter_input(INPUT_POST, "cmd");

if ( isset( $cmd ) && $cmd == "cookieCheck" )
{
    echo (isset($_COOKIE['CookieEnabledTest']) && $_COOKIE['CookieEnabledTest']=='check') ? 'enabled' : 'disabled';
}

As result an alert box appears which shows wheter cookies are enabled or not. Of course you don't have to show an alert box, from here you can take other steps to deal with deactivated cookies.

Cleanest way to reset forms

Angular Reactive Forms:

onCancel(): void {
  this.registrationForm.reset();
  this.registrationForm.controls['name'].setErrors(null);
  this.registrationForm.controls['email'].setErrors(null);
}

CSS: background-color only inside the margin

I needed something similar, and came up with using the :before (or :after) pseudoclasses:

#mydiv {
   background-color: #fbb;
   margin-top: 100px;
   position: relative;
}
#mydiv:before {
   content: "";
   background-color: #bfb;
   top: -100px;
   height: 100px;
   width: 100%;
   position: absolute;
}

JSFiddle

Return JsonResult from web api without its properties

As someone who has worked with ASP.NET API for about 3 years, I'd recommend returning an HttpResponseMessage instead. Don't use the ActionResult or IEnumerable!

ActionResult is bad because as you've discovered.

Return IEnumerable<> is bad because you may want to extend it later and add some headers, etc.

Using JsonResult is bad because you should allow your service to be extendable and support other response formats as well just in case in the future; if you seriously want to limit it you can do so using Action Attributes, not in the action body.

public HttpResponseMessage GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return Request.CreateResponse(HttpStatusCode.OK, result);
}

In my tests, I usually use the below helper method to extract my objects from the HttpResponseMessage:

 public class ResponseResultExtractor
    {
        public T Extract<T>(HttpResponseMessage response)
        {
            return response.Content.ReadAsAsync<T>().Result;
        }
    }

var actual = ResponseResultExtractor.Extract<List<ListItems>>(response);

In this way, you've achieved the below:

  • Your Action can also return Error Messages and status codes like 404 not found so in the above way you can easily handle it.
  • Your Action isn't limited to JSON only but supports JSON depending on the client's request preference and the settings in the Formatter.

Look at this: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation

Missing Authentication Token while accessing API Gateway?

Make sure you create Resource and then create method inside it. That was the issue for me. Thanks

enter image description here

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

sometimes when data grow bigger mysql WHERE IN's could be pretty slow because of query optimization. Try using STRAIGHT_JOIN to tell mysql to execute query as is, e.g.

SELECT STRAIGHT_JOIN table.field FROM table WHERE table.id IN (...)

but beware: in most cases mysql optimizer works pretty well, so I would recommend to use it only when you have this kind of problem

Two Divs next to each other, that then stack with responsive change

today this kind of thing can be done by using display:flex;

https://jsfiddle.net/suunyz3e/1435/

html:

  <div class="container flex-direction">
      <div class="div1">
        <span>Div One</span>
      </div>
      <div class="div2">
        <span>Div Two</span>
      </div>
  </div>

css:

.container{
  display:inline-flex;
  flex-wrap:wrap;
  border:1px solid black;
}
.flex-direction{
  flex-direction:row;
}
.div1{
  border-right:1px solid black;
  background-color:#727272;
  width:165px;
  height:132px;
}

.div2{
  background-color:#fff;
  width:314px;
  height:132px;
}

span{
  font-size:16px;
    font-weight:bold;
    display: block;
    line-height: 132px;
    text-align: center;
}

@media screen and (max-width: 500px) {
  .flex-direction{
  flex-direction:column;
  }
.div1{
  width:202px;
  height:131px;
  border-right:none;
  border-bottom:1px solid black;
  }
  .div2{
    width:202px;
    height:107px;
  }
  .div2 span{
    line-height:107px;
  }

}

How can I align text in columns using Console.WriteLine?

Just to add to roya's answer. In c# 6.0 you can now use string interpolation:

Console.WriteLine($"{customer[DisplayPos],10}" +
                  $"{salesFigures[DisplayPos],10}" +
                  $"{feePayable[DisplayPos],10}" +
                  $"{seventyPercentValue,10}" +
                  $"{thirtyPercentValue,10}");

This can actually be one line without all the extra dollars, I just think it makes it a bit easier to read like this.

And you could also use a static import on System.Console, allowing you to do this:

using static System.Console;

WriteLine(/* write stuff */);

Could not open a connection to your authentication agent

I resolved the error by force stopping (killed) git processes (ssh agent), then uninstalling Git, and then installing Git again.

Write a function that returns the longest palindrome in a given string

Reference: Wikipedia.com

The best algorithm i have ever found, with complexity O(N)

 import java.util.Arrays;

 public class ManachersAlgorithm {

  public static String findLongestPalindrome(String s) {
    if (s==null || s.length()==0)
      return "";

    char[] s2 = addBoundaries(s.toCharArray());
    int[] p = new int[s2.length]; 
    int c = 0, r = 0; // Here the first element in s2 has been processed.
    int m = 0, n = 0; // The walking indices to compare if two elements are the same
    for (int i = 1; i<s2.length; i++) {
      if (i>r) {
        p[i] = 0; m = i-1; n = i+1;
      } else {
        int i2 = c*2-i;
        if (p[i2]<(r-i)) {
          p[i] = p[i2];
          m = -1; // This signals bypassing the while loop below. 
        } else {
          p[i] = r-i;
          n = r+1; m = i*2-n;
        }
      }
      while (m>=0 && n<s2.length && s2[m]==s2[n]) {
        p[i]++; m--; n++;
      }
      if ((i+p[i])>r) {
        c = i; r = i+p[i];
      }
    }
    int len = 0; c = 0;
    for (int i = 1; i<s2.length; i++) {
      if (len<p[i]) {
        len = p[i]; c = i;
      }
    }
    char[] ss = Arrays.copyOfRange(s2, c-len, c+len+1);
    return String.valueOf(removeBoundaries(ss));
  }

  private static char[] addBoundaries(char[] cs) {
    if (cs==null || cs.length==0)
      return "||".toCharArray();

    char[] cs2 = new char[cs.length*2+1];
    for (int i = 0; i<(cs2.length-1); i = i+2) {
      cs2[i] = '|';
      cs2[i+1] = cs[i/2];
    }
    cs2[cs2.length-1] = '|';
    return cs2;
  }

  private static char[] removeBoundaries(char[] cs) {
    if (cs==null || cs.length<3)
      return "".toCharArray();

    char[] cs2 = new char[(cs.length-1)/2];
    for (int i = 0; i<cs2.length; i++) {
      cs2[i] = cs[i*2+1];
    }
    return cs2;
  }    
}

Swift Open Link in Safari

In Swift 1.2:

@IBAction func openLink {    
    let pth = "http://www.google.com"
    if let url = NSURL(string: pth){
        UIApplication.sharedApplication().openURL(url)
}

Cloning a private Github repo

Private clone URLs take the form [email protected]:username/repo.git - perhaps you needed to use git@ rather than git://?

git:// URLs are read only, and it looks like private repos do not allow this form of access.

How to use git merge --squash?

What finally cleared this up for me was a comment showing that:

git checkout main
git merge --squash feature

is the equivalent of doing:

git checkout feature
git diff main > feature.patch
git checkout main
patch -p1 < feature.patch
git add .

When I want to merge a feature branch with 105(!!) commits and have them all squashed into one, I don't want to git rebase -i origin/master because I need to separately resolve merge conflicts for each of the intermediate commits (or at least the ones which git can't figure out itself). Using git merge --squash gets me the result I want, of a single commit for merging an entire feature branch. And, I only need to do at most one manual conflict resolution.

how to get the value of a textarea in jquery?

in javascript :

document.getElementById("message").value

How Can I Remove “public/index.php” in the URL Generated Laravel?

HERE ARE SIMPLE STEPS TO REMOVE PUBLIC IN URL (Laravel 5)

1: Copy all files form public folder and past them in laravel root folder

2: Open index.php and change

From

 require __DIR__.'/../bootstrap/autoload.php';

To

 require __DIR__.'/bootstrap/autoload.php';

And

$app = require_once __DIR__.'/../bootstrap/app.php';

To

$app = require_once __DIR__.'/bootstrap/app.php';

In laravel 4 path 2 is $app = require_once __DIR__.'/bootstrap/start.php'; instead of $app = require_once __DIR__.'/bootstrap/app.php';/app.php

That is it.

SQL User Defined Function Within Select

Use a scalar-valued UDF, not a table-value one, then you can use it in a SELECT as you want.

Class method decorator with self arguments?

Another option would be to abandon the syntactic sugar and decorate in the __init__ of the class.

def countdown(number):
    def countdown_decorator(func):
        def func_wrapper():
            for index in reversed(range(1, number+1)):
                print(index)
            func()
        return func_wrapper
    return countdown_decorator

class MySuperClass():
    def __init__(self, number):
        self.number = number
        self.do_thing = countdown(number)(self.do_thing)
    
    def do_thing(self):
        print('im doing stuff!')


myclass = MySuperClass(3)

myclass.do_thing()

which would print

3
2
1
im doing stuff!

How can I access Google Sheet spreadsheets only with Javascript?

'JavaScript accessing Google Docs' would be tedious to implement and moreover Google documentation is also not that simple to get it. I have some good links to share by which you can achieve js access to gdoc:

http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs

http://code.google.com/apis/spreadsheets/gadgets/

http://code.google.com/apis/gdata/docs/js.html

http://www.mail-archive.com/[email protected]/msg01924.html

May be these would help you out..

JBoss default password

I can also verify the above solution except I had to change in

**..\server\<server profile>\conf\props\jmx-console-users.properties**

Conditionally change img src based on model data

<ul>
  <li ng-repeat=interface in interfaces>
       <img src='green-checkmark.png' ng-show="interface=='UP'" />
       <img src='big-black-X.png' ng-show="interface=='DOWN'" />
  </li>
</ul>

Detect home button press in android

Recently I was trying to detect the home press button, because I needed it to do the same as the method "onBackPressed()". In order to do this, I had to override the method "onSupportNavigateUp()" like this:

override fun onSupportNavigateUp(): Boolean {
    onBackPressed()
    return true
}

It worked perfectly. =)

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

Android Studio Gradle Configuration with name 'default' not found

Try adding Volley library and sync and run the program. if one has pulled and i has volley usage and the error shows as -Android Studio Gradle Configuration with name 'default' not found then follow the step of adding the volley library in your gradle. hope it helps. I cleared my problem this way.

How to import and use image in a Vue single file component?

As simple as:

<template>
    <div id="app">
        <img src="./assets/logo.png">
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style> 

Taken from the project generated by vue cli.

If you want to use your image as a module, do not forget to bind data to your Vuejs component:

<template>
    <div id="app">
        <img :src="image"/>
    </div>
</template>
    
<script>
    import image from "./assets/logo.png"
    
    export default {
        data: function () {
            return {
                image: image
            }
        }
    }
</script>
    
<style lang="css">
</style>

And a shorter version:

<template>
    <div id="app">
        <img :src="require('./assets/logo.png')"/>
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style> 

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Sometimes the problem is in the composer memory limit. In my case, I tried increasing the php memory limit but still got the error. You can use COMPOSER_MEMORY_LIMIT=-1 to get around that. Use it as a prefix:

COMPOSER_MEMORY_LIMIT=-1 composer require the/library

You have to prefix it again in the future.

Hope this helps.

How to encrypt and decrypt file in Android?

I had a similar problem and for encrypt/decrypt i came up with this solution:

public static byte[] generateKey(String password) throws Exception
{
    byte[] keyStart = password.getBytes("UTF-8");

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    sr.setSeed(keyStart);
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    return skey.getEncoded();
}

public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
{

    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(fileData);

    return encrypted;
}

public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
{
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);

    byte[] decrypted = cipher.doFinal(fileData);

    return decrypted;
}

To save a encrypted file to sd do:

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();

To decode a file use:

byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);

For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/

Double value to round up in Java

If you do not want to use DecimalFormat (e.g. due to its efficiency) and you want a general solution, you could also try this method that uses scaled rounding:

public static double roundToDigits(double value, int digitCount) {
    if (digitCount < 0)
        throw new IllegalArgumentException("Digit count must be positive for rounding!");

    double factor = Math.pow(10, digitCount);
    return (double)(Math.round(value * factor)) / factor;
}

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

How to attach a file using mail command on Linux?

mail on every version of modern Linux that I've tried can do it. No need for other software:

matiu@matiu-laptop:~$ mail -a doc.jpg [email protected]
Subject: testing

This is a test
EOT

ctrl+d when you're done typing.

Convert a list to a string in C#

Maybe you are trying to do

string combindedString = string.Join( ",", myList.ToArray() );

You can replace "," with what you want to split the elements in the list by.

Edit: As mention in the comments you could also do

string combindedString = string.Join( ",", myList);

Reference:

Join<T>(String, IEnumerable<T>) 
Concatenates the members of a collection, using the specified separator between each member.

How to check if ping responded or not in a batch file

The question was to see if ping responded which this script does.

However this will not work if you get the Host Unreachable message as this returns ERRORLEVEL 0 and passes the check for Received = 1 used in this script, returning Link is UP from the script. Host Unreachable occurs when ping was delivered to target notwork but remote host cannot be found.

If I recall the correct way to check if ping was successful is to look for the string 'TTL' using Find.

@echo off
cls
set ip=%1
ping -n 1 %ip% | find "TTL"
if not errorlevel 1 set error=win
if errorlevel 1 set error=fail
cls
echo Result: %error%

This wont work with IPv6 networks because ping will not list TTL when receiving reply from IPv6 address.

How to convert PDF files to images

I used PDFiumSharp and ImageSharp in a .NET Standard 2.1 class library.

/// <summary>
/// Saves a thumbnail (jpg) to the same folder as the PDF file, using dimensions 300x423,
/// which corresponds to the aspect ratio of 'A' paper sizes like A4 (ratio h/w=sqrt(2))
/// </summary>
/// <param name="pdfPath">Source path of the pdf file.</param>
/// <param name="thumbnailPath">Target path of the thumbnail file.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void SaveThumbnail(string pdfPath, string thumbnailPath = "", int width = 300, int height = 423)
{
    using var pdfDocument = new PdfDocument(pdfPath);
    var firstPage = pdfDocument.Pages[0];

    using var pageBitmap = new PDFiumBitmap(width, height, true);

    firstPage.Render(pageBitmap);

    var imageJpgPath = string.IsNullOrWhiteSpace(thumbnailPath)
        ? Path.ChangeExtension(pdfPath, "jpg")
        : thumbnailPath;
    var image = Image.Load(pageBitmap.AsBmpStream());

    // Set the background to white, otherwise it's black. https://github.com/SixLabors/ImageSharp/issues/355#issuecomment-333133991
    image.Mutate(x => x.BackgroundColor(Rgba32.White));

    image.Save(imageJpgPath, new JpegEncoder());
}

Generating unique random numbers (integers) between 0 and 'x'

function generateRange(pCount, pMin, pMax) {
    min = pMin < pMax ? pMin : pMax;
    max = pMax > pMin ? pMax : pMin;
    var resultArr = [], randNumber;
    while ( pCount > 0) {
        randNumber = Math.round(min + Math.random() * (max - min));
        if (resultArr.indexOf(randNumber) == -1) {
            resultArr.push(randNumber);
            pCount--;
        }
    }
    return resultArr;
}

Depending on range needed the method of returning the integer can be changed to: ceil (a,b], round [a,b], floor [a,b), for (a,b) is matter of adding 1 to min with floor.

Oracle SELECT TOP 10 records

You'll need to put your current query in subquery as below :

SELECT * FROM (
  SELECT DISTINCT 
  APP_ID, 
  NAME, 
  STORAGE_GB, 
  HISTORY_CREATED, 
  TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE  
  FROM HISTORY WHERE 
    STORAGE_GB IS NOT NULL AND 
      APP_ID NOT IN (SELECT APP_ID FROM HISTORY WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') ='06.02.2009')
  ORDER BY STORAGE_GB DESC )
WHERE ROWNUM <= 10

Oracle applies rownum to the result after it has been returned.
You need to filter the result after it has been returned, so a subquery is required. You can also use RANK() function to get Top-N results.

For performance try using NOT EXISTS in place of NOT IN. See this for more.

How to cancel a local git commit

You can tell Git what to do with your index (set of files that will become the next commit) and working directory when performing git reset by using one of the parameters:

--soft: Only commits will be reseted, while Index and the working directory are not altered.

--mixed: This will reset the index to match the HEAD, while working directory will not be touched. All the changes will stay in the working directory and appear as modified.

--hard: It resets everything (commits, index, working directory) to match the HEAD.

In your case, I would use git reset --soft to keep your modified changes in Index and working directory. Be sure to check this out for a more detailed explanation.

Beginner Python Practice?

I always find it easier to learn a language in a specific problem domain. You might try looking at Django and doing the tutorial. This will give you a very light-weight intro to both Python and to a web framework (a very well-documented one) that is 100% Python.

Then do something in your field(s) of expertise -- graph generation, or whatever -- and tie that into a working framework to see if you got it right. My universe tends to be computational linguistics and there are a number of Python-based toolkits to help get you started. E.g. Natural Language Toolkit.

Just a thought.

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

So the simplest way is,

alter table table_name change column_name column_name int(11) NULL;

How to Load an Assembly to AppDomain with all references recursively?

Once you pass the assembly instance back to the caller domain, the caller domain will try to load it! This is why you get the exception. This happens in your last line of code:

domain.Load(AssemblyName.GetAssemblyName(path));

Thus, whatever you want to do with the assembly, should be done in a proxy class - a class which inherit MarshalByRefObject.

Take in count that the caller domain and the new created domain should both have access to the proxy class assembly. If your issue is not too complicated, consider leaving the ApplicationBase folder unchanged, so it will be same as the caller domain folder (the new domain will only load Assemblies it needs).

In simple code:

public void DoStuffInOtherDomain()
{
    const string assemblyPath = @"[AsmPath]";
    var newDomain = AppDomain.CreateDomain("newDomain");
    var asmLoaderProxy = (ProxyDomain)newDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(ProxyDomain).FullName);

    asmLoaderProxy.GetAssembly(assemblyPath);
}

class ProxyDomain : MarshalByRefObject
{
    public void GetAssembly(string AssemblyPath)
    {
        try
        {
            Assembly.LoadFrom(AssemblyPath);
            //If you want to do anything further to that assembly, you need to do it here.
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException(ex.Message, ex);
        }
    }
}

If you do need to load the assemblies from a folder which is different than you current app domain folder, create the new app domain with specific dlls search path folder.

For example, the app domain creation line from the above code should be replaced with:

var dllsSearchPath = @"[dlls search path for new app domain]";
AppDomain newDomain = AppDomain.CreateDomain("newDomain", new Evidence(), dllsSearchPath, "", true);

This way, all the dlls will automaically be resolved from dllsSearchPath.

Detecting real time window size changes in Angular 4

To get it on init

public innerWidth: any;
ngOnInit() {
    this.innerWidth = window.innerWidth;
}

If you wanna keep it updated on resize:

@HostListener('window:resize', ['$event'])
onResize(event) {
  this.innerWidth = window.innerWidth;
}

How to pause for specific amount of time? (Excel/VBA)

Use the Wait method:

Application.Wait Now + #0:00:01#

or (for Excel 2010 and later):

Application.Wait Now + #12:00:01 AM#

Using ng-if as a switch inside ng-repeat?

Try to surround strings (hoot, story, article) with quotes ':

<div ng-repeat = "data in comments">
    <div ng-if="data.type == 'hoot' ">
        //different template with hoot data
    </div>
    <div ng-if="data.type == 'story' ">
        //different template with story data
    </div>
    <div ng-if="data.type == 'article' ">
        //different template with article data
    </div> 
</div>

Add animated Gif image in Iphone UIImageView

With Swift and KingFisher

   lazy var animatedPart: AnimatedImageView = {
        let img = AnimatedImageView()
        if let src = Bundle.main.url(forResource: "xx", withExtension: "gif"){
            img.kf.setImage(with: src)
        }
        return img
   }()

Android Studio is slow (how to speed up)?

I detected another reason - Thumbs.db, which affected performance badly.

Go to File > Settings > Editor > File Types and in field Ignore files and folders add this: Thumbs.db;

Now, Android Studio runs like a charm.

jQuery append() and remove() element

You can call a reset function before appending. Something like this:

    function resetNewReviewBoardForm() {
    $("#Description").val('');
    $("#PersonName").text('');
    $("#members").empty(); //this one what worked in my case
    $("#EmailNotification").val('False');
}

jQuery checkbox event handling

I have try the code from first answer, it not working but I have play around and this work for me

$('#vip').change(function(){
    if ($(this).is(':checked')) {
        alert('checked');
    } else {
        alert('uncheck');
    }
});

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

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

see 15.22.2 of the JLS. For boolean operands, the & operator is boolean, not bitwise. The only difference between && and & for boolean operands is that for && it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).

So in your case, if b is a primitive, a = a && b, a = a & b, and a &= b all do the same thing.

What are the integrity and crossorigin attributes?

Technically, the Integrity attribute helps with just that - it enables the proper verification of the data source. That is, it merely allows the browser to verify the numbers in the right source file with the amounts requested by the source file located on the CDN server.

Going a bit deeper, in case of the established encrypted hash value of this source and its checked compliance with a predefined value in the browser - the code executes, and the user request is successfully processed.

Crossorigin attribute helps developers optimize the rates of CDN performance, at the same time, protecting the website code from malicious scripts.

In particular, Crossorigin downloads the program code of the site in anonymous mode, without downloading cookies or performing the authentication procedure. This way, it prevents the leak of user data when you first load the site on a specific CDN server, which network fraudsters can easily replace addresses.

Source: https://yon.fun/what-is-link-integrity-and-crossorigin/

Xcode: failed to get the task for process

I switched back to "Automatic" on the build settings provisioning profile for "Debug" and left the release certificate profile unchanged, mine worked. Tried the other answers. nothing worked. Didn't want to have to reconfigure my certificates. Automatic on the provisioning profile did the trick

screenshot

Path of currently executing powershell script

Split-Path $MyInvocation.MyCommand.Path -Parent

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

In PHP, what is a closure and why does it use the "use" identifier?

Until very recent years, PHP has defined its AST and PHP interpreter has isolated the parser from the evaluation part. During the time when the closure is introduced, PHP's parser is highly coupled with the evaluation.

Therefore when the closure was firstly introduced to PHP, the interpreter has no method to know which which variables will be used in the closure, because it is not parsed yet. So user has to pleased the zend engine by explicit import, doing the homework that zend should do.

This is the so-called simple way in PHP.

How to execute only one test spec with angular-cli

You can test only specific file with the Angular CLI (the ng command) like this:

ng test --main ./path/to/test.ts

Further docs are at https://angular.io/cli/test

Note that while this works for standalone library files, it will not work for angular components/services/etc. This is because angular files have dependencies on other files (namely src/test.ts in Angular 7). Sadly the --main flag doesn't take multiple arguments.

curl posting with header application/x-www-form-urlencoded

 $curl = curl_init();
 curl_setopt_array($curl, array(
            CURLOPT_URL => "http://example.com",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "value1=111&value2=222",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded"
            ),
        ));
 $response = curl_exec($curl);
 $err = curl_error($curl);

 curl_close($curl);

 if (!$err)
 {
      var_dump($response);
 }

What does Maven do, in theory and in practice? When is it worth to use it?

Maven is a build tool. Along with Ant or Gradle are Javas tools for building.
If you are a newbie in Java though just build using your IDE since Maven has a steep learning curve.

Change Placeholder Text using jQuery

simply you can use

$("#yourtextboxid").attr("placeholder", "variable");

where, if variable is string then you can use like above, if it is variable replace it with the name like "variable" with out double quotes.

eg: $("#youtextboxid").attr("placeholder", variable); it will work.

What is REST? Slightly confused

REST is a software design pattern typically used for web applications. In layman's terms this means that it is a commonly used idea used in many different projects. It stands for REpresentational State Transfer. The basic idea of REST is treating objects on the server-side (as in rows in a database table) as resources than can be created or destroyed.

The most basic way of thinking about REST is as a way of formatting the URLs of your web applications. For example, if your resource was called "posts", then:

/posts Would be how a user would access ALL the posts, for displaying.

/posts/:id Would be how a user would access and view an individual post, retrieved based on their unique id.

/posts/new Would be how you would display a form for creating a new post.

Sending a POST request to /users would be how you would actually create a new post on the database level.

Sending a PUT request to /users/:id would be how you would update the attributes of a given post, again identified by a unique id.

Sending a DELETE request to /users/:id would be how you would delete a given post, again identified by a unique id.

As I understand it, the REST pattern was mainly popularized (for web apps) by the Ruby on Rails framework, which puts a big emphasis on RESTful routes. I could be wrong about that though.

I may not be the most qualified to talk about it, but this is how I've learned it (specifically for Rails development).

When someone refers to a "REST api," generally what they mean is an api that uses RESTful urls for retrieving data.

how to show calendar on text box click in html

try to use jquery-ui

<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>

<script>   
    $(function() {
         $( "#calendar" ).datepicker();   
    }); 
</script>

<p>Calendar: <input type="text" id="calendar" /></p>

more

How to set up a PostgreSQL database in Django

This is one of the very good and step by step process to set up PostgreSQL in ubuntu server. I have tried it with Ubuntu 16.04 and its working.

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04

Define variable to use with IN operator (T-SQL)

This one uses PATINDEX to match ids from a table to a non-digit delimited integer list.

-- Given a string @myList containing character delimited integers 
-- (supports any non digit delimiter)
DECLARE @myList VARCHAR(MAX) = '1,2,3,4,42'

SELECT * FROM [MyTable]
    WHERE 
        -- When the Id is at the leftmost position 
        -- (nothing to its left and anything to its right after a non digit char) 
        PATINDEX(CAST([Id] AS VARCHAR)+'[^0-9]%', @myList)>0 
        OR
        -- When the Id is at the rightmost position
        -- (anything to its left before a non digit char and nothing to its right) 
        PATINDEX('%[^0-9]'+CAST([Id] AS VARCHAR), @myList)>0
        OR
        -- When the Id is between two delimiters 
        -- (anything to its left and right after two non digit chars)
        PATINDEX('%[^0-9]'+CAST([Id] AS VARCHAR)+'[^0-9]%', @myList)>0
        OR
        -- When the Id is equal to the list
        -- (if there is only one Id in the list)
        CAST([Id] AS VARCHAR)=@myList

Notes:

  • when casting as varchar and not specifying byte size in parentheses the default length is 30
  • % (wildcard) will match any string of zero or more characters
  • ^ (wildcard) not to match
  • [^0-9] will match any non digit character
  • PATINDEX is an SQL standard function that returns the position of a pattern in a string

Increase days to php current Date()

a day is 86400 seconds.

$tomorrow = date('y:m:d', time() + 86400);

Concatenating strings in C, which method is more efficient?

sprintf() is designed to handle far more than just strings, strcat() is specialist. But I suspect that you are sweating the small stuff. C strings are fundamentally inefficient in ways that make the differences between these two proposed methods insignificant. Read "Back to Basics" by Joel Spolsky for the gory details.

This is an instance where C++ generally performs better than C. For heavy weight string handling using std::string is likely to be more efficient and certainly safer.

[edit]

[2nd edit]Corrected code (too many iterations in C string implementation), timings, and conclusion change accordingly

I was surprised at Andrew Bainbridge's comment that std::string was slower, but he did not post complete code for this test case. I modified his (automating the timing) and added a std::string test. The test was on VC++ 2008 (native code) with default "Release" options (i.e. optimised), Athlon dual core, 2.6GHz. Results:

C string handling = 0.023000 seconds
sprintf           = 0.313000 seconds
std::string       = 0.500000 seconds

So here strcat() is faster by far (your milage may vary depending on compiler and options), despite the inherent inefficiency of the C string convention, and supports my original suggestion that sprintf() carries a lot of baggage not required for this purpose. It remains by far the least readable and safe however, so when performance is not critical, has little merit IMO.

I also tested a std::stringstream implementation, which was far slower again, but for complex string formatting still has merit.

Corrected code follows:

#include <ctime>
#include <cstdio>
#include <cstring>
#include <string>

void a(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000; i++)
    {
        strcpy(both, first);
        strcat(both, " ");
        strcat(both, second);
    }
}

void b(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000; i++)
        sprintf(both, "%s %s", first, second);
}

void c(char *first, char *second, char *both)
{
    std::string first_s(first) ;
    std::string second_s(second) ;
    std::string both_s(second) ;

    for (int i = 0; i != 1000000; i++)
        both_s = first_s + " " + second_s ;
}

int main(void)
{
    char* first= "First";
    char* second = "Second";
    char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char));
    clock_t start ;

    start = clock() ;
    a(first, second, both);
    printf( "C string handling = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    start = clock() ;
    b(first, second, both);
    printf( "sprintf           = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    start = clock() ;
    c(first, second, both);
    printf( "std::string       = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    return 0;
}

Make Axios send cookies in its requests automatically

So I had this exact same issue and lost about 6 hours of my life searching, I had the

withCredentials: true

But the browser still didn't save the cookie until for some weird reason I had the idea to shuffle the configuration setting:

Axios.post(GlobalVariables.API_URL + 'api/login', {
        email,
        password,
        honeyPot
    }, {
        withCredentials: true,
        headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
    }});

Seems like you should always send the 'withCredentials' Key first.

Is there a way to get rid of accents and convert a whole string to regular letters?

Use java.text.Normalizer to handle this for you.

string = Normalizer.normalize(string, Normalizer.Form.NFD);
// or Normalizer.Form.NFKD for a more "compatable" deconstruction 

This will separate all of the accent marks from the characters. Then, you just need to compare each character against being a letter and throw out the ones that aren't.

string = string.replaceAll("[^\\p{ASCII}]", "");

If your text is in unicode, you should use this instead:

string = string.replaceAll("\\p{M}", "");

For unicode, \\P{M} matches the base glyph and \\p{M} (lowercase) matches each accent.

Thanks to GarretWilson for the pointer and regular-expressions.info for the great unicode guide.

How do I extract data from a DataTable?

The simplest way to extract data from a DataTable when you have multiple data types (not just strings) is to use the Field<T> extension method available in the System.Data.DataSetExtensions assembly.

var id = row.Field<int>("ID");         // extract and parse int
var name = row.Field<string>("Name");  // extract string

From MSDN, the Field<T> method:

Provides strongly-typed access to each of the column values in the DataRow.

This means that when you specify the type it will validate and unbox the object.

For example:

// iterate over the rows of the datatable
foreach (var row in table.AsEnumerable())  // AsEnumerable() returns IEnumerable<DataRow>
{
    var id = row.Field<int>("ID");                           // int
    var name = row.Field<string>("Name");                    // string
    var orderValue = row.Field<decimal>("OrderValue");       // decimal
    var interestRate = row.Field<double>("InterestRate");    // double
    var isActive = row.Field<bool>("Active");                // bool
    var orderDate = row.Field<DateTime>("OrderDate");        // DateTime
}

It also supports nullable types:

DateTime? date = row.Field<DateTime?>("DateColumn");

This can simplify extracting data from DataTable as it removes the need to explicitly convert or parse the object into the correct types.

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

How to redirect to the same page in PHP

My preferred method for reloading the same page is $_SERVER['PHP_SELF']

header('Location: '.$_SERVER['PHP_SELF']);
die;

Don't forget to die or exit after your header();

Edit: (Thanks @RafaelBarros )

If the query string is also necessary, use

header('Location:'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
die;

Edit: (thanks @HugoDelsing)

When htaccess url manipulation is in play the value of $_SERVER['PHP_SELF'] may take you to the wrong place. In that case the correct url data will be in $_SERVER['REQUEST_URI'] for your redirect, which can look like Nabil's answer below:

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

You can also use $_SERVER[REQUEST_URI] to assign the correct value to $_SERVER['PHP_SELF'] if desired. This can help if you use a redirect function heavily and you don't want to change it. Just set the correct vale in your request handler like this:

$_SERVER['PHP_SELF'] = 'https://sample.com/controller/etc';

Does PHP have threading?

In short: yes, there is multithreading in php but you should use multiprocessing instead.

Backgroud info: threads vs. processes

There is always a bit confusion about the distinction of threads and processes, so i'll shortly describe both:

  • A thread is a sequence of commands that the CPU will process. The only data it consists of is a program counter. Each CPU core will only process one thread at a time but can switch between the execution of different ones via scheduling.
  • A process is a set of shared resources. That means it consists of a part of memory, variables, object instances, file handles, mutexes, database connections and so on. Each process also contains one or more threads. All threads of the same process share its resources, so you may use a variable in one thread that you created in another. If those threads are parts of two different processes, then they cannot access each others resources directly. In this case you need inter-process communication through e.g. pipes, files, sockets...

Multiprocessing

You can achieve parallel computing by creating new processes (that also contain a new thread) with php. If your threads do not need much communication or synchronization, this is your choice, since the processes are isolated and cannot interfere with each other's work. Even if one crashes, that doesn't concern the others. If you do need much communication, you should read on at "multithreading" or - sadly - consider using another programming language, because inter-process communication and synchronization introduces a lot of complexion.

In php you have two ways to create a new process:

let the OS do it for you: you can tell your operation system to create a new process and run a new (or the same) php script in it.

  • for linux you can use the following or consider Darryl Hein's answer:

    $cmd = 'nice php script.php 2>&1 & echo $!';
    pclose(popen($cmd, 'r'));
    
  • for windows you may use this:

    $cmd = 'start "processname" /MIN /belownormal cmd /c "script.php 2>&1"';
    pclose(popen($cmd, 'r'));
    

do it yourself with a fork: php also provides the possibility to use forking through the function pcntl_fork(). A good tutorial on how to do this can be found here but i strongly recommend not to use it, since fork is a crime against humanity and especially against oop.

Multithreading

With multithreading all your threads share their resources so you can easily communicate between and synchronize them without a lot of overhead. On the other side you have to know what you are doing, since race conditions and deadlocks are easy to produce but very difficult to debug.

Standard php does not provide any multithreading but there is an (experimental) extension that actually does - pthreads. Its api documentation even made it into php.net. With it you can do some stuff as you can in real programming languages :-) like this:

class MyThread extends Thread {
    public function run(){
        //do something time consuming
    }
}

$t = new MyThread();
if($t->start()){
    while($t->isRunning()){
        echo ".";
        usleep(100);
    }
    $t->join();
}

For linux there is an installation guide right here at stackoverflow's.

For windows there is one now:

  • First you need the thread-safe version of php.
  • You need the pre-compiled versions of both pthreads and its php extension. They can be downloaded here. Make sure that you download the version that is compatible with your php version.
  • Copy php_pthreads.dll (from the zip you just downloaded) into your php extension folder ([phpDirectory]/ext).
  • Copy pthreadVC2.dll into [phpDirectory] (the root folder - not the extension folder).
  • Edit [phpDirectory]/php.ini and insert the following line

    extension=php_pthreads.dll
    
  • Test it with the script above with some sleep or something right there where the comment is.

And now the big BUT: Although this really works, php wasn't originally made for multithreading. There exists a thread-safe version of php and as of v5.4 it seems to be nearly bug-free but using php in a multi-threaded environment is still discouraged in the php manual (but maybe they just did not update their manual on this, yet). A much bigger problem might be that a lot of common extensions are not thread-safe. So you might get threads with this php extension but the functions you're depending on are still not thread-safe so you will probably encounter race conditions, deadlocks and so on in code you did not write yourself...

How to set the title text color of UIButton?

This is swift 5 compatible answer. If you want to use one of the built-in colours then you can simply use

button.setTitleColor(.red, for: .normal)

If you want some custom colours, then create an extension for a UIColor as below first.

import UIKit
extension UIColor {
    static var themeMoreButton = UIColor.init(red: 53/255, green: 150/255, blue: 36/255, alpha: 1)
}

Then use it for your button as below.

button.setTitleColor(UIColor.themeMoreButton, for: .normal)

Tip: You can use this method to store custom colours from rgba colour code and reuse it throughout your application.

Angular, Http GET with parameter?

Above solutions not helped me, but I resolve same issue by next way

private setHeaders(params) {      
        const accessToken = this.localStorageService.get('token');
        const reqData = {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
        };
        if(params) {
            let reqParams = {};        
            Object.keys(params).map(k =>{
                reqParams[k] = params[k];
            });
            reqData['params'] = reqParams;
        }
        return reqData;
    }

and send request

this.http.get(this.getUrl(url), this.setHeaders(params))

Its work with NestJS backend, with other I don't know.

How to check for valid email address?

Email addresses are not as simple as they seem! For example, Bob_O'[email protected], is a valid email address.

I've had some luck with the lepl package (http://www.acooke.org/lepl/). It can validate email addresses as indicated in RFC 3696: http://www.faqs.org/rfcs/rfc3696.html

Found some old code:

import lepl.apps.rfc3696
email_validator = lepl.apps.rfc3696.Email()
if not email_validator("[email protected]"):
    print "Invalid email"

How to convert file to base64 in JavaScript?

Modern ES6 way (async/await)

const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
});

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   console.log(await toBase64(file));
}

Main();

UPD:

If you want to catch errors

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   const result = await toBase64(file).catch(e => Error(e));
   if(result instanceof Error) {
      console.log('Error: ', result.message);
      return;
   }
   //...
}

How to empty the content of a div

This method works best to me:

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}

To use it we can deploy like this:

document.getElementsByID('DIV_Id').remove();

or

document.getElementsByClassName('DIV_Class').remove();

What could cause java.lang.reflect.InvocationTargetException?

From the Javadoc of Method.invoke()

Throws: InvocationTargetException - if the underlying method throws an exception.

This exception is thrown if the method called threw an exception.

What is the equivalent of Select Case in Access SQL?

You can use IIF for a similar result.

Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html

SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer 
FROM MyTable;

Cursor inside cursor

You have a variety of problems. First, why are you using your specific @@FETCH_STATUS values? It should just be @@FETCH_STATUS = 0.

Second, you are not selecting your inner Cursor into anything. And I cannot think of any circumstance where you would select all fields in this way - spell them out!

Here's a sample to go by. Folder has a primary key of "ClientID" that is also a foreign key for Attend. I'm just printing all of the Attend UIDs, broken down by Folder ClientID:

Declare @ClientID int;
Declare @UID int;

DECLARE Cur1 CURSOR FOR
    SELECT ClientID From Folder;

OPEN Cur1
FETCH NEXT FROM Cur1 INTO @ClientID;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Processing ClientID: ' + Cast(@ClientID as Varchar);
    DECLARE Cur2 CURSOR FOR
        SELECT UID FROM Attend Where ClientID=@ClientID;
    OPEN Cur2;
    FETCH NEXT FROM Cur2 INTO @UID;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Found UID: ' + Cast(@UID as Varchar);
        FETCH NEXT FROM Cur2 INTO @UID;
    END;
    CLOSE Cur2;
    DEALLOCATE Cur2;
    FETCH NEXT FROM Cur1 INTO @ClientID;
END;
PRINT 'DONE';
CLOSE Cur1;
DEALLOCATE Cur1;

Finally, are you SURE you want to be doing something like this in a stored procedure? It is very easy to abuse stored procedures and often reflects problems in characterizing your problem. The sample I gave, for example, could be far more easily accomplished using standard select calls.

How to convert an ASCII character into an int in C

As everyone else told you, you can convert it directly... UNLESS you meant something like "how can I convert an ASCII Extended character to its UTF-16 or UTF-32 value". This is a TOTALLY different question (one at least as good). And one quite difficult, if I remember correctly, if you are using only "pure" C. Then you could start here: https://stackoverflow.com/questions/114611/what-is-the-best-unicode-library-for-c/114643#114643

(for ASCII Extended I mean one of the many "extensions" to the ASCII set. The 0-127 characters of the base ASCII set are directly convertible to Unicode, while the 128-255 are not.). For example ISO_8859-1 http://en.wikipedia.org/wiki/ISO_8859-1 is an 8 bit extensions to the 7 bit ASCII set, or the (quite famous) codepages 437 and 850.

Lowercase and Uppercase with jQuery

Try this:

var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();

Possible duplicate with: How do I use jQuery to ignore case when selecting

use current date as default value for a column

Add a default constraint with the GETDATE() function as value.

ALTER TABLE myTable 
  ADD CONSTRAINT CONSTRAINT_NAME
    DEFAULT GETDATE() FOR myColumn

Text overflow ellipsis on two lines

It seems more elegant combining two classes. You can drop two-lines class if only one row need see:

_x000D_
_x000D_
.ellipse {_x000D_
          white-space: nowrap;_x000D_
          display:inline-block;_x000D_
          overflow: hidden;_x000D_
          text-overflow: ellipsis;_x000D_
       }_x000D_
      .two-lines {_x000D_
          -webkit-line-clamp: 2;_x000D_
          display: -webkit-box;_x000D_
          -webkit-box-orient: vertical;_x000D_
          white-space: normal;_x000D_
      }_x000D_
      .width{_x000D_
          width:100px;_x000D_
          border:1px solid hotpink;_x000D_
      }
_x000D_
        <span class='width ellipse'>_x000D_
          some texts some texts some texts some texts some texts some texts some texts_x000D_
       </span>_x000D_
_x000D_
       <span class='width ellipse two-lines'>_x000D_
          some texts some texts some texts some texts some texts some texts some texts_x000D_
       </span>
_x000D_
_x000D_
_x000D_

How to deep copy a list?

If your list elements are immutable objects then you can use this, otherwise you have to use deepcopy from copy module.

you can also use shortest way for deep copy a list like this.

a = [0,1,2,3,4,5,6,7,8,9,10]
b = a[:] #deep copying the list a and assigning it to b
print id(a)
20983280
print id(b)
12967208

a[2] = 20
print a
[0, 1, 20, 3, 4, 5, 6, 7, 8, 9,10]
print b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10]

Python loop that also accesses previous and next values

Using generators, it is quite simple:

signal = ['?Signal value?']
def pniter( iter, signal=signal ):
    iA = iB = signal
    for iC in iter:
        if iB is signal:
            iB = iC
            continue
        else:
            yield iA, iB, iC
        iA = iB
        iB = iC
    iC = signal
    yield iA, iB, iC

if __name__ == '__main__':
    print('test 1:')
    for a, b, c in pniter( range( 10 )):
        print( a, b, c )
    print('\ntest 2:')
    for a, b, c in pniter([ 20, 30, 40, 50, 60, 70, 80 ]):
        print( a, b, c )
    print('\ntest 3:')
    cam = { 1: 30, 2: 40, 10: 9, -5: 36 }
    for a, b, c in pniter( cam ):
        print( a, b, c )
    for a, b, c in pniter( cam ):
        print( a, a if a is signal else cam[ a ], b, b if b is signal else cam[ b ], c, c if c is signal else cam[ c ])
    print('\ntest 4:')
    for a, b, c in pniter([ 20, 30, None, 50, 60, 70, 80 ]):
        print( a, b, c )
    print('\ntest 5:')
    for a, b, c in pniter([ 20, 30, None, 50, 60, 70, 80 ], ['sig']):
        print( a, b, c )
    print('\ntest 6:')
    for a, b, c in pniter([ 20, ['?Signal value?'], None, '?Signal value?', 60, 70, 80 ], signal ):
        print( a, b, c )

Note that tests that include None and the same value as the signal value still work, because the check for the signal value uses "is" and the signal is a value that Python doesn't intern. Any singleton marker value can be used as a signal, though, which might simplify user code in some circumstances.

Browse files and subfolders in Python

from tkinter import *
import os

root = Tk()
file = filedialog.askdirectory()
changed_dir = os.listdir(file)
print(changed_dir)
root.mainloop()

Convert and format a Date in JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
 <!DOCTYPE html>
 <html dir="ltr" lang="en-US">
 <head>
 <meta charset="UTF-8" />
  <title>JSP with the current date</title>
  </head>
 <body>
 <%java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy"); %>
<h1>Current Date: <%= df.format(new java.util.Date()) %> </h1>
</body>
</html>

Output: Current Date: 10/03/2010

How to convert any Object to String?

"toString()" is Very useful method which returns a string representation of an object. The "toString()" method returns a string reperentation an object.It is recommended that all subclasses override this method.

Declaration: java.lang.Object.toString()

Since, you have not mentioned which object you want to convert, so I am just using any object in sample code.

Integer integerObject = 5;
String convertedStringObject = integerObject .toString();
System.out.println(convertedStringObject );

You can find the complete code here. You can test the code here.

Python error when trying to access list by index - "List indices must be integers, not str"

player['score'] is your problem. player is apparently a list which means that there is no 'score' element. Instead you would do something like:

name, score = player[0], player[1]
return name + ' ' + str(score)

Of course, you would have to know the list indices (those are the 0 and 1 in my example).

Something like player['score'] is allowed in python, but player would have to be a dict.

You can read more about both lists and dicts in the python documentation.

How can I disable ARC for a single file in a project?

Add flag “-fno-objc-arc”.

Simple follow steps : App>Targets>Build Phases>Compile Sources> add flag after class “-fno-objc-arc”

Recursively look for files with a specific extension

Though using find command can be useful here, the shell itself provides options to achieve this requirement without any third party tools. The bash shell provides an extended glob support option using which you can get the file names under recursive paths that match with the extensions you want.

The extended option is extglob which needs to be set using the shopt option as below. The options are enabled with the -s support and disabled with he -u flag. Additionally you could use couple of options more i.e. nullglob in which an unmatched glob is swept away entirely, replaced with a set of zero words. And globstar that allows to recurse through all the directories

shopt -s extglob nullglob globstar

Now all you need to do is form the glob expression to include the files of a certain extension which you can do as below. We use an array to populate the glob results because when quoted properly and expanded, the filenames with special characters would remain intact and not get broken due to word-splitting by the shell.

For example to list all the *.csv files in the recursive paths

fileList=(**/*.csv)

The option ** is to recurse through the sub-folders and *.csv is glob expansion to include any file of the extensions mentioned. Now for printing the actual files, just do

printf '%s\n' "${fileList[@]}"

Using an array and doing a proper quoted expansion is the right way when used in shell scripts, but for interactive use, you could simply use ls with the glob expression as

ls -1 -- **/*.csv

This could very well be expanded to match multiple files i.e. file ending with multiple extension (i.e. similar to adding multiple flags in find command). For example consider a case of needing to get all recursive image files i.e. of extensions *.gif, *.png and *.jpg, all you need to is

ls -1 -- **/+(*.jpg|*.gif|*.png)

This could very well be expanded to have negate results also. With the same syntax, one could use the results of the glob to exclude files of certain type. Assume you want to exclude file names with the extensions above, you could do

excludeResults=()
excludeResults=(**/!(*.jpg|*.gif|*.png))
printf '%s\n' "${excludeResults[@]}"

The construct !() is a negate operation to not include any of the file extensions listed inside and | is an alternation operator just as used in the Extended Regular Expressions library to do an OR match of the globs.

Note that these extended glob support is not available in the POSIX bourne shell and its purely specific to recent versions of bash. So if your are considering portability of the scripts running across POSIX and bash shells, this option wouldn't be right.

Best way to store chat messages in a database?

There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.

Actually you can find here in Stack Overflow a link to an example schema for a chat: example

If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages

Getting RAW Soap Data from a Web Reference Client running in ASP.net

It looks like Tim Carter's solution doesn't work if the call to the web reference throws an exception. I've been trying to get at the raw web resonse so I can examine it (in code) in the error handler once the exception is thrown. However, I'm finding that the response log written by Tim's method is blank when the call throws an exception. I don't completely understand the code, but it appears that Tim's method cuts into the process after the point where .Net has already invalidated and discarded the web response.

I'm working with a client that's developing a web service manually with low level coding. At this point, they are adding their own internal process error messages as HTML formatted messages into the response BEFORE the SOAP formatted response. Of course, the automagic .Net web reference blows up on this. If I could get at the raw HTTP response after an exception is thrown, I could look for and parse any SOAP response within the mixed returning HTTP response and know that they received my data OK or not.

Later ...

Here's a solution that does work, even after an execption (note that I'm only after the response - could get the request too):

namespace ChuckBevitt
{
    class GetRawResponseSoapExtension : SoapExtension
    {
        //must override these three methods
        public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
        {
            return null;
        }
        public override object GetInitializer(Type serviceType)
        {
            return null;
        }
        public override void Initialize(object initializer)
        {
        }

        private bool IsResponse = false;

        public override void ProcessMessage(SoapMessage message)
        {
            //Note that ProcessMessage gets called AFTER ChainStream.
            //That's why I'm looking for AfterSerialize, rather than BeforeDeserialize
            if (message.Stage == SoapMessageStage.AfterSerialize)
                IsResponse = true;
            else
                IsResponse = false;
        }

        public override Stream ChainStream(Stream stream)
        {
            if (IsResponse)
            {
                StreamReader sr = new StreamReader(stream);
                string response = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();

                File.WriteAllText(@"C:\test.txt", response);

                byte[] ResponseBytes = Encoding.ASCII.GetBytes(response);
                MemoryStream ms = new MemoryStream(ResponseBytes);
                return ms;

            }
            else
                return stream;
        }
    }
}

Here's how you configure it in the config file:

<configuration>
     ...
  <system.web>
    <webServices>
      <soapExtensionTypes>
        <add type="ChuckBevitt.GetRawResponseSoapExtension, TestCallWebService"
           priority="1" group="0" />
      </soapExtensionTypes>
    </webServices>
  </system.web>
</configuration>

"TestCallWebService" shoud be replaced with the name of the library (that happened to be the name of the test console app I was working in).

You really shouldn't have to go to ChainStream; you should be able to do it more simply from ProcessMessage as:

public override void ProcessMessage(SoapMessage message)
{
    if (message.Stage == SoapMessageStage.BeforeDeserialize)
    {
        StreamReader sr = new StreamReader(message.Stream);
        File.WriteAllText(@"C:\test.txt", sr.ReadToEnd());
        message.Stream.Position = 0; //Will blow up 'cause type of stream ("ConnectStream") doesn't alow seek so can't reset position
    }
}

If you look up SoapMessage.Stream, it's supposed to be a read-only stream that you can use to inspect the data at this point. This is a screw-up 'cause if you do read the stream, subsequent processing bombs with no data found errors (stream was at end) and you can't reset the position to the beginning.

Interestingly, if you do both methods, the ChainStream and the ProcessMessage ways, the ProcessMessage method will work because you changed the stream type from ConnectStream to MemoryStream in ChainStream, and MemoryStream does allow seek operations. (I tried casting the ConnectStream to MemoryStream - wasn't allow.)

So ..... Microsoft should either allow seek operations on the ChainStream type or make the SoapMessage.Stream truly a read-only copy as it's supposed to be. (Write your congressman, etc...)

One further point. After creating a way to retreive the raw HTTP response after an exception, I still didn't get the full response (as determined by a HTTP sniffer). This was because when the development web service added the HTML error messages to the beginning of the response, it didn't adjust the Content-Length header, so the Content-Length value was less than the size of the actual response body. All I got was the Content-Length value number of characters - the rest were missing. Obviously, when .Net reads the response stream, it just reads the Content-Length number of characters and doesn't allow for the Content-Length value possibily being wrong. This is as it should be; but if the Content-Length header value is wrong, the only way you'll ever get the entire response body is with a HTTP sniffer (I user HTTP Analyzer from http://www.ieinspector.com).

Count number of objects in list

I spent ages trying to figure this out but it is simple! You can use length(·). length(mylist) will tell you the number of objects mylist contains.

... and just realised someone had already answered this- sorry!

How to upload a file and JSON data in Postman?

The way to send mulitpart data which containts a file with the json data is the following, we need to set the content-type of the respective json key fields to 'application/json' in the postman body tab like the following: enter image description here

TimeStamp on file name using PowerShell

Thanks for the above script. One little modification to add in the file ending correctly. Try this ...

$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**

Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat

Not able to access adb in OS X through Terminal, "command not found"

In addition to slhck, this is what worked for me (mac).

To check where your sdk is located.

  1. Open Android studio and go to:

File -> Project Structure -> Sdk location

  1. Copy the path.

  2. Create the hidden .bash_profile in your home.

  3. (open it with vim, or open -e) with the following:

export PATH=/Users/<Your session name>/Library/Android/sdk/platform-tools:/Users/<Your session name>/Library/Android/sdk/tools:$PATH

  1. Then simply use this in your terminal: . ~/.bash_profile

SO post on how to find adb devices

Java ArrayList for integers

Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.

For Ex:

list.add(new Integer[3]);

In this way first entry of ArrayList is an integer array which can hold at max 3 values.

Link to download apache http server for 64bit windows.

Check out the link given it has Apache HTTP Server 2.4.2 x86 and x64 Windows Installers http://www.anindya.com/apache-http-server-2-4-2-x86-and-x64-windows-installers/

How to list processes attached to a shared memory segment in linux?

given your example above - to find processes attached to shmid 98306

lsof | egrep "98306|COMMAND"

How do I view 'git diff' output with my preferred diff tool/ viewer?

If you're on a Mac and have XCode, then you have FileMerge installed. The terminal command is opendiff, so you can just do git difftool -t opendiff

stringstream, string, and char* conversion confusion

stringstream.str() returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That's why your code prints garbage.

You could copy that temporary string object to some other string object and take the C string from that one:

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

Note that I made the temporary string const, because any changes to it might cause it to re-allocate and thus render cstr invalid. It is therefor safer to not to store the result of the call to str() at all and use cstr only until the end of the full expression:

use_c_str( stringstream.str().c_str() );

Of course, the latter might not be easy and copying might be too expensive. What you can do instead is to bind the temporary to a const reference. This will extend its lifetime to the lifetime of the reference:

{
  const std::string& tmp = stringstream.str();   
  const char* cstr = tmp.c_str();
}

IMO that's the best solution. Unfortunately it's not very well known.

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

With Angular CLI 6 you need to use builders as ng eject is deprecated and will soon be removed in 8.0. That's what it says when I try to do an ng eject

enter image description here

You can use angular-builders package (https://github.com/meltedspark/angular-builders) to provide your custom webpack config.

I have tried to summarize all in a single blog post on my blog - How to customize build configuration with custom webpack config in Angular CLI 6

but essentially you add following dependencies -

  "devDependencies": {
    "@angular-builders/custom-webpack": "^7.0.0",
    "@angular-builders/dev-server": "^7.0.0",
    "@angular-devkit/build-angular": "~0.11.0",

In angular.json make following changes -

  "architect": {
    "build": {
      "builder": "@angular-builders/custom-webpack:browser",
      "options": {
        "customWebpackConfig": {"path": "./custom-webpack.config.js"},

Notice change in builder and new option customWebpackConfig. Also change

    "serve": {
      "builder": "@angular-builders/dev-server:generic",

Notice the change in builder again for serve target. Post these changes you can create a file called custom-webpack.config.js in your same root directory and add your webpack config there.

However, unlike ng eject configuration provided here will be merged with default config so just add stuff you want to edit/add.

How to print exact sql query in zend framework ?

$statement = $this->sql->getSqlStringForSqlObject( HERE GOES Zend\Db\Sql\SelectSQL object );

echo "SQL statement: $statement";

Example:

$select = $this->sql->select();
...
$select->from(array( 'u' => 'users' ));
$select->join(...
$select->group('u.id');
...
$statement = $this->sql->getSqlStringForSqlObject($select);
echo $statement;

SQL Update Multiple Fields FROM via a SELECT Statement

You can use:

UPDATE s SET
  s.Field1 = q.Field1,
  s.Field2 = q.Field2,
  (list of fields...)
FROM (
  SELECT Field1, Field2, (list of fields...)
  FROM ProfilerTest.dbo.BookingDetails 
  WHERE MyID=@MyID
) q
WHERE s.MyID2=@ MyID2

How do I post button value to PHP?

    $restore = $this->createElement('submit', 'restore', array(
        'label' => 'FILE_RESTORE',
        'class' => 'restore btn btn-small btn-primary',
        'attribs' => array(
            'onClick' => 'restoreCheck();return false;'
        )
    ));

How do you completely remove the button border in wpf?

You can use Hyperlink instead of Button, like this:

        <TextBlock>
            <Hyperlink TextDecorations="{x:Null}">
            <Image Width="16"
                   Height="16"
                   Margin="3"
                   Source="/YourProjectName;component/Images/close-small.png" />
            </Hyperlink>
        </TextBlock>

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

filename and line number of Python script

Thanks to mcandre, the answer is:

#python3
from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print(frameinfo.filename, frameinfo.lineno)

Python: Split a list into sub-lists based on index ranges

If you already know the indices:

list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]

Note that we're adding +1 to the end to make the range inclusive...

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

Apple provides a macro to help provide better code compatibility, including Swift. Using the macro looks like this.

typedef NS_ENUM(NSInteger, PlayerStateType) {
  PlayerStateOff,
  PlayerStatePlaying,
  PlayerStatePaused
};

Documented here

nvm is not compatible with the npm config "prefix" option:

I ran into this while using node installed via nvm, with nvm installed via homebrew. I solved it by running brew uninstall nvm, rm -rf $NVM_DIR, then reinstalling nvm using the official install script and reinstalling the node version I needed.

Note: I also had $NVM_DIR mounted and symlinked. I moved it back into my homedir.

Android M Permissions: onRequestPermissionsResult() not being called

I had a similar problem except I was pressing a button to make a call, which triggers the callIntent. I checked permission first, if not granted I ask for permission and onRequestPermissionResult I call the check permission and call again.

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case Constants.PERMISSIONS_REQUEST_CALL_PHONE: {
            if ( grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                checkPermissionsAndCall();
            }
        }
    }
}

public void checkPermissionsAndCall(){
    if (Build.VERSION.SDK_INT > 22) {
        if(ContextCompat.checkSelfPermission(getContext(),
                Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED){
            requestPermissions( new String[]{Manifest.permission.CALL_PHONE}, Constants.PERMISSIONS_REQUEST_CALL_PHONE);
        }
        else{
            callIntent();
        }
    }
}

SQL UPDATE all values in a field with appended string CONCAT not working

convert the NULL values with empty string by wrapping it in COALESCE

"UPDATE table SET data = CONCAT(COALESCE(`data`,''), 'a')"

OR

Use CONCAT_WS instead:

"UPDATE table SET data = CONCAT_WS(',',data, 'a')"

Sending email from Command-line via outlook without having to click send

You can use cURL and CRON to run .php files at set times.

Here's an example of what cURL needs to run the .php file:

curl http://localhost/myscript.php

Then setup the CRON job to run the above cURL:

nano -w /var/spool/cron/root
or
crontab -e

Followed by:

01 * * * * /usr/bin/curl http://www.yoursite.com/script.php

For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/

For more info about cURL: What is cURL in PHP?

For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )

NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.

Best of luck with the automatic PHP running :-)

What's the difference between Thread start() and Runnable run()

The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

Get path from open file in Python

You can get it like this also.

filepath = os.path.abspath(f.name)

What does "implements" do on a class?

It is called an interface. Many OO languages have this feature. You might want to read through the php explanation here: http://de2.php.net/interface