Programs & Examples On #Curvycorners

A Javascript tool providing border-radius support for older browsers.

Check if a value is in an array or not with Excel VBA

This Question was asked here: VBA Arrays - Check strict (not approximative) match

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

Work on a remote project with Eclipse via SSH

I tried ssh -X but it was unbearably slow.

I also tried RSE, but it didn't even support building the project with a Makefile (I'm being told that this has changed since I posted my answer, but I haven't tried that out)

I read that NX is faster than X11 forwarding, but I couldn't get it to work.

Finally, I found out that my server supports X2Go (the link has install instructions if yours does not). Now I only had to:

  • download and unpack Eclipse on the server,
  • install X2Go on my local machine (sudo apt-get install x2goclient on Ubuntu),
  • configure the connection (host, auto-login with ssh key, choose to run Eclipse).

Everything is just as if I was working on a local machine, including building, debugging, and code indexing. And there are no noticeable lags.

Implementing SearchView in action bar

If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:

old:

android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"

new:

app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"

pre-android x:

app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"

For more information, it's updated documentation is located here.

How can I convert a std::string to int?

use the atoi function to convert the string to an integer:

string a = "25";

int b = atoi(a.c_str());

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

JSchException: Algorithm negotiation fail

The issue is with the Version of JSCH jar you are using.

Update it to latest jar.

I was also getting the same error and this solution worked.

You can download latest jar from

http://www.jcraft.com/jsch/

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

VB.Net Properties - Public Get, Private Set

One additional tweak worth mentioning: I'm not sure if this is a .NET 4.0 or Visual Studio 2010 feature, but if you're using both you don't need to declare the value parameter for the setter/mutator block of code:

Private _name As String

Public Property Name() As String
    Get
        Return _name
    End Get
    Private Set
        _name = value
    End Set
End Property

React: "this" is undefined inside a component function

In my case, for a stateless component that received the ref with forwardRef, I had to do what it is said here https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd

From this (onClick doesn't have access to the equivalent of 'this')

const Com = forwardRef((props, ref) => {
  return <input ref={ref} onClick={() => {console.log(ref.current} } />
})

To this (it works)

const useCombinedRefs = (...refs) => {
  const targetRef = React.useRef()

  useEffect(() => {
    refs.forEach(ref => {
      if (!ref) return

      if (typeof ref === 'function') ref(targetRef.current)
      else ref.current = targetRef.current
    })
  }, [refs])

  return targetRef
}

const Com = forwardRef((props, ref) => {
  const innerRef = useRef()
  const combinedRef = useCombinedRefs(ref, innerRef)

  return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})

Hidden Columns in jqGrid

To hide the grid column

jQuery("#validGrid").jqGrid('hideCol',str);

Redirect all output to file in Bash

Command:

foo >> output.txt 2>&1

appends to the output.txt file, without replacing the content.

determine DB2 text string length

Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;

How to set python variables to true or false?

Python boolean keywords are True and False, notice the capital letters. So like this:

a = True;
b = True;
match_var = True if a == b else False
print match_var;

When compiled and run, this prints:

True

failed to load ad : 3

I'm just going to leave this here incase it works for someone. After trying all the fixes mentioned in all the forums and posts what worked for me is simply using a global AdRequest object. I would use the same object when calling loadAd on each adView in each Activity. I have seen that it tends to load the same Ad on each AdView regardless of activity but at least now I get ads.

typescript - cloning object

Came across this problem myself and in the end wrote a small library cloneable-ts that provides an abstract class, which adds a clone method to any class extending it. The abstract class borrows the Deep Copy Function described in the accepted answer by Fenton only replacing copy = {}; with copy = Object.create(originalObj) to preserve the class of the original object. Here is an example of using the class.

import {Cloneable, CloneableArgs} from 'cloneable-ts';

// Interface that will be used as named arguments to initialize and clone an object
interface PersonArgs {
    readonly name: string;
    readonly age: number;
}

// Cloneable abstract class initializes the object with super method and adds the clone method
// CloneableArgs interface ensures that all properties defined in the argument interface are defined in class
class Person extends Cloneable<TestArgs>  implements CloneableArgs<PersonArgs> {
    readonly name: string;
    readonly age: number;

    constructor(args: TestArgs) {
        super(args);
    }
}

const a = new Person({name: 'Alice', age: 28});
const b = a.clone({name: 'Bob'})
a.name // Alice
b.name // Bob
b.age // 28

Or you could just use the Cloneable.clone helper method:

import {Cloneable} from 'cloneable-ts';

interface Person {
    readonly name: string;
    readonly age: number;
}

const a: Person = {name: 'Alice', age: 28};
const b = Cloneable.clone(a, {name: 'Bob'})
a.name // Alice
b.name // Bob
b.age // 28    

Process.start: how to get the output?

You can process your output synchronously or asynchronously.

1. Synchronous example

static void runCommand()
{
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*)
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.Start();
    //* Read the output (or the error)
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    string err = process.StandardError.ReadToEnd();
    Console.WriteLine(err);
    process.WaitForExit();
}

Note that it's better to process both output and errors: they must be handled separately.

(*) For some commands (here StartInfo.Arguments) you must add the /c directive, otherwise the process freezes in the WaitForExit().

2. Asynchronous example

static void runCommand() 
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set your output and error (asynchronous) handlers
    process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
    process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
    //* Start process and handlers
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
}

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

If you don't need to do complicate operations with the output, you can bypass the OutputHandler method, just adding the handlers directly inline:

//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);

Android: how to handle button click

To make things easier asp Question 2 stated, you can make use of lambda method like this to save variable memory and to avoid navigating up and down in your view class

//method 1
findViewById(R.id.buttonSend).setOnClickListener(v -> {
          // handle click
});

but if you wish to apply click event to your button at once in a method.

you can make use of Question 3 by @D. Tran answer. But do not forget to implement your view class with View.OnClickListener.

In other to use Question #3 properly

Static extension methods

In short, no, you can't.

Long answer, extension methods are just syntactic sugar. IE:

If you have an extension method on string let's say:

public static string SomeStringExtension(this string s)
{
   //whatever..
}

When you then call it:

myString.SomeStringExtension();

The compiler just turns it into:

ExtensionClass.SomeStringExtension(myString);

So as you can see, there's no way to do that for static methods.

And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:

Bool.Parse(..)

vs.

Helper.ParseBool(..);

Doesn't really bring much to the table...

What is the maximum possible length of a query string?

Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.

Please see the below example code for Windows IIS Servers with Web.config:

<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxQueryString="1024" maxUrl="2048">
           <headerLimits>
              <add header="Content-type" sizeLimit="100" />
           </headerLimits>
        </requestLimits>
     </requestFiltering>
</security>
</system.webServer>

This would also work on a server level using machine.config.

Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

C function that counts lines in file

You declare

int countlines(char *filename)

to take a char * argument.

You call it like this

countlines(fp)

passing in a FILE *.

That is why you get that compile error.

You probably should change that second line to

countlines("Test.txt")

since you open the file in countlines

Your current code is attempting to open the file in two different places.

Return HTML content as a string, given URL. Javascript Function

In some websites, XMLHttpRequest may send you something like <script src="#"></srcipt>. In that case, try using a HTML document like the script under:

<html>
  <body>
    <iframe src="website.com"></iframe>
    <script src="your_JS"></script>
  </body>
</html>

Now you can use JS to get some text out of the HTML, such as getElementbyId.

But this may not work for some websites with cross-domain blocking.

Fuzzy matching using T-SQL

Regarding de-duping things your string split and match is great first cut. If there are known items about the data that can be leveraged to reduce workload and/or produce better results, it is always good to take advantage of them. Bear in mind that often for de-duping it is impossible to entirely eliminate manual work, although you can make that much easier by catching as much as you can automatically and then generating reports of your "uncertainty cases."

Regarding name matching: SOUNDEX is horrible for quality of matching and especially bad for the type of work you are trying to do as it will match things that are too far from the target. It's better to use a combination of double metaphone results and the Levenshtein distance to perform name matching. With appropriate biasing this works really well and could probably be used for a second pass after doing a cleanup on your knowns.

You may also want to consider using an SSIS package and looking into Fuzzy Lookup and Grouping transformations (http://msdn.microsoft.com/en-us/library/ms345128(SQL.90).aspx).

Using SQL Full-Text Search (http://msdn.microsoft.com/en-us/library/cc879300.aspx) is a possibility as well, but is likely not appropriate to your specific problem domain.

CSS white space at bottom of page despite having both min-height and height tag

(class/ID):after {
content:none;
}

Always works for me class or ID can be for a div or even body causing the white space.

Javascript: The prettiest way to compare one value against multiple values

(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.

Is there a concise way to iterate over a stream with indices in Java 8?

If you happen to use Vavr(formerly known as Javaslang), you can leverage the dedicated method:

Stream.of("A", "B", "C")
  .zipWithIndex();

If we print out the content, we will see something interesting:

Stream((A, 0), ?)

This is because Streams are lazy and we have no clue about next items in the stream.

What is Gradle in Android Studio?

It's the new build tool that Google wants to use for Android. It's being used due to it being more extensible, and useful than ant. It is meant to enhance developer experience.

You can view a talk by Xavier Ducrohet from the Android Developer Team on Google I/O here.

There is also another talk on Android Studio by Xavier and Tor Norbye, also during Google I/O here.

Determine if variable is defined in Python

try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope

How to take a screenshot programmatically on iOS

This will save a screenshot and as well return the screenshot too.

-(UIImage *)capture{
    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *imageView = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(imageView, nil, nil, nil); //if you need to save
    return imageView;
}

self referential struct definition?

A Structure which contain a reference to itself. A common occurrence of this in a structure which describes a node for a link list. Each node needs a reference to the next node in the chain.

struct node
{
       int data;
       struct node *next; // <-self reference
};

NodeJS - What does "socket hang up" actually mean?

In my case, it was because a application/json response was badly formatted (contains a stack trace). The response was never send to the server. That was very tricky to debug because, there were no log. This thread helps me a lot to understand what happens.

Properly escape a double quote in CSV

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

Android: Color To Int conversion

Paint DOES have set color function.

/**
 * Set the paint's color. Note that the color is an int containing alpha
 * as well as r,g,b. This 32bit value is not premultiplied, meaning that
 * its alpha can be any value, regardless of the values of r,g,b.
 * See the Color class for more details.
 *
 * @param color The new color (including alpha) to set in the paint.
 */
public native void setColor(@ColorInt int color);

As an Android developer, I set paint color like this...

paint.setColor(getResources().getColor(R.color.xxx));

I define the color value on color.xml something like...

<color name="xxx">#008fd2</color>

By the way if you want to the hex RGB value of specific color value, then you can check website like this: http://www.rapidtables.com/web/color/RGB_Color.htm

I hope this helps ! Enjoy coding!

Typescript: difference between String and string

The two types are distinct in JavaScript as well as TypeScript - TypeScript just gives us syntax to annotate and check types as we go along.

String refers to an object instance that has String.prototype in its prototype chain. You can get such an instance in various ways e.g. new String('foo') and Object('foo'). You can test for an instance of the String type with the instanceof operator, e.g. myString instanceof String.

string is one of JavaScript's primitive types, and string values are primarily created with literals e.g. 'foo' and "bar", and as the result type of various functions and operators. You can test for string type using typeof myString === 'string'.

The vast majority of the time, string is the type you should be using - almost all API interfaces that take or return strings will use it. All JS primitive types will be wrapped (boxed) with their corresponding object types when using them as objects, e.g. accessing properties or calling methods. Since String is currently declared as an interface rather than a class in TypeScript's core library, structural typing means that string is considered a subtype of String which is why your first line passes compilation type checks.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

Just had a similar issue when I ran pod install, I saw the following warnings/errors (related to CLANG_CXX_LIBRARY):

The Error/Warning from Cocoapods

[!] The `Project [Debug]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.debug.xcconfig'. This can lead to problems with the CocoaPods installation
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

[!] The `Project [Release]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.release.xcconfig'. This can lead to problems with the CocoaPods installation
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

The Fix

  1. Select your Project so you can see the Build Settings.
  2. Select your Target (AppName under Targets)
  3. Find C++ Standard Library (It will probably be in BOLD - This means it's overridden).
  4. Select the Line (So it's highlighted Blue), and press ? + DELETE (Command + Backspace)

The line should not be bolded anymore and if you run pod install the warnings/errors should have disappeared.


Visual Aid

CLANG_CXX_LIBRARY Error/Warning with Cocoapods

Uploading Images to Server android

Try this method for uploading Image file from camera

package com.example.imageupload;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;

public class MultipartEntity implements HttpEntity {

private String boundary = null;

ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;

public MultipartEntity() {
    this.boundary = System.currentTimeMillis() + "";
}

public void writeFirstBoundaryIfNeeds() {
    if (!isSetFirst) {
        try {
            out.write(("--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {

        }
    }
    isSetFirst = true;
}

public void writeLastBoundaryIfNeeds() {
    if (isSetLast) {
        return;
    }
    try {
        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
    } catch (final IOException e) {

    }
    isSetLast = true;
}

public void addPart(final String key, final String value) {
    writeFirstBoundaryIfNeeds();
    try {
        out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
                .getBytes());
        out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
        out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
        out.write(value.getBytes());
        out.write(("\r\n--" + boundary + "\r\n").getBytes());
    } catch (final IOException e) {

    }
}

public void addPart(final String key, final String fileName,
        final InputStream fin) {
    addPart(key, fileName, fin, "application/octet-stream");
}

public void addPart(final String key, final String fileName,
        final InputStream fin, String type) {
    writeFirstBoundaryIfNeeds();
    try {
        type = "Content-Type: " + type + "\r\n";
        out.write(("Content-Disposition: form-data; name=\"" + key
                + "\"; filename=\"" + fileName + "\"\r\n").getBytes());
        out.write(type.getBytes());
        out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());

        final byte[] tmp = new byte[4096];
        int l = 0;
        while ((l = fin.read(tmp)) != -1) {
            out.write(tmp, 0, l);
        }
        out.flush();
    } catch (final IOException e) {

    } finally {
        try {
            fin.close();
        } catch (final IOException e) {

        }
    }
}

public void addPart(final String key, final File value) {
    try {
        addPart(key, value.getName(), new FileInputStream(value));
    } catch (final FileNotFoundException e) {

    }
}

public long getContentLength() {
    writeLastBoundaryIfNeeds();
    return out.toByteArray().length;
}

public Header getContentType() {
    return new BasicHeader("Content-Type", "multipart/form-data; boundary="
            + boundary);
}

public boolean isChunked() {
    return false;
}

public boolean isRepeatable() {
    return false;
}

public boolean isStreaming() {
    return false;
}

public void writeTo(final OutputStream outstream) throws IOException {
    outstream.write(out.toByteArray());
}

public Header getContentEncoding() {
    return null;
}

public void consumeContent() throws IOException,
        UnsupportedOperationException {
    if (isStreaming()) {
        throw new UnsupportedOperationException(
                "Streaming entity does not implement #consumeContent()");
    }
}

public InputStream getContent() throws IOException,
        UnsupportedOperationException {
    return new ByteArrayInputStream(out.toByteArray());
}

}

Use of class for uploading

private void doFileUpload(File file_path) {

    Log.d("Uri", "Do file path" + file_path);

    try {

        HttpClient client = new DefaultHttpClient();
        //use your server path of php file
        HttpPost post = new HttpPost(ServerUploadPath);

        Log.d("ServerPath", "Path" + ServerUploadPath);

        FileBody bin1 = new FileBody(file_path);
        Log.d("Enter", "Filebody complete " + bin1);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("uploaded_file", bin1);
        reqEntity.addPart("email", new StringBody(useremail));

        post.setEntity(reqEntity);
        Log.d("Enter", "Image send complete");

        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        Log.d("Enter", "Get Response");
        try {

            final String response_str = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                Log.i("RESPONSE", response_str);
                JSONObject jobj = new JSONObject(response_str);
                result = jobj.getString("ResponseCode");
                Log.e("Result", "...." + result);

            }
        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
    } catch (Exception e) {
        Log.e("Upload Exception", "");
        e.printStackTrace();
    }
}

Service for uploading

   <?php
$image_name = $_FILES["uploaded_file"]["name"]; 
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;    
$flag=0;                 

if (file_exists("Images/".$new_image_name))
{
           $msg=$new_image_name . " already exists."
           header('Content-type: application/json');        
           echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));        
}else{  
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
                   $flag = 1;
}   

if($flag == 1){                    
            require 'db.php';   
            $static_url =$new_image_name;
            $conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
            $db=mysql_select_db($db_database,$conn) or die("unable to select message_app"); 
            $email = "";
            if((isset($_REQUEST['email'])))
            {
                     $email = $_REQUEST['email'];
            }

    $sql ="insert into alert(images) values('$static_url')";

     $result=mysql_query($sql);

     if($result){
    echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
       } else
       {

         echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
        }
}
    else{
    echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
    }
    ?>

What is TypeScript and why would I use it in place of JavaScript?

"TypeScript Fundamentals" -- a Pluralsight video-course by Dan Wahlin and John Papa is a really good, presently (March 25, 2016) updated to reflect TypeScript 1.8, introduction to Typescript.

For me the really good features, beside the nice possibilities for intellisense, are the classes, interfaces, modules, the ease of implementing AMD, and the possibility to use the Visual Studio Typescript debugger when invoked with IE.

To summarize: If used as intended, Typescript can make JavaScript programming more reliable, and easier. It can increase the productivity of the JavaScript programmer significantly over the full SDLC.

What static analysis tools are available for C#?

Axivion Bauhaus Suite is a static analysis tool that works with C# (as well as C, C++ and Java).

It provides the following capabilities:

  • Software Architecture Visualization (inlcuding dependencies)
  • Enforcement of architectural rules e.g. layering, subsystems, calling rules
  • Clone Detection - highlighting copy and pasted (and modified code)
  • Dead Code Detection
  • Cycle Detection
  • Software Metrics
  • Code Style Checks

These features can be run on a one-off basis or as part of a Continuous Integration process. Issues can be highlighted on a per project basis or per developer basis when the system is integrated with a source code control system.

Playing m3u8 Files with HTML Video Tag

Might be a little late with the answer but you need to supply the MIME type attribute in the video tag: type="application/x-mpegURL". The video tag I use for a 16:9 stream looks like this.

<video width="352" height="198" controls>
    <source src="playlist.m3u8" type="application/x-mpegURL">
</video>

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

The fragment already has startActivityForResult, which would call onActivityResult in the fragment if you use it, instead of getActivity()...

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

A few years ago it was said that update() and digest() were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:

var crypto    = require('crypto');
var text      = 'I love cupcakes';
var secret    = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1';   //consider using sha256
var hash, hmac;

// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);    
hmac.write(text); // write in to the stream
hmac.end();       // can't read from the stream until you call end()
hash = hmac.read().toString('hex');    // read out hmac digest
console.log("Method 1: ", hash);

// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);

Tested on node v6.2.2 and v7.7.2

See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.

How to use in jQuery :not and hasClass() to get a specific element without a class

Use the not function instead:

var lastOpenSite = $(this).siblings().not('.closedTab');

hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.

cannot connect to pc-name\SQLEXPRESS

go to services and start the ones related to SQL

How to enable file sharing for my app?

If you editing info.plist directly, below should help you, don't key in "YES" as string below:

<key>UIFileSharingEnabled</key>
<string>YES</string>

You should use this:

<key>UIFileSharingEnabled</key>
<true/>

SSH to Elastic Beanstalk instance

I found it to be a 2-step process. This assumes that you've already set up a keypair to access EC2 instances in the relevant region.

Configure Security Group

  1. In the AWS console, open the EC2 tab.

  2. Select the relevant region and click on Security Group.

  3. You should have an elasticbeanstalk-default security group if you have launched an Elastic Beanstalk instance in that region.

  4. Edit the security group to add a rule for SSH access. The below will lock it down to only allow ingress from a specific IP address.

    SSH | tcp | 22 | 22 | 192.168.1.1/32
    

Configure the environment of your Elastic Beanstalk Application

  1. If you haven't made a key pair yet, make one by clicking Key Pairs below Security Group in the ec2 tab.
  2. In the AWS console, open the Elastic Beanstalk tab.
  3. Select the relevant region.
  4. Select relevant Environment
  5. Select Configurations in left pane.
  6. Select Security.
  7. Under "EC2 key pair:", select the name of your keypair in the Existing Key Pair field.

If after these steps you see that the Health is set Degraded

enter image description here

that's normal and it just means that the EC2 instance is being updated. Just wait on a few seconds it'll be Ok again

enter image description here

Once the instance has relaunched, you need to get the host name from the AWS Console EC2 instances tab, or via the API. You should then be able to ssh onto the server.

$ ssh -i path/to/keypair.pub [email protected]

Note: For adding a keypair to the environment configuration, the instances' termination protection must be off as Beanstalk would try to terminate the current instances and start new instances with the KeyPair.

Note: If something is not working, check the "Events" tab in the Beanstalk application / environments and find out what went wrong.

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

After trying all solutions it worked only for me after specifying the host

mysql -u root -p -h127.0.0.1

when asking for password

Enter password:

press enter

and it will work , if everything is ok as above .

How to get a variable value if variable name is stored as string?

For my fellow zsh users, the way to accomplish the same thing as the accepted answer is to use:

${(P)a}

It is appropriately called Parameter name replacement

This forces the value of the parameter name to be interpreted as a further parameter name, whose value will be used where appropriate. Note that flags set with one of the typeset family of commands (in particular case transformations) are not applied to the value of name used in this fashion.

If used with a nested parameter or command substitution, the result of that will be taken as a parameter name in the same way. For example, if you have ‘foo=bar’ and ‘bar=baz’, the strings ${(P)foo}, ${(P)${foo}}, and ${(P)$(echo bar)} will be expanded to ‘baz’.

Likewise, if the reference is itself nested, the expression with the flag is treated as if it were directly replaced by the parameter name. It is an error if this nested substitution produces an array with more than one word. For example, if ‘name=assoc’ where the parameter assoc is an associative array, then ‘${${(P)name}[elt]}’ refers to the element of the associative subscripted ‘elt’.

How to make sure that string is valid JSON using JSON.NET

I'm using this one:

  internal static bool IsValidJson(string data)
  {
     data = data.Trim();
     try
     {
        if (data.StartsWith("{") && data.EndsWith("}"))
        {
           JToken.Parse(data);
        }
        else if (data.StartsWith("[") && data.EndsWith("]"))
        {
           JArray.Parse(data);
        }
        else
        {
           return false;
        }
        return true;
     }
     catch
     {
        return false;
     }
  }

Can I set an opacity only to the background image of a div?

None of the solutions worked for me. If everything else fails, get the picture to Photoshop and apply some effect. 5 minutes versus so much time on this...

How can getContentResolver() be called in Android?

Access contentResolver in Kotlin , inside activities, Object classes &... :

Application().contentResolver

Restart pods when configmap updates in Kubernetes?

The current best solution to this problem (referenced deep in https://github.com/kubernetes/kubernetes/issues/22368 linked in the sibling answer) is to use Deployments, and consider your ConfigMaps to be immutable.

When you want to change your config, create a new ConfigMap with the changes you want to make, and point your deployment at the new ConfigMap. If the new config is broken, the Deployment will refuse to scale down your working ReplicaSet. If the new config works, then your old ReplicaSet will be scaled to 0 replicas and deleted, and new pods will be started with the new config.

Not quite as quick as just editing the ConfigMap in place, but much safer.

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

I find the best is to always convert to unicode - but this is difficult to achieve because in practice you'd have to check and convert every argument to every function and method you ever write that includes some form of string processing.

So I came up with the following approach to either guarantee unicodes or byte strings, from either input. In short, include and use the following lambdas:

# guarantee unicode string
_u = lambda t: t.decode('UTF-8', 'replace') if isinstance(t, str) else t
_uu = lambda *tt: tuple(_u(t) for t in tt) 
# guarantee byte string in UTF8 encoding
_u8 = lambda t: t.encode('UTF-8', 'replace') if isinstance(t, unicode) else t
_uu8 = lambda *tt: tuple(_u8(t) for t in tt)

Examples:

text='Some string with codes > 127, like Zürich'
utext=u'Some string with codes > 127, like Zürich'
print "==> with _u, _uu"
print _u(text), type(_u(text))
print _u(utext), type(_u(utext))
print _uu(text, utext), type(_uu(text, utext))
print "==> with u8, uu8"
print _u8(text), type(_u8(text))
print _u8(utext), type(_u8(utext))
print _uu8(text, utext), type(_uu8(text, utext))
# with % formatting, always use _u() and _uu()
print "Some unknown input %s" % _u(text)
print "Multiple inputs %s, %s" % _uu(text, text)
# but with string.format be sure to always work with unicode strings
print u"Also works with formats: {}".format(_u(text))
print u"Also works with formats: {},{}".format(*_uu(text, text))
# ... or use _u8 and _uu8, because string.format expects byte strings
print "Also works with formats: {}".format(_u8(text))
print "Also works with formats: {},{}".format(*_uu8(text, text))

Here's some more reasoning about this.

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

Smooth scroll to div id jQuery

This works to me.

<div id="demo">
        <h2>Demo</h2>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $(document).ready(function () {
        // Handler for .ready() called.
        $('html, body').animate({
            scrollTop: $('#demo').offset().top
        }, 'slow');
    });
</script>

Thanks.

How to calculate the time interval between two time strings

Both time and datetime have a date component.

Normally if you are just dealing with the time part you'd supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a datetime for each with the day set to today and subtract the start from the stop time to get the interval (timedelta).

Laravel Escaping All HTML in Blade Template

use this tag {!! description text !!}

Python loop for inside lambda

Just in case, if someone is looking for a similar problem...

Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code). Instead, you can use a simple list comprehension.

[print(i) for i in x]

BTW, the return values will be a list on None s.

Auto Increment after delete in MySQL

I got a very simple but tricky method.

While deleting a row, you can preserve the IDs into another temporary table. After that, when you will insert new data into the main table then you can search and pick IDs from the temporary table. So use a checking here. If the temporary table has no IDs then calculate maximum ID into the main table and set the new ID as: new_ID = old_max_ID+1.

NB: You can not use auto-increment feature here.

How can I get log4j to delete old rotating log files?

You can achieve it using custom log4j appender.
MaxNumberOfDays - possibility to set amount of days of rotated log files.
CompressBackups - possibility to archive old logs with zip extension.

package com.example.package;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CustomLog4jAppender extends FileAppender {

    private static final int TOP_OF_TROUBLE = -1;
    private static final int TOP_OF_MINUTE = 0;
    private static final int TOP_OF_HOUR = 1;
    private static final int HALF_DAY = 2;
    private static final int TOP_OF_DAY = 3;
    private static final int TOP_OF_WEEK = 4;
    private static final int TOP_OF_MONTH = 5;

    private String datePattern = "'.'yyyy-MM-dd";
    private String compressBackups = "false";
    private String maxNumberOfDays = "7";
    private String scheduledFilename;
    private long nextCheck = System.currentTimeMillis() - 1;
    private Date now = new Date();
    private SimpleDateFormat sdf;
    private RollingCalendar rc = new RollingCalendar();

    private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");

    public CustomLog4jAppender() {
    }

    public CustomLog4jAppender(Layout layout, String filename, String datePattern) throws IOException {
        super(layout, filename, true);
        this.datePattern = datePattern;
        activateOptions();
    }

    public void setDatePattern(String pattern) {
        datePattern = pattern;
    }

    public String getDatePattern() {
        return datePattern;
    }

    @Override
    public void activateOptions() {
        super.activateOptions();
        if (datePattern != null && fileName != null) {
            now.setTime(System.currentTimeMillis());
            sdf = new SimpleDateFormat(datePattern);
            int type = computeCheckPeriod();
            printPeriodicity(type);
            rc.setType(type);
            File file = new File(fileName);
            scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
        } else {
            LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
        }
    }

    private void printPeriodicity(int type) {
        String appender = "Log4J Appender: ";
        switch (type) {
            case TOP_OF_MINUTE:
                LogLog.debug(appender + name + " to be rolled every minute.");
                break;
            case TOP_OF_HOUR:
                LogLog.debug(appender + name + " to be rolled on top of every hour.");
                break;
            case HALF_DAY:
                LogLog.debug(appender + name + " to be rolled at midday and midnight.");
                break;
            case TOP_OF_DAY:
                LogLog.debug(appender + name + " to be rolled at midnight.");
                break;
            case TOP_OF_WEEK:
                LogLog.debug(appender + name + " to be rolled at start of week.");
                break;
            case TOP_OF_MONTH:
                LogLog.debug(appender + name + " to be rolled at start of every month.");
                break;
            default:
                LogLog.warn("Unknown periodicity for appender [" + name + "].");
        }
    }

    private int computeCheckPeriod() {
        RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.ENGLISH);
        Date epoch = new Date(0);
        if (datePattern != null) {
            for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
                simpleDateFormat.setTimeZone(gmtTimeZone);
                String r0 = simpleDateFormat.format(epoch);
                rollingCalendar.setType(i);
                Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
                String r1 = simpleDateFormat.format(next);
                if (!r0.equals(r1)) {
                    return i;
                }
            }
        }
        return TOP_OF_TROUBLE;
    }

    private void rollOver() throws IOException {
        if (datePattern == null) {
            errorHandler.error("Missing DatePattern option in rollOver().");
            return;
        }
        String datedFilename = fileName + sdf.format(now);
        if (scheduledFilename.equals(datedFilename)) {
            return;
        }
        this.closeFile();
        File target = new File(scheduledFilename);
        if (target.exists()) {
            Files.delete(target.toPath());
        }
        File file = new File(fileName);
        boolean result = file.renameTo(target);
        if (result) {
            LogLog.debug(fileName + " -> " + scheduledFilename);
        } else {
            LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
        }
        try {
            this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
        } catch (IOException e) {
            errorHandler.error("setFile(" + fileName + ", false) call failed.");
        }
        scheduledFilename = datedFilename;
    }

    @Override
    protected void subAppend(LoggingEvent event) {
        long n = System.currentTimeMillis();
        if (n >= nextCheck) {
            now.setTime(n);
            nextCheck = rc.getNextCheckMillis(now);
            try {
                cleanupAndRollOver();
            } catch (IOException ioe) {
                LogLog.error("cleanupAndRollover() failed.", ioe);
            }
        }
        super.subAppend(event);
    }

    public String getCompressBackups() {
        return compressBackups;
    }

    public void setCompressBackups(String compressBackups) {
        this.compressBackups = compressBackups;
    }

    public String getMaxNumberOfDays() {
        return maxNumberOfDays;
    }

    public void setMaxNumberOfDays(String maxNumberOfDays) {
        this.maxNumberOfDays = maxNumberOfDays;
    }

    protected void cleanupAndRollOver() throws IOException {
        File file = new File(fileName);
        Calendar cal = Calendar.getInstance();
        int maxDays = 7;
        try {
            maxDays = Integer.parseInt(getMaxNumberOfDays());
        } catch (Exception e) {
            // just leave it at 7.
        }
        cal.add(Calendar.DATE, -maxDays);
        Date cutoffDate = cal.getTime();
        if (file.getParentFile().exists()) {
            File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false));
            int nameLength = file.getName().length();
            for (File value : Optional.ofNullable(files).orElse(new File[0])) {
                String datePart;
                try {
                    datePart = value.getName().substring(nameLength);
                    Date date = sdf.parse(datePart);
                    if (date.before(cutoffDate)) {
                        Files.delete(value.toPath());
                    } else if (getCompressBackups().equalsIgnoreCase("YES") || getCompressBackups().equalsIgnoreCase("TRUE")) {
                        zipAndDelete(value);
                    }
                } catch (Exception pe) {
                    // This isn't a file we should touch (it isn't named correctly)
                }
            }
        }
        rollOver();
    }

    private void zipAndDelete(File file) throws IOException {
        if (!file.getName().endsWith(".zip")) {
            File zipFile = new File(file.getParent(), file.getName() + ".zip");
            try (FileInputStream fis = new FileInputStream(file);
                 FileOutputStream fos = new FileOutputStream(zipFile);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                byte[] buffer = new byte[4096];
                while (true) {
                    int bytesRead = fis.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    } else {
                        zos.write(buffer, 0, bytesRead);
                    }
                }
                zos.closeEntry();
            }
            Files.delete(file.toPath());
        }
    }

    class StartsWithFileFilter implements FileFilter {
        private String startsWith;
        private boolean inclDirs;

        StartsWithFileFilter(String startsWith, boolean includeDirectories) {
            super();
            this.startsWith = startsWith.toUpperCase();
            inclDirs = includeDirectories;
        }

        public boolean accept(File pathname) {
            if (!inclDirs && pathname.isDirectory()) {
                return false;
            } else {
                return pathname.getName().toUpperCase().startsWith(startsWith);
            }
        }
    }

    class RollingCalendar extends GregorianCalendar {
        private static final long serialVersionUID = -3560331770601814177L;

        int type = CustomLog4jAppender.TOP_OF_TROUBLE;

        RollingCalendar() {
            super();
        }

        RollingCalendar(TimeZone tz, Locale locale) {
            super(tz, locale);
        }

        void setType(int type) {
            this.type = type;
        }

        long getNextCheckMillis(Date now) {
            return getNextCheckDate(now).getTime();
        }

        Date getNextCheckDate(Date now) {
            this.setTime(now);

            switch (type) {
                case CustomLog4jAppender.TOP_OF_MINUTE:
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MINUTE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_HOUR:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.HOUR_OF_DAY, 1);
                    break;
                case CustomLog4jAppender.HALF_DAY:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    int hour = get(Calendar.HOUR_OF_DAY);
                    if (hour < 12) {
                        this.set(Calendar.HOUR_OF_DAY, 12);
                    } else {
                        this.set(Calendar.HOUR_OF_DAY, 0);
                        this.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    break;
                case CustomLog4jAppender.TOP_OF_DAY:
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.DATE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_WEEK:
                    this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.WEEK_OF_YEAR, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_MONTH:
                    this.set(Calendar.DATE, 1);
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MONTH, 1);
                    break;
                default:
                    throw new IllegalStateException("Unknown periodicity type.");
            }
            return getTime();
        }
    }    
}

And use this properties in your log4j config file:

log4j.appender.[appenderName]=com.example.package.CustomLog4jAppender
log4j.appender.[appenderName].File=/logs/app-daily.log
log4j.appender.[appenderName].Append=true
log4j.appender.[appenderName].encoding=UTF-8
log4j.appender.[appenderName].layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.[appenderName].layout.ConversionPattern=%-5.5p %d %C{1.} - %m%n
log4j.appender.[appenderName].DatePattern='.'yyyy-MM-dd
log4j.appender.[appenderName].MaxNumberOfDays=7
log4j.appender.[appenderName].CompressBackups=true

Replace multiple strings with multiple other strings

    var str = "I have a cat, a dog, and a goat.";

    str = str.replace(/goat/i, "cat");
    // now str = "I have a cat, a dog, and a cat."

    str = str.replace(/dog/i, "goat");
    // now str = "I have a cat, a goat, and a cat."

    str = str.replace(/cat/i, "dog");
    // now str = "I have a dog, a goat, and a cat."

Can I draw rectangle in XML?

try this

                <TableRow
                    android:layout_width="match_parent"
                    android:layout_marginTop="5dp"
                    android:layout_height="wrap_content">

                    <View
                        android:layout_width="15dp"
                        android:layout_height="15dp"
                        android:background="#3fe1fa" />

                    <TextView
                        android:textSize="12dp"
                        android:paddingLeft="10dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="1700 Market Street"
                        android:id="@+id/textView8" />
                </TableRow>

output

enter image description here

SQL Server 2005 Setting a variable to the result of a select query

You can use something like

SET @cnt = (SELECT COUNT(*) FROM User)

or

SELECT @cnt = (COUNT(*) FROM User)

For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis.

Edit: Have you tried something like this?

DECLARE @OOdate DATETIME

SET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1

Select COUNT(FF.HALID) 
from Outages.FaultsInOutages as OFIO 
inner join Faults.Faults as FF 
    ON FF.HALID = OFIO.HALID 
WHERE @OODate = FF.FaultDate
    AND OFIO.OutageID = 1

nano error: Error opening terminal: xterm-256color

After upgrading to OSX Lion, I started getting this error on certain (Debian/Ubuntu) servers. The fix is simply to install the “ncurses-term” package which provides the file /usr/share/terminfo/x/xterm-256color.

This worked for me on a Ubuntu server, via Erik Osterman.

How to make Bitmap compress without change the bitmap size?

If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.

Quality Accepts 0 - 100

0 = MAX Compression (Least Quality which is suitable for Small images)

100 = Least Compression (MAX Quality which is suitable for Big images)

Proper way to exit command line program?

Using control-z suspends the process (see the output from stty -a which lists the key stroke under susp). That leaves it running, but in suspended animation (so it is not using any CPU resources). It can be resumed later.

If you want to stop a program permanently, then any of interrupt (often control-c) or quit (often control-\) will stop the process, the latter producing a core dump (unless you've disabled them). You might also use a HUP or TERM signal (or, if really necessary, the KILL signal, but try the other signals first) sent to the process from another terminal; or you could use control-z to suspend the process and then send the death threat from the current terminal, and then bring the (about to die) process back into the foreground (fg).

Note that all key combinations are subject to change via the stty command or equivalents; the defaults may vary from system to system.

Pass object to javascript function

function myFunction(arg) {
    alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}

myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });

Using Django time/date widgets in custom form

My head code for 1.4 version(some new and some removed)

{% block extrahead %}

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/widgets.css"/>

<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/core.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/RelatedObjectLookups.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.init.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/actions.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/calendar.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/DateTimeShortcuts.js"></script>

{% endblock %}

Using G++ to compile multiple .cpp and .h files

Now that I've separated the classes to .h and .cpp files do I need to use a makefile or can I still use the "g++ main.cpp" command?

Compiling several files at once is a poor choice if you are going to put that into the Makefile.

Normally in a Makefile (for GNU/Make), it should suffice to write that:

# "all" is the name of the default target, running "make" without params would use it
all: executable1

# for C++, replace CC (c compiler) with CXX (c++ compiler) which is used as default linker
CC=$(CXX)

# tell which files should be used, .cpp -> .o make would do automatically
executable1: file1.o file2.o

That way make would be properly recompiling only what needs to be recompiled. One can also add few tweaks to generate the header file dependencies - so that make would also properly rebuild what's need to be rebuilt due to the header file changes.

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

IIS7 defines a defaultDocument section in its configuration files which can be found in the %WinDir%\System32\InetSrv\Config folder. Most likely, the file index.aspx is already defined as a default document in one of IIS7's configuration files and you are adding it again in your web.config.

I suspect that removing the line <add value="index.aspx" />

from the defaultDocument/files section will fix your issue.

The defaultDocument section of your config will look like:

<defaultDocument>
  <files>
    <remove value="default.aspx" />
    <remove value="index.html" />
    <remove value="iisstart.htm" />
    <remove value="index.htm" />
    <remove value="Default.asp" />
    <remove value="Default.htm" />
  </files>
</defaultDocument>

Note that index.aspx will still appear in the list of default documents for your site in the IIS manager.

For more information about IIS7 configuration, click here.

How to use makefiles in Visual Studio?

A UNIX guy probably told you that. :)

You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret_cast of the builder. IMO the simplest thing is just to use Solutions.

Download single files from GitHub

Git does not support downloading parts of the repository. You have to download all of it. But you should be able to do this with GitHub.

When you view a file it has a link to the "raw" version. The URL is constructed like so

https://raw.githubusercontent.com/user/repository/branch/filename

By filling in the blanks in the URL, you can use Wget or cURL (with the -L option, see below) or whatever to download a single file. Again, you won't get any of the nice version control features used by Git by doing this.

Update: I noticed you mention this doesn't work for binary files. You probably shouldn't use binary files in your Git repository, but GitHub has a download section for each repository that you can use to upload files. If you need more than one binary, you can use a .zip file. The URL to download an uploaded file is:

https://github.com/downloads/user/repository/filename

Note that the URLs given above, from the links on github.com, will redirect to raw.githubusercontent.com. You should not directly use the URL given by this HTTP 302 redirect because, per RFC 2616: "Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests."

right click context menu for datagridview

Use the CellMouseDown event on the DataGridView. From the event handler arguments you can determine which cell was clicked. Using the PointToClient() method on the DataGridView you can determine the relative position of the pointer to the DataGridView, so you can pop up the menu in the correct location.

(The DataGridViewCellMouseEvent parameter just gives you the X and Y relative to the cell you clicked, which isn't as easy to use to pop up the context menu.)

This is the code I used to get the mouse position, then adjust for the position of the DataGridView:

var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);
this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);

The entire event handler looks like this:

private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    // Ignore if a column or row header is clicked
    if (e.RowIndex != -1 && e.ColumnIndex != -1)
    {
        if (e.Button == MouseButtons.Right)
        {
            DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];

            // Here you can do whatever you want with the cell
            this.DataGridView1.CurrentCell = clickedCell;  // Select the clicked cell, for instance

            // Get mouse position relative to the vehicles grid
            var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);

            // Show the context menu
            this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);
        }
    }
}

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Also check if a completely empty app.config file (completely blank with absolutely no markup) is within the test project. This was the culprit in my case.

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

If you do Code-First and already have a Database:

public override void Up()
{
    AlterColumn("dbo.MyTable","Id", c =>  c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"));
}

jQuery: go to URL with target="_blank"

Use,

var url = $(this).attr('href');
window.open(url, '_blank');

Update:the href is better off being retrieved with prop since it will return the full url and it's slightly faster.

var url = $(this).prop('href');

How to delete node from XML file using C#

DocumentElement is the root node of the document so childNodes[1] doesn't exist in that document. childNodes[0] would be the <Settings> node

jQuery Data vs Attr?

If you are passing data to a DOM element from the server, you should set the data on the element:

<a id="foo" data-foo="bar" href="#">foo!</a>

The data can then be accessed using .data() in jQuery:

console.log( $('#foo').data('foo') );
//outputs "bar"

However when you store data on a DOM node in jQuery using data, the variables are stored on the node object. This is to accommodate complex objects and references as storing the data on the node element as an attribute will only accommodate string values.

Continuing my example from above:
$('#foo').data('foo', 'baz');

console.log( $('#foo').attr('data-foo') );
//outputs "bar" as the attribute was never changed

console.log( $('#foo').data('foo') );
//outputs "baz" as the value has been updated on the object

Also, the naming convention for data attributes has a bit of a hidden "gotcha":

HTML:
<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('fooBarBaz') );
//outputs "fizz-buzz" as hyphens are automatically camelCase'd

The hyphenated key will still work:

HTML:
<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('foo-bar-baz') );
//still outputs "fizz-buzz"

However the object returned by .data() will not have the hyphenated key set:

$('#bar').data().fooBarBaz; //works
$('#bar').data()['fooBarBaz']; //works
$('#bar').data()['foo-bar-baz']; //does not work

It's for this reason I suggest avoiding the hyphenated key in javascript.

For HTML, keep using the hyphenated form. HTML attributes are supposed to get ASCII-lowercased automatically, so <div data-foobar></div>, <DIV DATA-FOOBAR></DIV>, and <dIv DaTa-FoObAr></DiV> are supposed to be treated as identical, but for the best compatibility the lower case form should be preferred.

The .data() method will also perform some basic auto-casting if the value matches a recognized pattern:

HTML:
<a id="foo"
    href="#"
    data-str="bar"
    data-bool="true"
    data-num="15"
    data-json='{"fizz":["buzz"]}'>foo!</a>
JS:
$('#foo').data('str');  //`"bar"`
$('#foo').data('bool'); //`true`
$('#foo').data('num');  //`15`
$('#foo').data('json'); //`{fizz:['buzz']}`

This auto-casting ability is very convenient for instantiating widgets & plugins:

$('.widget').each(function () {
    $(this).widget($(this).data());
    //-or-
    $(this).widget($(this).data('widget'));
});

If you absolutely must have the original value as a string, then you'll need to use .attr():

HTML:
<a id="foo" href="#" data-color="ABC123"></a>
<a id="bar" href="#" data-color="654321"></a>
JS:
$('#foo').data('color').length; //6
$('#bar').data('color').length; //undefined, length isn't a property of numbers

$('#foo').attr('data-color').length; //6
$('#bar').attr('data-color').length; //6

This was a contrived example. For storing color values, I used to use numeric hex notation (i.e. 0xABC123), but it's worth noting that hex was parsed incorrectly in jQuery versions before 1.7.2, and is no longer parsed into a Number as of jQuery 1.8 rc 1.

jQuery 1.8 rc 1 changed the behavior of auto-casting. Before, any format that was a valid representation of a Number would be cast to Number. Now, values that are numeric are only auto-cast if their representation stays the same. This is best illustrated with an example.

HTML:
<a id="foo"
    href="#"
    data-int="1000"
    data-decimal="1000.00"
    data-scientific="1e3"
    data-hex="0x03e8">foo!</a>
JS:
                              // pre 1.8    post 1.8
$('#foo').data('int');        //    1000        1000
$('#foo').data('decimal');    //    1000   "1000.00"
$('#foo').data('scientific'); //    1000       "1e3"
$('#foo').data('hex');        //    1000     "0x03e8"

If you plan on using alternative numeric syntaxes to access numeric values, be sure to cast the value to a Number first, such as with a unary + operator.

JS (cont.):
+$('#foo').data('hex'); // 1000

Error: unable to verify the first certificate in nodejs

Another dirty hack, which will make all your requests insecure:

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0

'any' vs 'Object'

Bit old, but doesn't hurt to add some notes.

When you write something like this

let a: any;
let b: Object;
let c: {};
  • a has no interface, it can be anything, the compiler knows nothing about its members so no type checking is performed when accessing/assigning both to it and its members. Basically, you're telling the compiler to "back off, I know what I'm doing, so just trust me";
  • b has the Object interface, so ONLY the members defined in that interface are available for b. It's still JavaScript, so everything extends Object;
  • c extends Object, like anything else in TypeScript, but adds no members. Since type compatibility in TypeScript is based on structural subtyping, not nominal subtyping, c ends up being the same as b because they have the same interface: the Object interface.

And that's why

a.doSomething(); // Ok: the compiler trusts you on that
b.doSomething(); // Error: Object has no doSomething member
c.doSomething(); // Error: c neither has doSomething nor inherits it from Object

and why

a.toString(); // Ok: whatever, dude, have it your way
b.toString(); // Ok: toString is defined in Object
c.toString(); // Ok: c inherits toString from Object

So Object and {} are equivalents in TypeScript.

If you declare functions like these

function fa(param: any): void {}
function fb(param: Object): void {}

with the intention of accepting anything for param (maybe you're going to check types at run-time to decide what to do with it), remember that

  • inside fa, the compiler will let you do whatever you want with param;
  • inside fb, the compiler will only let you reference Object's members.

It is worth noting, though, that if param is supposed to accept multiple known types, a better approach is to declare it using union types, as in

function fc(param: string|number): void {}

Obviously, OO inheritance rules still apply, so if you want to accept instances of derived classes and treat them based on their base type, as in

interface IPerson {
    gender: string;
}

class Person implements IPerson {
    gender: string;
}

class Teacher extends Person {}

function func(person: IPerson): void {
    console.log(person.gender);
}

func(new Person());     // Ok
func(new Teacher());    // Ok
func({gender: 'male'}); // Ok
func({name: 'male'});   // Error: no gender..

the base type is the way to do it, not any. But that's OO, out of scope, I just wanted to clarify that any should only be used when you don't know whats coming, and for anything else you should annotate the correct type.

UPDATE:

Typescript 2.2 added an object type, which specifies that a value is a non-primitive: (i.e. not a number, string, boolean, symbol, undefined, or null).

Consider functions defined as:

function b(x: Object) {}
function c(x: {}) {}
function d(x: object) {}

x will have the same available properties within all of these functions, but it's a type error to call d with a primitive:

b("foo"); //Okay
c("foo"); //Okay
d("foo"); //Error: "foo" is a primitive

How to get all files under a specific directory in MATLAB?

This is a handy function for getting filenames, with the specified format (usually .mat) in a root folder!

    function filenames = getFilenames(rootDir, format)
        % Get filenames with specified `format` in given `foler` 
        %
        % Parameters
        % ----------
        % - rootDir: char vector
        %   Target folder
        % - format: char vector = 'mat'
        %   File foramt

        % default values
        if ~exist('format', 'var')
            format = 'mat';
        end

        format = ['*.', format];
        filenames = dir(fullfile(rootDir, format));
        filenames = arrayfun(...
            @(x) fullfile(x.folder, x.name), ...
            filenames, ...
            'UniformOutput', false ...
        );
    end

In your case, you can use the following snippet :)

filenames = getFilenames('D:/dic/**');
for i = 1:numel(filenames)
    filename = filenames{i};
    % do your job!
end

How to close IPython Notebook properly?

There isn't currently a better way to do it than Ctrl+C in the terminal.

We're thinking about how to have an explicit shutdown, but there's some tension between the notebook as a single-user application, where the user is free to stop it, and as a multi-user server, where only an admin should be able to stop it. We haven't quite worked out how to handle the differences yet.

(For future readers, this is the situation with 0.12 released and 0.13 in development.)

Update December 2017

The IPython Notebook has become the Jupyter Notebook. A recent version has added a jupyter notebook stop shell command which will shut down a server running on that system. You can pass the port number at the command line if it's not the default port 8888.

You can also use nbmanager, a desktop application which can show running servers and shut them down.

Finally, we are working on adding:

  • A config option to automatically shut down the server if you don't use it for a specified time.
  • A button in the user interface to shut the server down. (We know it's a bit crazy that it has taken this long. Changing UI is controversial.)

How do I update the element at a certain position in an ArrayList?

Let arrList be the ArrayList and newValue the new String, then just do:

arrList.set(5, newValue);

This can be found in the java api reference here.

Escaping ampersand in URL

This may help if someone want it in PHP

$variable ="candy_name=M&M";
$variable = str_replace("&", "%26", $variable);

How do I get the logfile from an Android device?

I have created a small library (.aar) to retrieve the logs by email. You can use it with Gmail accounts. It is pretty simple but works. You can get a copy from here

The site is in Spanish, but there is a PDF with an english version of the product description.

I hope it can help.

Convert Int to String in Swift

I prefer using String Interpolation

let x = 45
let string = "\(x)"

Each object has some string representation. This makes things simpler. For example if you need to create some String with multiple values. You can also do any math in it or use some conditions

let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"

Table-level backup

You probably have two options, as SQL Server doesn't support table backups. Both would start with scripting the table creation. Then you can either use the Script Table - INSERT option which will generate a lot of insert statements, or you can use Integration services (DTS with 2000) or similar to export the data as CSV or similar.

How to change cursor from pointer to finger using jQuery?

How do you change your cursor to the finger (like for clicking on links) instead of the regular pointer?

This is very simple to achieve using the CSS property cursor, no jQuery needed.

You can read more about in: CSS cursor property and cursor - CSS | MDN

_x000D_
_x000D_
.default {_x000D_
  cursor: default;_x000D_
}_x000D_
.pointer {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<a class="default" href="#">default</a>_x000D_
_x000D_
<a class="pointer" href="#">pointer</a>
_x000D_
_x000D_
_x000D_

How do I get the latest version of my code?

If the above commands didn't help you use this method:

  1. Go to the git archive where you have Fork
  2. Click Settings> Scroll down and click Delete this repository
  3. Confirm delete
  4. Fork again, and re-enter the git clone <url_git>
  5. You already have the latest version

React won't load local images

I faced the same issue, and I found out the problem was the location of my images. Instead of saving them into the src folder, you should store them in the public directory and have direct access.

Kudos.

build-impl.xml:1031: The module has not been deployed

Start your IDE with administrative privilege( Windows: right click and run as admin), so that it has read write access to tomact folder for deployment. It worked for me.

do <something> N times (declarative syntax)

// calls doSomething 42 times
Array( 42 ).join( "x" ).split( "" ).forEach( doSomething );

and

// creates 42 somethings
var somethings = Array( 42 ).join( "x" ).split( "" ).map( () => buildSomething(); );

or ( via https://stackoverflow.com/a/20066663/275501 )

Array.apply(null, {length: 42}).forEach( doSomething );

IE prompts to open or save json result from server

I changed the content-type to "text/html" instead of "application/json" server side before returning the response. Described it in a blog post, where other solutions have also been added:

http://blog.degree.no/2012/09/jquery-json-ie8ie9-treats-response-as-downloadable-file/

How to push JSON object in to array using javascript

You need to have the 'data' array outside of the loop, otherwise it will get reset in every loop and also you can directly push the json. Find the solution below:-

var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
    console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
    my_json = feed;
    console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
    data.push(my_json);
     //["2017-03-14T01:00:32Z", 33358, "4", "4", "0"]
}); 
console.log(data);

Node.js version on the command line? (not the REPL)

Just type npm version in your command line and it will display all the version details about node, npm, v8 engine etc.

enter image description here

preg_match(); - Unknown modifier '+'

Try this code:

preg_match('/[a-zA-Z]+<\/a>.$/', $lastgame, $match);
print_r($match);

Using / as a delimiter means you also need to escape it here, like so: <\/a>.

UPDATE

preg_match('/<a.*<a.*>(.*)</', $lastgame, $match);
echo'['.$match[1].']';

Might not be the best way...

Jest spyOn function called

You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const instance = app.instance()
    const spy = jest.spyOn(instance, 'myClickFunc')

    instance.forceUpdate();    

    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

Get values from other sheet using VBA

That will be (for you very specific example)

ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value=someval

OR

someVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value

So get a F1 click and read about Worksheets collection, which contains Worksheet objects, which in turn has a Cells collection, holding Cell objects...

Delete from two tables in one query

The OP is just missing the table aliases after the delete

DELETE t1, t2 
FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id 
WHERE t1.id = some_id

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

Even if I don't generally like the tone of John Gruber's Daring Fireball blog, his Larger iPhone Display Conjecture is well worth the read.

He guessed but got exactly right both the resolution in points and in pixels for both models, except that he did not (me neither) expect Apple to build a smaller resolution physical display and scale down (details are in @Tommy's answer).

The gist of it all is that one should stop thinking in terms of pixels and start thinking in terms of points (this has been the case for quite some time, it's not a recent invention) and resulting physical size of UI elements. In short, both new iPhone models improve in this regard as physically most elements remain the same size, you can just fit more of them on the screen (for each bigger screen you can fit more).

I'm just slightly disappointed they haven't kept mapping of internal resolution to actual screen resolution 1:1 for the bigger model.

Primary key or Unique index?

If something is a primary key, depending on your DB engine, the entire table gets sorted by the primary key. This means that lookups are much faster on the primary key because it doesn't have to do any dereferencing as it has to do with any other kind of index. Besides that, it's just theory.

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

Styling text input caret

If you are using a webkit browser you can change the color of the caret by following the next CSS snippet. I'm not sure if It's possible to change the format with CSS.

input,
textarea {
    font-size: 24px;
    padding: 10px;
    
    color: red;
    text-shadow: 0px 0px 0px #000;
    -webkit-text-fill-color: transparent;
}

input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
    color:
    text-shadow: none;
    -webkit-text-fill-color: initial;
}

Here is an example: http://jsfiddle.net/8k1k0awb/

How to debug .htaccess RewriteRule not working

Perhaps a more logical method would be to create a file (e.g. test.html), add some content and then try to set it as the index page:

DirectoryIndex test.html

For the most part, the .htaccess rule will override the Apache configuration where working at the directory/file level

Using JQuery hover with HTML image map

I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P

Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.

Error Code: 2013. Lost connection to MySQL server during query

Three things to be followed and make sure:

  1. Whether multiple queries show lost connection?
  2. how you use set query in MySQL?
  3. how delete + update query simultaneously?

Answers:

  1. Always try to remove definer as MySQL creates its own definer and if multiple tables involved for updation try to make a single query as sometimes multiple query shows lost connection
  2. Always SET value at the top but after DELETE if its condition doesn't involve SET value.
  3. Use DELETE FIRST THEN UPDATE IF BOTH OF THEM OPERATIONS ARE PERFORMED ON DIFFERENT TABLES

Excel telling me my blank cells aren't blank

My method is similar to Curt's suggestion above about saving it as a tab-delimited file and re-importing. It assumes that your data has only values without formulas. This is probably a good assumption because the problem of "bad" blanks is caused by the confusion between blanks and nulls -- usually in the data imported from some other place -- so there shouldn't be any formulas. My method is to parse in place -- very similar to saving as a text file and re-importing, but you can do this without closing and re-opening the file. It's under Data > Text-to-Columns > delimited > remove all parsing characters (can also choose Text if you want) > Finish. This should cause Excel to re-recognize your data from scratch or from text and recognize blanks as really blank. You can automate this in a subroutine:

Sub F2Enter_new()         
   Dim rInput As Range
   If Selection.Cells.Count > 1 Then Set rInput = Selection
   Set rInput = Application.InputBox(Title:="Select", prompt:="input range", _ 
                                     Default:=rInput.Address, Type:=8)
'   Application.EnableEvents = False: Application.ScreenUpdating = False
   For Each c In rInput.Columns
      c.TextToColumns Destination:=Range(c.Cells(1).Address), DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
      Semicolon:=False, Comma:=False, Space:=False, Other:=False, _
      FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
   Next c
   Application.EnableEvents = True: Application.ScreenUpdating = True
End Sub

You can also turn-on that one commented line to make this subroutine run "in the background". For this subroutine, it improves performance only slightly (for others, it can really help a lot). The name is F2Enter because the original manual method for fixing this "blanks" problem is to make Excel recognize the formula by pushing F2 and Enter.

How to set upload_max_filesize in .htaccess?

php_value upload_max_filesize 30M is correct.

You will have to contact your hosters -- some don't allow you to change values in php.ini

How do you push a tag to a remote repository using Git?

How can I push my tag to the remote repository so that all client computers can see it?

Run this to push mytag to your git origin (eg: GitHub or GitLab)

git push origin refs/tags/mytag

It's better to use the full "refspec" as shown above (literally refs/tags/mytag) just in-case mytag is actually v1.0.0 and is ambiguous (eg: because there's a branch also named v1.0.0).

Checking if an object is a given type in Swift

Swift 4.2 , In my case , using isKind function .

isKind(of:) Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.

  let items : [AnyObject] = ["A", "B" , ... ]
  for obj in items {
    if(obj.isKind(of: NSString.self)){
      print("String")
    }
  }

Readmore https://developer.apple.com/documentation/objectivec/nsobjectprotocol/1418511-iskind

How to create timer events using C++ 11?

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

Here you go, enjoy:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }

};

void test1(void)
{
    return;
}

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;
}

Outputs after two seconds:

101

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

I use the following customization in Laravel to:

  1. Default created_at to the current timestamp
  2. Update the timestamp when the record is updated

First, I'll create a file, helpers.php, in the root of Laravel and insert the following:

<?php

if (!function_exists('database_driver')) {
    function database_driver(): string
    {
        $connection = config('database.default');
        return config('database.connections.' . $connection . '.driver');
    }
}

if (!function_exists('is_database_driver')) {
    function is_database_driver(string $driver): bool
    {
        return $driver === database_driver();
    }
}

In composer.json, I'll insert the following into autoload. This allows composer to auto-discover helpers.php.

    "autoload": {
        "files": [
            "app/Services/Uploads/Processors/processor_functions.php",
            "app/helpers.php"
        ]
    },

I use the following in my Laravel models.

        if (is_database_driver('sqlite')) {
            $table->timestamps();
        } else {
            $table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('updated_at')
                ->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
        }

This allows my team to continue using sqlite for unit tests. ON UPDATE CURRENT_TIMESTAMP is a MySQL shortcut and is not available in sqlite.

Use tnsnames.ora in Oracle SQL Developer

This helped me:

Posted: 8/12/2011 4:54

Set tnsnames directory tools->Preferences->Database->advanced->Tnsnames Directory

https://forums.oracle.com/forums/thread.jspa?messageID=10020012&#10020012

Add space between two particular <td>s

None of the answers worked for me. The simplest way would be to add <td>s in between with width = 5px and background='white' or whatever the background color of the page is.

Again this will fail in case you have a list of <th>s representing table headers.

Which exception should I raise on bad/illegal argument combinations in Python?

It depends on what the problem with the arguments is.

If the argument has the wrong type, raise a TypeError. For example, when you get a string instead of one of those Booleans.

if not isinstance(save, bool):
    raise TypeError(f"Argument save must be of type bool, not {type(save)}")

Note, however, that in Python we rarely make any checks like this. If the argument really is invalid, some deeper function will probably do the complaining for us. And if we only check the boolean value, perhaps some code user will later just feed it a string knowing that non-empty strings are always True. It might save him a cast.

If the arguments have invalid values, raise ValueError. This seems more appropriate in your case:

if recurse and not save:
    raise ValueError("If recurse is True, save should be True too")

Or in this specific case, have a True value of recurse imply a True value of save. Since I would consider this a recovery from an error, you might also want to complain in the log.

if recurse and not save:
    logging.warning("Bad arguments in import_to_orm() - if recurse is True, so should save be")
    save = True

Android Camera Preview Stretched

F1Sher's solution is nice but sometimes doesn't work. Particularly, when your surfaceView doesn't cover whole screen. In this case you need to override onMeasure() method. I have copied my code here for your reference.

Since I measured surfaceView based on width then I have little bit white gap at the end of my screen that I filled it by design. You are able to fix this issue if you keep height and increase width by multiply it to ratio. However, it will squish surfaceView slightly.

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = "CameraPreview";

    private Context mContext;
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private List<Camera.Size> mSupportedPreviewSizes;
    private Camera.Size mPreviewSize;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mContext = context;
        mCamera = camera;

        // supported preview sizes
        mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
        for(Camera.Size str: mSupportedPreviewSizes)
                Log.e(TAG, str.width + "/" + str.height);

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // empty. surfaceChanged will take care of stuff
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        Log.e(TAG, "surfaceChanged => w=" + w + ", h=" + h);
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.
        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or reformatting changes here
        // start preview with new settings
        try {
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
            mCamera.setParameters(parameters);
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

        if (mSupportedPreviewSizes != null) {
            mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
        }

        if (mPreviewSize!=null) {
            float ratio;
            if(mPreviewSize.height >= mPreviewSize.width)
                ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
            else
                ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;

            // One of these methods should be used, second method squishes preview slightly
            setMeasuredDimension(width, (int) (width * ratio));
  //        setMeasuredDimension((int) (width * ratio), height);
        }
    }

    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) h / w;

        if (sizes == null)
            return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        for (Camera.Size size : sizes) {
            double ratio = (double) size.height / size.width;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;

            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }

        return optimalSize;
    }
}

iFrame onload JavaScript event

Use the iFrame's .onload function of JavaScript:

<iframe id="my_iframe" src="http://www.test.tld/">
    <script type="text/javascript">
        document.getElementById('my_iframe').onload = function() {
            __doPostBack('ctl00$ctl00$bLogout','');
        }
    </script>
    <!--OTHER STUFF-->
</iframe>

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

PHP redirects are better if you can as with the JavaScript one you're causing the client to load the page before the redirect, whereas with the PHP one it sends the proper header.

However the PHP shouldn't go in the <head>, it should go before any output is sent to the client, as to do otherwise will cause errors.

Using <meta> tags have the same issue as Javascript in causing the initial page to load before doing the redirect. Server-side redirects are almost always better, if you can use them.

Apply CSS styles to an element depending on its child elements

On top of @kp's answer:

I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).

But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the decisions in the logic and not based on a CSS state.

tl;dr; apply the a and b styles to the parent <div>, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).

<style>
  .parent            { height: 50px; }
  .parent div        { display: none; }
  .with-children     { height: 100px; }
  .with-children div { display: block; }
</style>

<div class="parent">
  <div>child</div>
</div>

<script>
  // to show the children
  $('.parent').addClass('with-children');
</script>

Easiest way to read/write a file's content in Python

with open('x.py') as f: s = f.read()

***grins***

How to add fonts to create-react-app based projects?

There are two options:

Using Imports

This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.

As described in “Adding Images, Fonts, and Files”, you need to have a CSS file imported from JS. For example, by default src/index.js imports src/index.css:

import './index.css';

A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in src/fonts/MyFont.woff, your index.css might include this:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(./fonts/MyFont.woff) format('woff');
}

Notice how we’re using a relative path starting with ./. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.

Normally this should be enough.

Using public Folder

If for some reason you prefer not to use the build pipeline, and instead do it the “classic way”, you can use the public folder and put your fonts there.

The downside of this approach is that the files don’t get hashes when you compile for production so you’ll have to update their names every time you change them, or browsers will cache the old versions.

If you want to do it this way, put the fonts somewhere into the public folder, for example, into public/fonts/MyFont.woff. If you follow this approach, you should put CSS files into public folder as well and not import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you’d have a file like public/index.css. You would have to manually add <link> to this stylesheet from public/index.html:

<link rel="stylesheet" href="%PUBLIC_URL%/index.css">

And inside of it, you would use the regular CSS notation:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(fonts/MyFont.woff) format('woff');
}

Notice how I’m using fonts/MyFont.woff as the path. This is because index.css is in the public folder so it will be served from the public path (usually it’s the server root, but if you deploy to GitHub Pages and set your homepage field to http://myuser.github.io/myproject, it will be served from /myproject). However fonts are also in the public folder, so they will be served from fonts relatively (either http://mywebsite.com/fonts or http://myuser.github.io/myproject/fonts). Therefore we use the relative path.

Note that since we’re avoiding the build pipeline in this example, it doesn’t verify that the file actually exists. This is why I don’t recommend this approach. Another problem is that our index.css file doesn’t get minified and doesn’t get a hash. So it’s going to be slower for the end users, and you risk the browsers caching old versions of the file.

 Which Way to Use?

Go with the first method (“Using Imports”). I only described the second one since that’s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you’re working around some issue.

Can someone explain how to implement the jQuery File Upload plugin?

Check out the Image drag and drop uploader with image preview using dropper jquery plugin.

HTML

<div class="target" width="78" height="100"><img /></div>

JS

$(".target").dropper({
    action: "upload.php",

}).on("start.dropper", onStart);
function onStart(e, files){
console.log(files[0]);

    image_preview(files[0].file).then(function(res){
$('.dropper-dropzone').empty();
//$('.dropper-dropzone').css("background-image",res.data);
 $('#imgPreview').remove();        
$('.dropper-dropzone').append('<img id="imgPreview"/><span style="display:none">Drag and drop files or click to select</span>');
var widthImg=$('.dropper-dropzone').attr('width');
        $('#imgPreview').attr({width:widthImg});
    $('#imgPreview').attr({src:res.data});

    })

}

function image_preview(file){
    var def = new $.Deferred();
    var imgURL = '';
    if (file.type.match('image.*')) {
        //create object url support
        var URL = window.URL || window.webkitURL;
        if (URL !== undefined) {
            imgURL = URL.createObjectURL(file);
            URL.revokeObjectURL(file);
            def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
        }
        //file reader support
        else if(window.File && window.FileReader)
        {
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function () {
                imgURL = reader.result;
                def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
            }
        }
        else {
            def.reject({status: 1001, message: 'File uploader not supported', data:imgURL, error: {}});
        }
    }
    else
        def.reject({status: 1002, message: 'File type not supported', error: {}});
    return def.promise();
}

$('.dropper-dropzone').mouseenter(function() {
 $( '.dropper-dropzone>span' ).css("display", "block");
});

$('.dropper-dropzone').mouseleave(function() {
 $( '.dropper-dropzone>span' ).css("display", "none");
});

CSS

.dropper-dropzone{
    width:78px;
padding:3px;
    height:100px;
position: relative;
}
.dropper-dropzone>img{
    width:78px;
    height:100px;
margin-top=0;
}

.dropper-dropzone>span {
    position: absolute;
    right: 10px;
    top: 20px;
color:#ccc;


}

.dropper .dropper-dropzone{

padding:3px !important    
}

Demo Jsfiddle

read subprocess stdout line by line

Indeed, if you sorted out the iterator then buffering could now be your problem. You could tell the python in the sub-process not to buffer its output.

proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)

becomes

proc = subprocess.Popen(['python','-u', 'fake_utility.py'],stdout=subprocess.PIPE)

I have needed this when calling python from within python.

How can Perl's print add a newline by default?

If Perl 5.10+ is not an option, here is a quick and dirty approximation. It's not exactly the same, since say has some magic when its first arg is a handle, but for printing to STDOUT:

sub say {print @_, "\n"}

say 'hello';

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

You basically are required to send some information with the request.

Try this,

$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n")); 
//Basically adding headers to the request
$context = stream_context_create($opts);
$html = file_get_contents($url,false,$context);
$html = htmlspecialchars($html);

This worked out for me

How to get first character of a string in SQL?

INPUT

STRMIDDLENAME
--------------
Aravind Chaterjee
Shivakumar
Robin Van Parsee

SELECT STRMIDDLENAME, 
CASE WHEN INSTR(STRMIDDLENAME,' ',1,2) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)||
SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,2)+1,1)
WHEN INSTR(STRMIDDLENAME,' ',1,1) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)
ELSE SUBSTR(STRMIDDLENAME,1,1)
END AS FIRSTLETTERS
FROM Dual;

OUTPUT
STRMIDDLENAME                    FIRSTLETTERS
---------                        -----------------
Aravind Chaterjee                AC           
Shivakumar                       S
Robin Van Parsee                 RVP

How to set the 'selected option' of a select dropdown list with jquery

One thing I don't think anyone has mentioned, and a stupid mistake I've made in the past (especially when dynamically populating selects). jQuery's .val() won't work for a select input if there isn't an option with a value that matches the value supplied.

Here's a fiddle explaining -> http://jsfiddle.net/go164zmt/

<select id="example">
    <option value="0">Test0</option>
    <option value="1">Test1</option>
</select>

$("#example").val("0");
alert($("#example").val());
$("#example").val("1");
alert($("#example").val());

//doesn't exist
$("#example").val("2");
//and thus returns null
alert($("#example").val());

Is there a way to cast float as a decimal without rounding and preserving its precision?

Try SELECT CAST(field1 AS DECIMAL(10,2)) field1 and replace 10,2 with whatever precision you need.

Check existence of directory and create if doesn't exist

I know this question was asked a while ago, but in case useful, the here package is really helpful for not having to reference specific file paths and making code more portable. It will automatically define your working directory as the one that your .Rproj file resides in, so the following will often suffice without having to define the file path to your working directory:

library(here)

if (!dir.exists(here(outputDir))) {dir.create(here(outputDir))}

What's the difference between isset() and array_key_exists()?

The two are not exactly the same. I couldn't remember the exact differences, but they are outlined very well in What's quicker and better to determine if an array key exists in PHP?.

The common consensus seems to be to use isset whenever possible, because it is a language construct and therefore faster. However, the differences should be outlined above.

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

Bootstrap carousel multiple frames at once

This is what worked for me. Very simple jQuery and CSS to make responsive carousel works independently of carousels on the same page. Highly customizable but basically a div with white-space nowrap containing a bunch of inline-block elements and put the last one at the beginning to move back or the first one to the end to move forward. Thank you insertAfter!

_x000D_
_x000D_
$('.carosel-control-right').click(function() {_x000D_
  $(this).blur();_x000D_
  $(this).parent().find('.carosel-item').first().insertAfter($(this).parent().find('.carosel-item').last());_x000D_
});_x000D_
$('.carosel-control-left').click(function() {_x000D_
  $(this).blur();_x000D_
  $(this).parent().find('.carosel-item').last().insertBefore($(this).parent().find('.carosel-item').first());_x000D_
});
_x000D_
@media (max-width: 300px) {_x000D_
  .carosel-item {_x000D_
    width: 100%;_x000D_
  }_x000D_
}_x000D_
@media (min-width: 300px) {_x000D_
  .carosel-item {_x000D_
    width: 50%;_x000D_
  }_x000D_
}_x000D_
@media (min-width: 500px) {_x000D_
  .carosel-item {_x000D_
    width: 33.333%;_x000D_
  }_x000D_
}_x000D_
@media (min-width: 768px) {_x000D_
  .carosel-item {_x000D_
    width: 25%;_x000D_
  }_x000D_
}_x000D_
.carosel {_x000D_
  position: relative;_x000D_
  background-color: #000;_x000D_
}_x000D_
.carosel-inner {_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  font-size: 0;_x000D_
}_x000D_
.carosel-item {_x000D_
  display: inline-block;_x000D_
}_x000D_
.carosel-control {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  padding: 15px;_x000D_
  box-shadow: 0 0 10px 0px rgba(0, 0, 0, 0.5);_x000D_
  transform: translateY(-50%);_x000D_
  border-radius: 50%;_x000D_
  color: rgba(0, 0, 0, 0.5);_x000D_
  font-size: 30px;_x000D_
  display: inline-block;_x000D_
}_x000D_
.carosel-control-left {_x000D_
  left: 15px;_x000D_
}_x000D_
.carosel-control-right {_x000D_
  right: 15px;_x000D_
}_x000D_
.carosel-control:active,_x000D_
.carosel-control:hover {_x000D_
  text-decoration: none;_x000D_
  color: rgba(0, 0, 0, 0.8);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="carosel" id="carosel1">_x000D_
  <a class="carosel-control carosel-control-left glyphicon glyphicon-chevron-left" href="#"></a>_x000D_
  <div class="carosel-inner">_x000D_
    <img class="carosel-item" src="http://placehold.it/500/bbbbbb/fff&amp;text=1" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/CCCCCC&amp;text=2" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/eeeeee&amp;text=3" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/f4f4f4&amp;text=4" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/fcfcfc/333&amp;text=5" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/f477f4/fff&amp;text=6" />_x000D_
  </div>_x000D_
  <a class="carosel-control carosel-control-right glyphicon glyphicon-chevron-right" href="#"></a>_x000D_
</div>_x000D_
<div class="carosel" id="carosel2">_x000D_
  <a class="carosel-control carosel-control-left glyphicon glyphicon-chevron-left" href="#"></a>_x000D_
  <div class="carosel-inner">_x000D_
    <img class="carosel-item" src="http://placehold.it/500/bbbbbb/fff&amp;text=1" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/CCCCCC&amp;text=2" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/eeeeee&amp;text=3" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/f4f4f4&amp;text=4" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/fcfcfc/333&amp;text=5" />_x000D_
    <img class="carosel-item" src="http://placehold.it/500/f477f4/fff&amp;text=6" />_x000D_
  </div>_x000D_
  <a class="carosel-control carosel-control-right glyphicon glyphicon-chevron-right" href="#"></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I check if a jQuery plugin is loaded?

for the plugins that doesn't use fn namespace (for example pnotify), this works:

if($.pluginname) {
    alert("plugin loaded");
} else {
    alert("plugin not loaded");
}

This doesn't work:

if($.fn.pluginname)

How to override the path of PHP to use the MAMP path?

The latest version of MAMP (Version 5+) offers an easy way to make the MAMP PHP version available to the command line. Just select "PHP" in the the side bar menu and check "Make this version available on the command line". Easy peasy! See attached screenshot:)

screenshot

Pointer to 2D arrays in C

Both your examples are equivalent. However, the first one is less obvious and more "hacky", while the second one clearly states your intention.

int (*pointer)[280];
pointer = tab1;

pointer points to an 1D array of 280 integers. In your assignment, you actually assign the first row of tab1. This works since you can implicitly cast arrays to pointers (to the first element).

When you are using pointer[5][12], C treats pointer as an array of arrays (pointer[5] is of type int[280]), so there is another implicit cast here (at least semantically).

In your second example, you explicitly create a pointer to a 2D array:

int (*pointer)[100][280];
pointer = &tab1;

The semantics are clearer here: *pointer is a 2D array, so you need to access it using (*pointer)[i][j].

Both solutions use the same amount of memory (1 pointer) and will most likely run equally fast. Under the hood, both pointers will even point to the same memory location (the first element of the tab1 array), and it is possible that your compiler will even generate the same code.

The first solution is "more advanced" since one needs quite a deep understanding on how arrays and pointers work in C to understand what is going on. The second one is more explicit.

How can I replace newlines using PowerShell?

In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:

$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")

Clarification: small files only folks! Please don't try this on your 40 GB log file :)

Creating watermark using html and css

Other solutions are great but they didn't take care of the fact that watermark shouldn't get selected on selection from the mouse. This fiddle takes care or that: https://jsfiddle.net/MiKr13/d1r4o0jg/9/

This will be better option for pdf or static html.

CSS:

#watermark {
  opacity: 0.2;
  font-size: 52px;
  color: 'black';
  background: '#ccc';
  position: absolute;
  cursor: default;
  user-select: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  right: 5px;
  bottom: 5px;
}

Stopping a CSS3 Animation on last frame

You're looking for:

animation-fill-mode: forwards;

More info on MDN and browser support list on canIuse.

Javascript Src Path

Use an relative path to the root of your site, for example:

If clock.js is on http://domain.com/javascript/clock.js

Include :

<script language="JavaScript" src="/javascript/clock.js"></script>

If it's on your domain root directory:

<script language="JavaScript" src="/clock.js"></script>

How to do this in Laravel, subquery where in

The following code worked for me:

$result=DB::table('tablename')
->whereIn('columnName',function ($query) {
                $query->select('columnName2')->from('tableName2')
                ->Where('columnCondition','=','valueRequired');

            })
->get();

Find the similarity metric between two strings

Solution #1: Python builtin

use SequenceMatcher from difflib

pros: native python library, no need extra package.
cons: too limited, there are so many other good algorithms for string similarity out there.

example :
>>> from difflib import SequenceMatcher
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75

Solution #2: jellyfish library

its a very good library with good coverage and few issues. it supports:
- Levenshtein Distance
- Damerau-Levenshtein Distance
- Jaro Distance
- Jaro-Winkler Distance
- Match Rating Approach Comparison
- Hamming Distance

pros: easy to use, gamut of supported algorithms, tested.
cons: not native library.

example:

>>> import jellyfish
>>> jellyfish.levenshtein_distance(u'jellyfish', u'smellyfish')
2
>>> jellyfish.jaro_distance(u'jellyfish', u'smellyfish')
0.89629629629629637
>>> jellyfish.damerau_levenshtein_distance(u'jellyfish', u'jellyfihs')
1

How to get exact browser name and version?

  • There is a conflict between (Safari) and (Opera) and (Chrome) !!!

  • The above codes couldn't work properly

This is my code, and it works very well without any conflict:

function ExactBrowserName()
{

$ExactBrowserNameUA=$_SERVER['HTTP_USER_AGENT'];

if (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")) {
    // OPERA
    $ExactBrowserNameBR="Opera";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "chrome/")) {
    // CHROME
    $ExactBrowserNameBR="Chrome";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "msie")) {
    // INTERNET EXPLORER
    $ExactBrowserNameBR="Internet Explorer";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "firefox/")) {
    // FIREFOX
    $ExactBrowserNameBR="Firefox";
} elseIf (strpos(strtolower($ExactBrowserNameUA), "safari/") and strpos(strtolower($ExactBrowserNameUA), "opr/")==false and strpos(strtolower($ExactBrowserNameUA), "chrome/")==false) {
    // SAFARI
    $ExactBrowserNameBR="Safari";
} else {
    // OUT OF DATA
    $ExactBrowserNameBR="OUT OF DATA";
};

return $ExactBrowserNameBR;
}

How to compare Boolean?

Using direct conditions (like ==, !=, !condition) will have a slight performance improvement over the .equals(condition) as in one case you are calling the method from an object whereas direct comparisons are performed directly.

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

A simple algorithm for polygon intersection

You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.

One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton

Alan Murta has a complete implementation of a polygon clipper GPC.

Edit:

Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.

Create a file from a ByteArrayOutputStream

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

Efficient way to remove keys with empty strings from a dict

BrenBarn's solution is ideal (and pythonic, I might add). Here is another (fp) solution, however:

from operator import itemgetter
dict(filter(itemgetter(1), metadata.items()))

How to restore the menu bar in Visual Studio Code

You have two options.

Option 1

Make the menu bar temporarily visible.

  • press Alt key and you will be able to see the menu bar

Option 2

Make the menu bar permanently visible.

Steps:

  1. Press F1
  2. Type user settings
  3. Press Enter
  4. Click on the { } (top right corner of the window) to open settings.json file see the screenshot
  5. Then in the settings.json file, change the value to the default "window.menuBarVisibility": "default" you can see a sample here (or remove this line from JSON file. If you remove any value from the settings.json file then it will use the default settings for those entries. So if you want to make everything to default settings then remove all entries in the settings.json file).

Git merge error "commit is not possible because you have unmerged files"

You need to do two things. First add the changes with

git add .
git stash  

git checkout <some branch>

It should solve your issue as it solved to me.

setContentView(R.layout.main); error

Simply:

  1. Right click on your project.

  2. Go to properties.

  3. Select android (second option in the Left panel).

  4. Click "add..." (in library), select your project.

  5. Click ok.

  6. And finally, clean your project.

If this doesn't work, make sure that "android-support-v7-appcompat" is in your Project Explorer.

If it isn't there, you can add it by importing a simple project from: C:/android-sdks\extras\android\support\v7\appcompat

Visual Studio : short cut Key : Duplicate Line

I use application link:AutoHotkey with below code saved in CommentDuplikateSaveClipboard.ahk file. You can edit/remove shortcuts it is easy.
I have link to this file "Shortcut to CommentDuplikateSaveClipboard.ahk" in Autostart in windows.
This script protect your clipboard.
If you are more curious you would add shortcuts to thisable/enable script.
I sometimes use very impressive Multi Clipboard script to easy handle with many clips saved on disk and use with CTRL+C,X,V to copy,paste,cut,next,previous,delete this,delete all.

;CommentDuplikateSaveClipboard.ahk

!c:: ; Alt+C === Duplicate Line
^d:: ; Ctrl+D
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{CTRLDOWN}c{CTRLUP}{END}{ENTER}{CTRLDOWN}v{CTRLUP}{HOME}
Clipboard := ClipSaved
ClipSaved =
return

!x:: ; Alt+X === Comment Duplicate Line
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{CTRLDOWN}c{CTRLUP}{LEFT}//{END}{ENTER}{CTRLDOWN}v{CTRLUP}{HOME}
Clipboard := ClipSaved
ClipSaved =
return

!z:: ; Alt+Z === Del uncomment  Line
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{UP}{END}{SHIFTUP}{DEL}{HOME}{DEL}{DEL}
Clipboard := ClipSaved
ClipSaved =
return

!d:: ; Alt+D === Delete line
Send, {END}{SHIFTDOWN}{UP}{END}{SHIFTUP}{DEL}
return

!s:: ; Alt+S === Swap lines
ClipSaved := ClipboardAll
Send, {END}{SHIFTDOWN}{UP}{END}{SHIFTUP}{CTRLDOWN}x{CTRLUP}{UP}{END}{CTRLDOWN}v{CTRLUP}{HOME}
Clipboard := ClipSaved
ClipSaved =
return

!a:: ; Alt+A === Comment this line, uncomment above
Send, {END}{HOME}//{UP}{HOME}{DEL}{DEL}
return

How to locate the git config file in Mac

The global Git configuration file is stored at $HOME/.gitconfig on all platforms.

However, you can simply open a terminal and execute git config, which will write the appropriate changes to this file. You shouldn't need to manually tweak .gitconfig, unless you particularly want to.

The character encoding of the HTML document was not declared

You have to change the file from .html to .php.

and add this following line

header('Content-Type: text/html; charset=utf-8');

How do I show my global Git configuration?

The shortest,

git config -l

shows all inherited values from: system, global and local

Android - Spacing between CheckBox and text

I don't know guys, but I tested

<CheckBox android:paddingLeft="8mm" and only moves the text to the right, not entire control.

It suits me fine.

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

What does -1 mean in numpy reshape?

Used to reshape an array.

Say we have a 3 dimensional array of dimensions 2 x 10 x 10:

r = numpy.random.rand(2, 10, 10) 

Now we want to reshape to 5 X 5 x 8:

numpy.reshape(r, shape=(5, 5, 8)) 

will do the job.

Note that, once you fix first dim = 5 and second dim = 5, you don't need to determine third dimension. To assist your laziness, python gives the option of -1:

numpy.reshape(r, shape=(5, 5, -1)) 

will give you an array of shape = (5, 5, 8).

Likewise,

numpy.reshape(r, shape=(50, -1)) 

will give you an array of shape = (50, 4)

You can read more at http://anie.me/numpy-reshape-transpose-theano-dimshuffle/

c++ string array initialization

Prior to C++11, you cannot initialise an array using type[]. However the latest c++11 provides(unifies) the initialisation, so you can do it in this way:

string* pStr = new string[3] { "hi", "there"};

See http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init

What is the difference between RTP or RTSP in a streaming server?

AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.

Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.

To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.

Pretty much everything can be transported through TCP though.

(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)

Spring profiles and testing

Can I recommend doing it this way, define your test like this:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    TestPreperationExecutionListener.class
    })
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {

  @Test
  public void testContext(){

  }

  @Configuration
  @PropertySource("classpath:/myprops.properties")
  @ImportResource({"classpath:context.xml" })
  public static class MyContextConfiguration{

  }
}

with the following content in myprops.properties file:

spring.profiles.active=localtest

With this your second properties file should get resolved:

META-INF/spring/config_${spring.profiles.active}.properties

Is not an enclosing class Java

What I would suggest is not converting the non-static class to a static class because in that case, your inner class can't access the non-static members of outer class.

Example :

class Outer
{
    class Inner
    {
        //...
    }
}

So, in such case, you can do something like:

Outer o = new Outer();
Outer.Inner obj = o.new Inner();

How to compile a c++ program in Linux?

Use g++

g++ -o hi hi.cpp

g++ is for C++, gcc is for C although with the -libstdc++ you can compile c++ most people don't do this.

Interpreting segfault messages

Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.

"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.

"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.

Java "lambda expressions not supported at this language level"

In IntelliJ IDEA:

In File Menu ? Project Structure ? Project, change Project Language Level to 8.0 - Lambdas, type annotations etc.

For Android 3.0+ Go File ? Project Structure ? Module ? app and In Properties Tab set Source Compatibility and Target Compatibility to 1.8 (Java 8)

Screenshot:

enter image description here

Use bash to find first folder name that contains a string

pattern="foo"
for _dir in *"${pattern}"*; do
    [ -d "${_dir}" ] && dir="${_dir}" && break
done
echo "${dir}"

This is better than the other shell solution provided because

  • it will be faster for huge directories as the pattern is part of the glob and not checked inside the loop
  • actually works as expected when there is no directory matching your pattern (then ${dir} will be empty)
  • it will work in any POSIX-compliant shell since it does not rely on the =~ operator (if you need this depends on your pattern)
  • it will work for directories containing newlines in their name (vs. find)

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

Div width 100% minus fixed amount of pixels

We can achieve this using flex-box very easily.

If we have three elements like Header, MiddleContainer and Footer. And we want to give some fixed height to Header and Footer. then we can write like this:

For React/RN(defaults are 'display' as flex and 'flexDirection' as column), in web css we'll have to specify the body container or container containing these as display: 'flex', flex-direction: 'column' like below:

    container-containing-these-elements: {
     display: flex,
     flex-direction: column
    }
    header: {
     height: 40,
    },
    middle-container: {
     flex: 1, // this will take the rest of the space available.
    },
    footer: {
     height: 100,
    }

Chrome javascript debugger breakpoints don't do anything?

I encountered similar problems in both chrome and firefox though it may not be the solution for your issue. Am sharing here in the hopes it may help others. I have encountered this situation before in other unrelated projects but never understood why until it cropped up again today.

Scenario:

I have one page that uses two bootstrap modals that come from the same source and one set of javascript files (blueimp's awesome jquery fileupload).

  • BS Modal 1 is rendered on page load (via php) and is always present on the page. It is used for adding a new related record. (CakePHP....think SalesForcey type stuff)

  • BS Modal 2 is used for editing existing related records and it's html content is pulled in from an ajax call and appended to the DOM via jQuery.

  • Javascript supporting both modals included via standard html <script> tags.

I noticed that breakpoints are only triggered on Modal 1. They do not work when the code is being executed on the dynamically added Modal 2, even though it is quite obvious that the code is indeed being evaluated and run. Alert boxes pop up, codey type things get executed and output follows the logic set forth in the code.

I have not dived deeper to investigate further because I'm pressed for time, but wanted to put it out there and give back to the community.

PS: I use SO all the time, but this is my first post, so go easy on me :-)

How can I get a Bootstrap column to span multiple rows?

I believe the part regarding how to span rows has been answered thoroughly (i.e. by nesting rows), but I also ran into the issue of my nested rows not filling their container. While flexbox and negative margins are an option, a much easier solution is to use the predefined h-50 class on the row containing boxes 2, 3, 4, and 5.

Note: I am using Bootstrap-4, I just wanted to share because I ran into the same problem and found this to be a more elegant solution :)

This version of the application is not configured for billing through Google Play

Conclusions in 2021

For all of you who concerned about debugging - You CAN run and debug and test the code in debug mode

Here's how you can test the process:

(This of course relies on the fact that you have already added and activated your products, and your code is ready for integration with those products)

  1. Add com.android.vending.BILLING to the manifest
  2. Upload signed apk to internal testing
  3. Add license testers (Play console -> Settings -> License testing) - If you use multiple accounts on your device and you're not sure which one to use, just add all of them as testers.
  4. Run the application, as you normally would, from Android Studio (* The application should have the same version code as the one you just uploaded to internal testing)

I did the above and it is working just fine.

Retrieving a Foreign Key value with django-rest-framework serializers

Just use a related field without setting many=True.

Note that also because you want the output named category_name, but the actual field is category, you need to use the source argument on the serializer field.

The following should give you the output you need...

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.RelatedField(source='category', read_only=True)

    class Meta:
        model = Item
        fields = ('id', 'name', 'category_name')

Safest way to get last record ID from a table

And if you mean select the ID of the last record inserted, its

SELECT @@IDENTITY FROM table

Update OpenSSL on OS X with Homebrew

If you're using Homebrew /usr/local/bin should already be at the front of $PATH or at least come before /usr/bin. If you now run brew link --force openssl in your terminal window, open a new one and run which openssl in it. It should now show openssl under /usr/local/bin.

Python calling method in class

The first argument of all methods is usually called self. It refers to the instance for which the method is being called.

Let's say you have:

class A(object):
    def foo(self):
        print 'Foo'

    def bar(self, an_argument):
        print 'Bar', an_argument

Then, doing:

a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'

There's nothing special about this being called self, you could do the following:

class B(object):
    def foo(self):
        print 'Foo'

    def bar(this_object):
        this_object.foo()

Then, doing:

b = B()
b.bar() # prints 'Foo'

In your specific case:

dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT) 

(As suggested in comments MissileDevice.RIGHT could be more appropriate here!)

You could declare all your constants at module level though, so you could do:

dangerous_device.move(RIGHT)

This, however, is going to depend on how you want your code to be organized!

What is the maximum recursion depth in Python, and how to increase it?

Of course Fibonacci numbers can be computed in O(n) by applying the Binet formula:

from math import floor, sqrt

def fib(n):                                                     
    return int(floor(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))+0.5))

As the commenters note it's not O(1) but O(n) because of 2**n. Also a difference is that you only get one value, while with recursion you get all values of Fibonacci(n) up to that value.

How can I make my flexbox layout take 100% vertical space?

You should set height of html, body, .wrapper to 100% (in order to inherit full height) and then just set a flex value greater than 1 to .row3 and not on the others.

_x000D_
_x000D_
.wrapper, html, body {
    height: 100%;
    margin: 0;
}
.wrapper {
    display: flex;
    flex-direction: column;
}
#row1 {
    background-color: red;
}
#row2 {
    background-color: blue;
}
#row3 {
    background-color: green;
    flex:2;
    display: flex;
}
#col1 {
    background-color: yellow;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col2 {
    background-color: orange;
    flex: 1 1;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col3 {
    background-color: purple;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
_x000D_
<div class="wrapper">
    <div id="row1">this is the header</div>
    <div id="row2">this is the second line</div>
    <div id="row3">
        <div id="col1">col1</div>
        <div id="col2">col2</div>
        <div id="col3">col3</div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

DEMO

How is a tag different from a branch in Git? Which should I use, here?

Branches are made of wood and grow from the trunk of the tree. Tags are made of paper (derivative of wood) and hang like Christmas Ornaments from various places in the tree.

Your project is the tree, and your feature that will be added to the project will grow on a branch. The answer is branch.

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Sorting string array in C#

Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here

Command to open file with git

We would always prefer to use vi -- to open a file

vi <filename> -- to open a file

How to retrieve a file from a server via SFTP?

Try edtFTPj/PRO, a mature, robust SFTP client library that supports connection pools and asynchronous operations. Also supports FTP and FTPS so all bases for secure file transfer are covered.

'too many values to unpack', iterating over a dict. key=>string, value=>list

data = (['President','George','Bush','is','.'],['O','B-PERSON','I-PERSON','O','O'])
corpus = []
for(doc,tags) in data:
    doc_tag = []
    for word,tag in zip(doc,tags):
        doc_tag.append((word,tag))
        corpus.append(doc_tag)
        print(corpus)

What is the argument for printf that formats a long?

It depends, if you are referring to unsigned long the formatting character is "%lu". If you're referring to signed long the formatting character is "%ld".

Dynamically replace img src attribute with jQuery

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

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

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

Example:

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

Convert object to JSON string in C#

Use .net inbuilt class JavaScriptSerializer

  JavaScriptSerializer js = new JavaScriptSerializer();
  string json = js.Serialize(obj);

How to import Maven dependency in Android Studio/IntelliJ?

Android Studio 3

The answers that talk about Maven Central are dated since Android Studio uses JCenter as the default repository center now. Your project's build.gradle file should have something like this:

repositories {
    google()
    jcenter()
}

So as long as the developer has their Maven repository there (which Picasso does), then all you would have to do is add a single line to the dependencies section of your app's build.gradle file.

dependencies {
    // ...
    implementation 'com.squareup.picasso:picasso:2.5.2'
}

MessageBox with YesNoCancel - No & Cancel triggers same event

This should work fine:

Dim result As DialogResult = MessageBox.Show("message", "caption", MessageBoxButtons.YesNoCancel)
If result = DialogResult.Cancel Then
    MessageBox.Show("Cancel pressed")
ElseIf result = DialogResult.No Then
    MessageBox.Show("No pressed")
ElseIf result = DialogResult.Yes Then
    MessageBox.Show("Yes pressed")
End If

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

If you have to use the older client, here is my experience.

We are running a 32bit server so the development machines run the 32bit client. We run the 11.1 install, 11.2 gets the error. Once you have installed the 11.2 version you have to manually delete the files Oracle.Web.dll and System.Data.OracleClient.dll from the %windir%\Microsoft.NET\Framework\v2.0.50727, reinstall 11.1, then register the dlls with gacutil.exe.

This fixed the issue with my systems.

jquery save json data object in cookie

Try this one: https://github.com/tantau-horia/jquery-SuperCookie

Quick Usage:

create - create cookie

check - check existance

verify - verify cookie value if JSON

check_index - verify if index exists in JSON

read_values - read cookie value as string

read_JSON - read cookie value as JSON object

read_value - read value of index stored in JSON object

replace_value - replace value from a specified index stored in JSON object

remove_value - remove value and index stored in JSON object

Just use:

$.super_cookie().create("name_of_the_cookie",name_field_1:"value1",name_field_2:"value2"});
$.super_cookie().read_json("name_of_the_cookie");

How to "properly" print a list?

Here's an interactive session showing some of the steps in @TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)

Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

jQuery DataTable overflow and text-wrapping issues

Try adding td {word-wrap: break-word;} to the css and see if it fixes it.

Change background colour for Visual Studio

basically same for VS2012e: TOOLS > Options > Environment > Fonts and Colors > Display Items: Plain Text > "Item background" dropdown selector

REST API Best practice: How to accept list of parameter values as input

The standard way to pass a list of values as URL parameters is to repeat them:

http://our.api.com/Product?id=101404&id=7267261

Most server code will interpret this as a list of values, although many have single value simplifications so you may have to go looking.

Delimited values are also okay.

If you are needing to send JSON to the server, I don't like seeing it in in the URL (which is a different format). In particular, URLs have a size limitation (in practice if not in theory).

The way I have seen some do a complicated query RESTfully is in two steps:

  1. POST your query requirements, receiving back an ID (essentially creating a search criteria resource)
  2. GET the search, referencing the above ID
  3. optionally DELETE the query requirements if needed, but note that they requirements are available for reuse.