Programs & Examples On #Ora 00900

The statement that you've tried to execute is not a valid SQL statement.

How to execute an oracle stored procedure?

I use oracle 12 and it tell me that if you need to invoke the procedure then use call keyword. In your case it should be:

begin
  call temp_proc;
end;

When is std::weak_ptr useful?

When using pointers it's important to understand the different types of pointers available and when it makes sense to use each one. There are four types of pointers in two categories as follows:

  • Raw pointers:
    • Raw Pointer [ i.e. SomeClass* ptrToSomeClass = new SomeClass(); ]
  • Smart pointers:
    • Unique Pointers [ i.e.
      std::unique_ptr<SomeClass> uniquePtrToSomeClass ( new SomeClass() );
      ]
    • Shared Pointers [ i.e.
      std::shared_ptr<SomeClass> sharedPtrToSomeClass ( new SomeClass() );
      ]
    • Weak Pointers [ i.e.
      std::weak_ptr<SomeClass> weakPtrToSomeWeakOrSharedPtr ( weakOrSharedPtr );
      ]

Raw pointers (sometimes referred to as "legacy pointers", or "C pointers") provide 'bare-bones' pointer behavior and are a common source of bugs and memory leaks. Raw pointers provide no means for keeping track of ownership of the resource and developers must call 'delete' manually to ensure they are not creating a memory leak. This becomes difficult if the resource is shared as it can be challenging to know whether any objects are still pointing to the resource. For these reasons, raw pointers should generally be avoided and only used in performance-critical sections of the code with limited scope.

Unique pointers are a basic smart pointer that 'owns' the underlying raw pointer to the resource and is responsible for calling delete and freeing the allocated memory once the object that 'owns' the unique pointer goes out of scope. The name 'unique' refers to the fact that only one object may 'own' the unique pointer at a given point in time. Ownership may be transferred to another object via the move command, but a unique pointer can never be copied or shared. For these reasons, unique pointers are a good alternative to raw pointers in the case that only one object needs the pointer at a given time, and this alleviates the developer from the need to free memory at the end of the owning object's lifecycle.

Shared pointers are another type of smart pointer that are similar to unique pointers, but allow for many objects to have ownership over the shared pointer. Like unique pointer, shared pointers are responsible for freeing the allocated memory once all objects are done pointing to the resource. It accomplishes this with a technique called reference counting. Each time a new object takes ownership of the shared pointer the reference count is incremented by one. Similarly, when an object goes out of scope or stops pointing to the resource, the reference count is decremented by one. When the reference count reaches zero, the allocated memory is freed. For these reasons, shared pointers are a very powerful type of smart pointer that should be used anytime multiple objects need to point to the same resource.

Finally, weak pointers are another type of smart pointer that, rather than pointing to a resource directly, they point to another pointer (weak or shared). Weak pointers can't access an object directly, but they can tell whether the object still exists or if it has expired. A weak pointer can be temporarily converted to a shared pointer to access the pointed-to object (provided it still exists). To illustrate, consider the following example:

  • You are busy and have overlapping meetings: Meeting A and Meeting B
  • You decide to go to Meeting A and your co-worker goes to Meeting B
  • You tell your co-worker that if Meeting B is still going after Meeting A ends, you will join
  • The following two scenarios could play out:
    • Meeting A ends and Meeting B is still going, so you join
    • Meeting A ends and Meeting B has also ended, so you can't join

In the example, you have a weak pointer to Meeting B. You are not an "owner" in Meeting B so it can end without you, and you do not know whether it ended or not unless you check. If it hasn't ended, you can join and participate, otherwise, you cannot. This is different than having a shared pointer to Meeting B because you would then be an "owner" in both Meeting A and Meeting B (participating in both at the same time).

The example illustrates how a weak pointer works and is useful when an object needs to be an outside observer, but does not want the responsibility of sharing ownership. This is particularly useful in the scenario that two objects need to point to each other (a.k.a. a circular reference). With shared pointers, neither object can be released because they are still 'strongly' pointed to by the other object. When one of the pointers is a weak pointer, the object holding the weak pointer can still access the other object when needed, provided it still exists.

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

How do I print the percent sign(%) in c

Use "%%". The man page describes this requirement:

% A '%' is written. No argument is converted. The complete conversion specification is '%%'.

PostgreSQL naming conventions

There isn't really a formal manual, because there's no single style or standard.

So long as you understand the rules of identifier naming you can use whatever you like.

In practice, I find it easier to use lower_case_underscore_separated_identifiers because it isn't necessary to "Double Quote" them everywhere to preserve case, spaces, etc.

If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42" you'd be free to do that, though it'd be pain to type everywhere.

The main things to understand are:

  • Unless double-quoted, identifiers are case-folded to lower-case, so MyTable, MYTABLE and mytable are all the same thing, but "MYTABLE" and "MyTable" are different;

  • Unless double-quoted:

    SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).

  • You must double-quote keywords if you wish to use them as identifiers.

In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with" doesn't mean you should.

Capture Image from Camera and Display in Activity

Here you can open camera or gallery and set the selected image into imageview

private static final String IMAGE_DIRECTORY = "/YourDirectName";
private Context mContext;
private CircleImageView circleImageView;  // imageview
private int GALLERY = 1, CAMERA = 2;

Add permissions in manifest

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

In onCreate()

    requestMultiplePermissions(); // check permission 

    circleImageView = findViewById(R.id.profile_image);
    circleImageView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showPictureDialog();
        }
    });

Show options dialog box (to select image from camera or gallery)

private void showPictureDialog() {
    AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
    pictureDialog.setTitle("Select Action");
    String[] pictureDialogItems = {"Select photo from gallery", "Capture photo from camera"};
    pictureDialog.setItems(pictureDialogItems,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            choosePhotoFromGallary();
                            break;
                        case 1:
                            takePhotoFromCamera();
                            break;
                    }
                }
            });
    pictureDialog.show();
}

Get photo from Gallery

public void choosePhotoFromGallary() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, GALLERY);
}

Get photo from Camera

private void takePhotoFromCamera() {
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAMERA);
}

Once the image is get selected or captured then ,

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_CANCELED) {
        return;
    }
    if (requestCode == GALLERY) {
        if (data != null) {
            Uri contentURI = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
                String path = saveImage(bitmap);
                Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
                circleImageView.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
            }
        }

    } else if (requestCode == CAMERA) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        circleImageView.setImageBitmap(thumbnail);
        saveImage(thumbnail);
        Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show();
    }
}

Now its time to store the picture

public String saveImage(Bitmap myBitmap) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
    File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
    if (!wallpaperDirectory.exists()) {  // have the object build the directory structure, if needed.
        wallpaperDirectory.mkdirs();
    }

    try {
        File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        MediaScannerConnection.scanFile(this,
                new String[]{f.getPath()},
                new String[]{"image/jpeg"}, null);
        fo.close();
        Log.d("TAG", "File Saved::---&gt;" + f.getAbsolutePath());

        return f.getAbsolutePath();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return "";
}

Request permission

    private void requestMultiplePermissions() {
    Dexter.withActivity(this)
            .withPermissions(
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {  // check if all permissions are granted
                        Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
                    }

                    if (report.isAnyPermissionPermanentlyDenied()) { // check for permanent denial of any permission
                        // show alert dialog navigating to Settings
                        //openSettingsDialog();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).
            withErrorListener(new PermissionRequestErrorListener() {
                @Override
                public void onError(DexterError error) {
                    Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
                }
            })
            .onSameThread()
            .check();
}

Git push error pre-receive hook declined

Following resolved problem in my local machine:

A. First, ensure that you are using the correct log on details to connect to Bitbucket Server (ie. a username/password/SSH key that belongs to you) 

B. Then, ensure that the name/email address is correctly set in your local Git configuration: Set your local Git configuration for the account that you are trying to push under (the check asserts that you are the person who committed the files) * Note that this is case sensitive, both for name and email address * It is also space sensitive - some company accounts have extra spaces/characters in their name eg. "Contractor/ space space(LDN)".  You must include the same number of spaces in your configuration as on Bitbucket Server.  Check this in Notepad if stuck.

C. If you were using the wrong account, simply switch your account credentials (username/password/SSH key) and try pushing again.

D. Else, if your local configuration incorrect you will need to amend it

For MAC

open -a TextEdit.app ~/.gitconfig

NOTE: You will have to fix up the old commits that you were trying to push.

  1. Amend your last commit:

    > git commit --amend --reset-author
    
      
    <save and quit the commit file text editor that opens, if Vim then
    :wq to save and quit>
    
  2. Try re-pushing your commits:

    > git push
    

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

Getting coordinates of marker in Google Maps API

Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:

            function map_init() {
            var lt=48.451778;
            var lg=31.646305;

            var myLatlng = new google.maps.LatLng(lt,lg);
            var mapOptions = {
                center: new google.maps.LatLng(lt,lg),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map'),mapOptions);   
            var marker = new google.maps.Marker({
                position:myLatlng,
                map:map,
                draggable:true
            });

            google.maps.event.addListener(
                marker,
                'drag',
                function() {
                    document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
                    document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
                    document.getElementById('zoom').innerHTML = mapObject.getZoom();

                    // Dynamically show it somewhere if needed
                    $(".x").text(marker.position.lat().toFixed(6));
                    $(".y").text(marker.position.lng().toFixed(6));
                    $(".z").text(map.getZoom());

                }
            );                  
            }

Replace a string in a file with nodejs

On Linux or Mac, keep is simple and just use sed with the shell. No external libraries required. The following code works on Linux.

const shell = require('child_process').execSync
shell(`sed -i "s!oldString!newString!g" ./yourFile.js`)

The sed syntax is a little different on Mac. I can't test it right now, but I believe you just need to add an empty string after the "-i":

const shell = require('child_process').execSync
shell(`sed -i "" "s!oldString!newString!g" ./yourFile.js`)

The "g" after the final "!" makes sed replace all instances on a line. Remove it, and only the first occurrence per line will be replaced.

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

How do you add input from user into list in Python

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

Mixing C# & VB In The Same Project

I don't see how you can compile a project with the C# compiler (or the VB compiler) and not have it balk at the wrong language for the compiler.

Keep your C# code in a separate project from your VB project. You can include these projects into the same solution.

Disable same origin policy in Chrome

Used below command in Ubuntu to start chrome (disable same origin policy and open chrome in detached mode):

nohup google-chrome --disable-web-security --user-data-dir='/tmp' &

Xcode 6 Storyboard the wrong size?

While Asif Bilal's answer is a simpler solution that doesn't involve Size Classes (which were introduced in iOS 8.) it is strongly recommended you to get used to size classes as they are the future, and you will eventually jump in anyway at some point."


You probably haven't added the layout constraints.

Select your label, tap the layout constraints button on the bottom:

enter image description here

On that menu add width and height (it should NOT be the same as mine) by checking their checkbox and click add constraints. Then Control-drag your label to your main view, and then when you de-click, you should have the options to center horizontally and vertically in container. Add both, and you should be set up.

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

I have this issue in SOAP-UI and no one solution above dont helped me.

Proper solution for me was to add

-Dsoapui.sslcontext.algorithm=TLSv1

in vmoptions file (in my case it was ...\SoapUI-5.4.0\bin\SoapUI-5.4.0.vmoptions)

Difference between == and ===

!== and === are identity operators and are used to determine if two objects have the same reference.

Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

How to open a web server port on EC2 instance

Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".

Go to the "Network & Security" -> Security Group settings in the left hand navigation

enter image description here Find the Security Group that your instance is apart of Click on Inbound Rules enter image description here Use the drop down and add HTTP (port 80) enter image description here Click Apply and enjoy

How can I catch all the exceptions that will be thrown through reading and writing a file?

It is bad practice to catch Exception -- it's just too broad, and you may miss something like a NullPointerException in your own code.

For most file operations, IOException is the root exception. Better to catch that, instead.

What does body-parser do with express?

In order to get access to the post data we have to use body-parser. Basically what the body-parser is which allows express to read the body and then parse that into a Json object that we can understand.

Call a python function from jinja2

Never saw such simple way at official docs or at stack overflow, but i was amazed when found this:

# jinja2.__version__ == 2.8
from jinja2 import Template

def calcName(n, i):
    return ' '.join([n] * i)

template = Template("Hello {{ calcName('Gandalf', 2) }}")

template.render(calcName=calcName)
# or
template.render({'calcName': calcName})

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

I'm not sure about HQL, but in JPA you just call the query's setParameter with the parameter and collection.

Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);

where names is the collection of names you're searching for

Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");

Calculating Covariance with Python and Numpy

Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:

Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)

or like this:

Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)

Python display text with font & color?

There are 2 possibilities. In either case PyGame has to be initialized by pygame.init.

import pygame
pygame.init()

Use either the pygame.font module and create a pygame.font.SysFont or pygame.font.Font object. render() a pygame.Surface with the text and blit the Surface to the screen:

my_font = pygame.font.SysFont(None, 50)
text_surface = myfont.render("Hello world!", True, (255, 0, 0))
screen.blit(text_surface, (10, 10))

Or use the pygame.freetype module. Create a pygame.freetype.SysFont() or pygame.freetype.Font object. render() a pygame.Surface with the text or directly render_to() the text to the screen:

my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)
my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))

See also Text and font


Minimal pygame.font example: repl.it/@Rabbid76/PyGame-Text

import pygame

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

font = pygame.font.SysFont(None, 100)
text = font.render('Hello World', True, (255, 0, 0))

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    window.blit(text, text.get_rect(center = window.get_rect().center))
    pygame.display.flip()

pygame.quit()
exit()

Minimal pygame.freetype example: repl.it/@Rabbid76/PyGame-FreeTypeText

import pygame
import pygame.freetype

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

ft_font = pygame.freetype.SysFont('Times New Roman', 80)

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    text_rect = ft_font.get_rect('Hello World')
    text_rect.center = window.get_rect().center
    ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0))
    pygame.display.flip()

pygame.quit()
exit()

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

In my case, on commenting out the

<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> 

in the web.config file was throwing "Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata".

Rownum in postgresql

I have just tested in Postgres 9.1 a solution which is close to Oracle ROWNUM:

select row_number() over() as id, t.*
from information_schema.tables t;

"Invalid JSON primitive" in Ajax processing

As noted by jitter, the $.ajax function serializes any object/array used as the data parameter into a url-encoded format. Oddly enough, the dataType parameter only applies to the response from the server - and not to any data in the request.

After encountering the same problem I downloaded and used the jquery-json plugin to correctly encode the request data to the ScriptService. Then, used the $.toJSON function to encode the desired arguments to send to the server:

$.ajax({
    type: "POST",
    url: "EditUserProfile.aspx/DeleteRecord",
    data: $.toJSON(obj),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
    ....
});

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

JavaScript loop through json array?

Since i already started looking into it:

var data = [{
    "id": "1",
    "msg": "hi",
    "tid": "2013-05-05 23:35",
    "fromWho": "[email protected]"
}, {
    "id": "2",
    "msg": "there",
    "tid": "2013-05-05 23:45",
    "fromWho": "[email protected]"
}]

And this function

var iterateData =function(data){   for (var key in data) {
       if (data.hasOwnProperty(key)) {
          console.log(data[key].id);
       }
    }};

You can call it like this

iterateData(data); // write 1 and 2 to the console

Update after Erics comment

As eric pointed out a for in loop for an array can have unexpected results. The referenced question has a lengthy discussion about pros and cons.

Test with for(var i ...

But it seems that the follwing is quite save:

for(var i = 0; i < array.length; i += 1)

Although a test in chrome had the following result

var ar = [];
ar[0] = "a"; 
ar[1] = "b";
ar[4] = "c";

function forInArray(ar){ 
     for(var i = 0; i < ar.length; i += 1) 
        console.log(ar[i]);
}

// calling the function
// returns a,b, undefined, undefined, c, undefined
forInArray(ar); 

Test with .forEach()

At least in chrome 30 this works as expected

var logAr = function(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
ar.forEach(logAr); // returns a[0] = a, a[1] = b, a[4] = c

Links

VB.NET - How to move to next item a For Each Loop?

For Each I As Item In Items
    If I = x Then Continue For

    ' Do something
Next

How can I start PostgreSQL on Windows?

If you are getting an error "psql.exe' is not recognized as an internal or external command,... "

There can be : Causes

  • System is unable to find the psql.exe tool, because the path to this tool is not specified in the system environment variable PATH

or - PostgreSQL Database client not installed on your PC

Since you have already installed PostgreSQL the latter can not be the issue(assuming everything is installed as expected)

In order to fix the first one "please specify the full path to the bin directory in the PostgreSQL installation folder, where this tool resides."

For example

Path: "C:\Program Files\PostgreSQL\10\bin"

Adjusting the Xcode iPhone simulator scale and size

You can't have 1:1 ratio.

However you can scale it from the iOS Simulator > Window > Scale menu.

LinearLayout not expanding inside a ScrollView

Found the solution myself in the end. The problem was not with the LinearLayout, but with the ScrollView (seems weird, considering the fact that the ScrollView was expanding, while the LinearLayout wasn't).

The solution was to use android:fillViewport="true" on the ScrollView.

Angular2 RC6: '<component> is not a known element'

I received this error when I imported Module A into Module B, and then tried to use a component from Module A in Module B.

The solution is to declare that component in the exports array.

@NgModule({
  declarations: [
    MyComponent
  ],
  exports: [
    MyComponent
  ]
})
export class ModuleA {}
@NgModule({
  imports: [
    ModuleA
  ]
})
export class ModuleB {}

Check if input is integer type in C

I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!

#include<stdio.h>

int iFunctErrorCheck(int iLowerBound, int iUpperBound){

int iUserInput=0;
while (iUserInput==0){
    scanf("%i", &iUserInput);
    if (iUserInput==0){
        printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
        getchar();
    }
    if ((iUserInput!=0) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
        printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
        iUserInput=0;
    }
}
return iUserInput;
}

How to handle back button in activity

A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button

Setting Camera Parameters in OpenCV/Python

I wasn't able to fix the problem OpenCV either, but a video4linux (V4L2) workaround does work with OpenCV when using Linux. At least, it does on my Raspberry Pi with Rasbian and my cheap webcam. This is not as solid, light and portable as you'd like it to be, but for some situations it might be very useful nevertheless.

Make sure you have the v4l2-ctl application installed, e.g. from the Debian v4l-utils package. Than run (before running the python application, or from within) the command:

v4l2-ctl -d /dev/video1 -c exposure_auto=1 -c exposure_auto_priority=0 -c exposure_absolute=10

It overwrites your camera shutter time to manual settings and changes the shutter time (in ms?) with the last parameter to (in this example) 10. The lower this value, the darker the image.

Call a Vue.js component method from outside the component

Say you have a child_method() in the child component:

export default {
    methods: {
        child_method () {
            console.log('I got clicked')
        }
    }
}

Now you want to execute the child_method from parent component:

<template>
    <div>
        <button @click="exec">Execute child component</button>
        <child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
    </div>
</template>

export default {
    methods: {
        exec () { //accessing the child component instance through $refs
            this.$refs.child.child_method() //execute the method belongs to the child component
        }
    }
}

If you want to execute a parent component method from child component:

this.$parent.name_of_method()

NOTE: It is not recommended to access the child and parent component like this.

Instead as best practice use Props & Events for parent-child communication.

If you want communication between components surely use vuex or event bus

Please read this very helpful article


Very simple C# CSV reader

Here's a simple function I made. It accepts a string CSV line and returns an array of fields:

It works well with Excel generated CSV files, and many other variations.

    public static string[] ParseCsvRow(string r)
    {

        string[] c;
        string t;
        List<string> resp = new List<string>();
        bool cont = false;
        string cs = "";

        c = r.Split(new char[] { ',' }, StringSplitOptions.None);

        foreach (string y in c)
        {
            string x = y;


            if (cont)
            {
                // End of field
                if (x.EndsWith("\""))
                {
                    cs += "," + x.Substring(0, x.Length - 1);
                    resp.Add(cs);
                    cs = "";
                    cont = false;
                    continue;

                }
                else
                {
                    // Field still not ended
                    cs += "," + x;
                    continue;
                }
            }

            // Fully encapsulated with no comma within
            if (x.StartsWith("\"") && x.EndsWith("\""))
            {
                if ((x.EndsWith("\"\"") && !x.EndsWith("\"\"\"")) && x != "\"\"")
                {
                    cont = true;
                    cs = x;
                    continue;
                }

                resp.Add(x.Substring(1, x.Length - 2));
                continue;
            }

            // Start of encapsulation but comma has split it into at least next field
            if (x.StartsWith("\"") && !x.EndsWith("\""))
            {
                cont = true;
                cs += x.Substring(1);
                continue;
            }

            // Non encapsulated complete field
            resp.Add(x);

        }

        return resp.ToArray();

    }

Why does git status show branch is up-to-date when changes exist upstream?

in this case use git add and integrate all pending files and then use git commit and then git push

git add - integrate all pedent files

git commit - save the commit

git push - save to repository

handle textview link click in my android app

Coming at this almost a year later, there's a different manner in which I solved my particular problem. Since I wanted the link to be handled by my own app, there is a solution that is a bit simpler.

Besides the default intent filter, I simply let my target activity listen to ACTION_VIEW intents, and specifically, those with the scheme com.package.name

<intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="com.package.name" />  
</intent-filter>

This means that links starting with com.package.name:// will be handled by my activity.

So all I have to do is construct a URL that contains the information I want to convey:

com.package.name://action-to-perform/id-that-might-be-needed/

In my target activity, I can retrieve this address:

Uri data = getIntent().getData();

In my example, I could simply check data for null values, because when ever it isn't null, I'll know it was invoked by means of such a link. From there, I extract the instructions I need from the url to be able to display the appropriate data.

How do I display the current value of an Android Preference in the Preference summary?

Here is a working solution for all EditTextPreferences inside of a PreferenceFragment based on @tdeveaux answer:

public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
    private static final String TAG = "SettingsFragment";

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onResume () {
        super.onResume();

        for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); ++i) {
            Preference preference = getPreferenceScreen().getPreference(i);
            updatePreference(preference);
        }
    }

    @Override
    public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) {
        updatePreference(findPreference(key));
    }

    private void updatePreference (Preference preference) {
        if (preference instanceof EditTextPreference) {
            EditTextPreference editTextPreference = (EditTextPreference)preference;
            editTextPreference.setSummary(editTextPreference.getText());
        }
    }
}

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

In this case a[4] is the 5th integer in the array a, ap is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap now holds 45 and when you try to de-reference it (by doing *ap) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.

You should do ap = &(a[4]); or ap = a + 4;

In c array names decays to pointer, so a points to the 1st element of the array.
In this way, a is equivalent to &(a[0]).

Function overloading in Javascript - Best practices

Since JavaScript doesn't have function overload options object can be used instead. If there are one or two required arguments, it's better to keep them separate from the options object. Here is an example on how to use options object and populated values to default value in case if value was not passed in options object.

    function optionsObjectTest(x, y, opts) {
        opts = opts || {}; // default to an empty options object

        var stringValue = opts.stringValue || "string default value";
        var boolValue = !!opts.boolValue; // coerces value to boolean with a double negation pattern
        var numericValue = opts.numericValue === undefined ? 123 : opts.numericValue;

        return "{x:" + x + ", y:" + y + ", stringValue:'" + stringValue + "', boolValue:" + boolValue + ", numericValue:" + numericValue + "}";

}

here is an example on how to use options object

How can I correctly format currency using jquery?

Try regexp currency with jQuery (no plugin):

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('#test').click(function() {_x000D_
    TESTCURRENCY = $('#value').val().toString().match(/(?=[\s\d])(?:\s\.|\d+(?:[.]\d+)*)/gmi);_x000D_
    if (TESTCURRENCY.length <= 1) {_x000D_
      $('#valueshow').val(_x000D_
        parseFloat(TESTCURRENCY.toString().match(/^\d+(?:\.\d{0,2})?/))_x000D_
      );_x000D_
    } else {_x000D_
      $('#valueshow').val('Invalid a value!');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="text" value="12345.67890" id="value">_x000D_
<input type="button" id="test" value="CLICK">_x000D_
<input type="text" value="" id="valueshow">
_x000D_
_x000D_
_x000D_

Edit: New check a value to valid/invalid

Passing vector by reference

void do_something(int el, std::vector<int> **arr)

should be

void do_something(int el, std::vector<int>& arr)
{
    arr.push_back(el);
}

Pass by reference has been simplified to use the & in C++.

Get month name from number

8.1. datetime — Basic date and time types — Python 2.7.17 documentation https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

A list of all the strftime arguments. Names of months and nice stuff like formatting left zero fill. Read the full page for stuff like rules for "naive" arguments. Here is the list in brief: %a Sun, Mon, …, Sat

%A Sunday, Monday, …, Saturday

%w Weekday as number, where 0 is Sunday

%d Day of the month 01, 02, …, 31

%b Jan, Feb, …, Dec

%B January, February, …, December

%m Month number as a zero-padded 01, 02, …, 12

%y 2 digit year zero-padded 00, 01, …, 99

%Y 4 digit Year 1970, 1988, 2001, 2013

%H Hour (24-hour clock) zero-padded 00, 01, …, 23

%I Hour (12-hour clock) zero-padded 01, 02, …, 12

%p AM or PM.

%M Minute zero-padded 00, 01, …, 59

%S Second zero-padded 00, 01, …, 59

%f Microsecond zero-padded 000000, 000001, …, 999999

%z UTC offset in the form +HHMM or -HHMM +0000, -0400, +1030

%Z Time zone name UTC, EST, CST

%j Day of the year zero-padded 001, 002, …, 366

%U Week number of the year zero padded, Days before the first Sunday are week 0

%W Week number of the year (Monday as first day)

%c Locale’s date and time representation. Tue Aug 16 21:30:00 1988

%x Locale’s date representation. 08/16/1988 (en_US)

%X Locale’s time representation. 21:30:00

%% literal '%' character.

Asp.net Hyperlink control equivalent to <a href="#"></a>

If you need to access this as a server-side control (e.g. you want to add data attributes to a link, as I did), then there is a way to do what you want; however, you don't use the Hyperlink or HtmlAnchor controls to do it. Create a literal control and then add in "Your Text" as the text for the literal control (or whatever else you need to do that way). It's hacky, but it works.

Git: Create a branch from unstaged/uncommitted changes on master

If you are using the GitHub Windows client (as I am) and you are in the situation of having made uncommitted changes that you wish to move to a new branch, you can simply "Crate a new branch" via the GitHub client. It will switch to the newly created branch and preserve your changes.

enter image description here

Python equivalent of a given wget command

For Windows and Python 3.x, my two cents contribution about renaming the file on download :

  1. Install wget module : pip install wget
  2. Use wget :
import wget
wget.download('Url', 'C:\\PathToMyDownloadFolder\\NewFileName.extension')

Truely working command line example :

python -c "import wget; wget.download(""https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.17.2.tar.xz"", ""C:\\Users\\TestName.TestExtension"")"

Note : 'C:\\PathToMyDownloadFolder\\NewFileName.extension' is not mandatory. By default, the file is not renamed, and the download folder is your local path.

Combine two arrays

Just use:

$output = array_merge($array1, $array2);

That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite proceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.

Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...

A workaround is to recreate the keys.

$output = array_combine($output, $output);

Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)

$output = $array1 + $array2;

All of this can be seen in: http://php.net/manual/en/function.array-merge.php

Waiting for HOME ('android.process.acore') to be launched

I get this problem all the time and have lost many hours of potential productivity and education while I try to fix it. The only thing that works for me is the combination of three other good answers:

  1. Project -> Clean
  2. Delete all the AVDs and create new ones
  3. If an attempt to run still hangs too long on 'Waiting for HOME' (over two minutes) or the emulator keeps rebooting every minute or so, try Run as Android App several times, choosing the same existing emulator instance (I always choose runs manually).

It's odd that no one has a clue why this problem comes up, what causes it or what is going on internally. The only clue I can supply is that DDMS shows a few lines like "Class not found for preloading: libcore.base.CollectionUtils" during the 'Waiting for HOME' pause.

How can I do a BEFORE UPDATED trigger with sql server?

T-SQL supports only AFTER and INSTEAD OF triggers, it does not feature a BEFORE trigger, as found in some other RDBMSs.

I believe you will want to use an INSTEAD OF trigger.

ng-mouseover and leave to toggle item using mouse in angularjs

A little late here, but I've found this to be a common problem worth a custom directive to handle. Here's how that might look:

  .directive('toggleOnHover', function(){
    return {
      restrict: 'A',
      link: link
    };

    function link(scope, elem, attrs){
      elem.on('mouseenter', applyToggleExp);
      elem.on('mouseleave', applyToggleExp);

      function applyToggleExp(){
        scope.$apply(attrs.toggleOnHover);
      }
    }

  });

You can use it like this:

<li toggle-on-hover="editableProp = !editableProp">edit</li> 

The equivalent of a GOTO in python

Gotos are universally reviled in computer science and programming as they lead to very unstructured code.

Python (like almost every programming language today) supports structured programming which controls flow using if/then/else, loop and subroutines.

The key to thinking in a structured way is to understand how and why you are branching on code.

For example, lets pretend Python had a goto and corresponding label statement shudder. Look at the following code. In it if a number is greater than or equal to 0 we print if it

number = input()
if number < 0: goto negative
if number % 2 == 0:
   print "even"
else:
   print "odd"
goto end
label: negative
print "negative"
label: end
print "all done"

If we want to know when a piece of code is executed, we need to carefully traceback in the program, and examine how a label was arrived at - which is something that can't really be done.

For example, we can rewrite the above as:

number = input()
goto check

label: negative
print "negative"
goto end

label: check
if number < 0: goto negative
if number % 2 == 0:
   print "even"
else:
   print "odd"
goto end

label: end
print "all done"

Here, there are two possible ways to arrive at the "end", and we can't know which one was chosen. As programs get large this kind of problem gets worse and results in spaghetti code

In comparison, below is how you would write this program in Python:

number = input()
if number >= 0:
   if number % 2 == 0:
       print "even"
   else:
       print "odd"
else:
   print "negative"
print "all done"

I can look at a particular line of code, and know under what conditions it is met by tracing back the tree of if/then/else blocks it is in. For example, I know that the line print "odd" will be run when a ((number >= 0) == True) and ((number % 2 == 0) == False).

Static Initialization Blocks

It's also useful when you actually don't want to assign the value to anything, such as loading some class only once during runtime.

E.g.

static {
    try {
        Class.forName("com.example.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        throw new ExceptionInInitializerError("Cannot load JDBC driver.", e);
    }
}

Hey, there's another benefit, you can use it to handle exceptions. Imagine that getStuff() here throws an Exception which really belongs in a catch block:

private static Object stuff = getStuff(); // Won't compile: unhandled exception.

then a static initializer is useful here. You can handle the exception there.

Another example is to do stuff afterwards which can't be done during assigning:

private static Properties config = new Properties();

static {
    try { 
        config.load(Thread.currentThread().getClassLoader().getResourceAsStream("config.properties");
    } catch (IOException e) {
        throw new ExceptionInInitializerError("Cannot load properties file.", e);
    }
}

To come back to the JDBC driver example, any decent JDBC driver itself also makes use of the static initializer to register itself in the DriverManager. Also see this and this answer.

How to import spring-config.xml of one project into spring-config.xml of another project?

<import resource="classpath*:spring-config.xml" /> 

This is the most suitable one for class path configuration. Particularly when you are searching for the .xml files in a different project which is in your class path.

How do I get the path of the current executed file in Python?

this solution is robust even in executables

import inspect, os.path

filename = inspect.getframeinfo(inspect.currentframe()).filename
path     = os.path.dirname(os.path.abspath(filename))

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Should black box or white box testing be the emphasis for testers?

White Box Testing equals Software Unit Test. The developer or a development level tester (e.g. another developer) ensures that the code he has written is working properly according to the detailed level requirements before integrating it in the system.

Black Box Testing equals Integration Testing. The tester ensures that the system works according to the requirements on a functional level.

Both test approaches are equally important in my opinion.

A thorough unit test will catch defects in the development stage and not after the software has been integrated into the system. A system level black box test will ensure all software modules behave correctly when integrated together. A unit test in the development stage would not catch these defects since modules are usually developed independent from each other.

How to list all dates between two dates

I made a calendar using:

http://social.technet.microsoft.com/wiki/contents/articles/22776.t-sql-calendar-table.aspx

then a Store procedure passing two dates and thats all:

USE DB_NAME;
GO

CREATE PROCEDURE [dbo].[USP_LISTAR_RANGO_FECHAS]
@FEC_INICIO date,
@FEC_FIN date
AS
Select Date from CALENDARIO where Date BETWEEN @FEC_INICIO AND @FEC_FIN;

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

All good and valid courses of investigation especially the logs for more info.

For those hitting this it might be a simple gotcha where when you have created the DB User you may have enforced a password policy and left the user to change the password on first login (i.e. left the checkboxes around the password field at their default values).

Very easily done in SQL Management Studio and can of course cause authentication issues off the bat that are masked unless you look into the logs.

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

How can I find an element by CSS class with XPath?

XPath has a contains-token function, specifically designed for this situation:

//div[contains-token(@class, 'Test')]

It's only supported in the latest version of XPath (3.1) so you'll need an up-to-date implementation.

How do I query using fields inside the new PostgreSQL JSON datatype?

Postgres 9.2

I quote Andrew Dunstan on the pgsql-hackers list:

At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.

Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.

Postgres 9.3

Offers an arsenal of new functions and operators to add "json-processing".

The answer to the original question in Postgres 9.3:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ]'
  ) AS elem
WHERE elem->>'name' = 'Toby';

Advanced example:

For bigger tables you may want to add an expression index to increase performance:

Postgres 9.4

Adds jsonb (b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb also supports GIN, btree and hash indexes, GIN being the most potent of these.

The manual goes as far as suggesting:

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

Bold emphasis mine.

Performance benefits from general improvements to GIN indexes.

Postgres 9.5

Complete jsonb functions and operators. Add more functions to manipulate jsonb in place and for display.

Add Custom Headers using HttpWebRequest

IMHO it is considered as malformed header data.

You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.

The second way is true.

How to remove newlines from beginning and end of a string?

For anyone else looking for answer to the question when dealing with different linebreaks:

string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", "");          // Java 8

This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

This passes these tests:

// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));

// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));

// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));

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

Syntax highlighting is controlled by the theme you use, accessible through Preferences -> Color Scheme. Themes highlight different keywords, functions, variables, etc. through the use of scopes, which are defined by a series of regular expressions contained in a .tmLanguage file in a language's directory/package. For example, the JavaScript.tmLanguage file assigns the scopes source.js and variable.language.js to the this keyword. Since Sublime Text 3 is using the .sublime-package zip file format to store all the default settings it's not very straightforward to edit the individual files.

Unfortunately, not all themes contain all scopes, so you'll need to play around with different ones to find one that looks good, and gives you the highlighting you're looking for. There are a number of themes that are included with Sublime Text, and many more are available through Package Control, which I highly recommend installing if you haven't already. Make sure you follow the ST3 directions.

As it so happens, I've developed the Neon Color Scheme, available through Package Control, that you might want to take a look at. My main goal, besides trying to make a broad range of languages look as good as possible, was to identify as many different scopes as I could - many more than are included in the standard themes. While the JavaScript language definition isn't as thorough as Python's, for example, Neon still has a lot more diversity than some of the defaults like Monokai or Solarized.

jQuery highlighted with Neon Theme

I should note that I used @int3h's Better JavaScript language definition for this image instead of the one that ships with Sublime. It can be installed via Package Control.

UPDATE

Of late I've discovered another JavaScript replacement language definition - JavaScriptNext - ES6 Syntax. It has more scopes than the base JavaScript or even Better JavaScript. It looks like this on the same code:

JavaScriptNext

Also, since I originally wrote this answer, @skuroda has released PackageResourceViewer via Package Control. It allows you to seamlessly view, edit and/or extract parts of or entire .sublime-package packages. So, if you choose, you can directly edit the color schemes included with Sublime.

ANOTHER UPDATE

With the release of nearly all of the default packages on Github, changes have been coming fast and furiously. The old JS syntax has been completely rewritten to include the best parts of JavaScript Next ES6 Syntax, and now is as fully ES6-compatible as can be. A ton of other changes have been made to cover corner and edge cases, improve consistency, and just overall make it better. The new syntax has been included in the (at this time) latest dev build 3111.

If you'd like to use any of the new syntaxes with the current beta build 3103, simply clone the Github repo someplace and link the JavaScript (or whatever language(s) you want) into your Packages directory - find it on your system by selecting Preferences -> Browse Packages.... Then, simply do a git pull in the original repo directory from time to time to refresh any changes, and you can enjoy the latest and greatest! I should note that the repo uses the new .sublime-syntax format instead of the old .tmLanguage one, so they will not work with ST3 builds prior to 3084, or with ST2 (in both cases, you should have upgraded to the latest beta or dev build anyway).

I'm currently tweaking my Neon Color Scheme to handle all of the new scopes in the new JS syntax, but most should be covered already.

Does delete on a pointer to a subclass call the base class destructor?

I was wondering why my class' destructor was not called. The reason was that I had forgot to include definition of that class (#include "class.h"). I only had a declaration like "class A;" and the compiler was happy with it and let me call "delete".

Any difference between await Promise.all() and multiple await?

You can check for yourself.

In this fiddle, I ran a test to demonstrate the blocking nature of await, as opposed to Promise.all which will start all of the promises and while one is waiting it will go on with the others.

Difference between $.ajax() and $.get() and $.load()

Important note : jQuery.load() method can do not only GET but also POST requests, if data parameter is supplied (see: http://api.jquery.com/load/)

data Type: PlainObject or String A plain object or string that is sent to the server with the request.

Request Method The POST method is used if data is provided as an object; otherwise, GET is assumed.

Example: pass arrays of data to the server (POST request)
$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

How can I quickly delete a line in VIM starting at the cursor position?

(Edited to include commenter's good additions:)

D or its equivalent d$ will delete the rest of the line and leave you in command mode. C or c$ will delete the rest of the line and put you in insert mode, and new text will be appended to the line.

This is part of vitutor and vimtutor, excellent "reads" for vim beginners.

default value for struct member in C

An initialization function to a struct is a good way to grant it default values:

Mystruct s;
Mystruct_init(&s);

Or even shorter:

Mystruct s = Mystruct_init();  // this time init returns a struct

What are -moz- and -webkit-?

What are -moz- and -webkit-?

CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes.


Why do different browsers add different prefixes for the same effect?

A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:

Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.

Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.

Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid.

The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.


UPDATE AS OF THE YEAR 2016

As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.

As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016,

Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.

For example, just a few years ago, to set a rounded corner on a box you had to write:

-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;

But now that browsers have come to fully support this feature, you really only need the standardized version:

border-radius: 10px 5px;

Finding the right rules for all browsers

As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.

You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.

Input:

a {
  column-count: 3;
  column-gap: 10px;
  column-fill: auto;
}

Output:

a {
  -webkit-column-count: 3;
     -moz-column-count: 3;
          column-count: 3;
  -webkit-column-gap: 10px;
     -moz-column-gap: 10px;
          column-gap: 10px;
  -webkit-column-fill: auto;
     -moz-column-fill: auto;
          column-fill: auto;
}

What is Model in ModelAndView from Spring MVC?

ModelAndView: The name itself explains it is data structure which contains Model and View data.

Map() model=new HashMap(); 
model.put("key.name", "key.value");
new ModelAndView("view.name", model);

// or as follows

ModelAndView mav = new ModelAndView();
mav.setViewName("view.name");
mav.addObject("key.name", "key.value");

if model contains only single value, we can write as follows:

ModelAndView("view.name","key.name", "key.value");

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

Parse string to date with moment.js

  • How to change any string date to object date (also with moment.js):

let startDate = "2019-01-16T20:00:00.000"; let endDate = "2019-02-11T20:00:00.000"; let sDate = new Date(startDate); let eDate = new Date(endDate);

  • with moment.js:

startDate = moment(sDate); endDate = moment(eDate);

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

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

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

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

If you run (in SSMS):

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

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

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

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

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

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

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

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

Then it will ask:

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

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

How to calculate growth with a positive and negative number?

It really does not make sense to shift both into the positive, if you want a growth value that is comparable with the normal growth as result of both positive numbers. If I want to see the growth of 2 positive numbers, I don't want the shifting.

It makes however sense to invert the growth for 2 negative numbers. -1 to -2 is mathematically a growth of 100%, but that feels as something positive, and in fact, the result is a decline.

So, I have following function, allowing to invert the growth for 2 negative numbers:

setGrowth(Quantity q1, Quantity q2, boolean fromPositiveBase) {
if (q1.getValue().equals(q2.getValue()))
    setValue(0.0F);
else if (q1.getValue() <= 0 ^ q2.getValue() <= 0) // growth makes no sense
    setNaN();
else if (q1.getValue() < 0 && q2.getValue() < 0) // both negative, option to invert
    setValue((q2.getValue() - q1.getValue()) / ((fromPositiveBase? -1: 1) * q1.getValue()));
else // both positive
    setValue((q2.getValue() - q1.getValue()) / q1.getValue());
}

Where is android studio building my .apk file?

YourApplication\app\build\outputs\apk

How do I pass a variable to the layout using Laravel' Blade templating?

For future Google'rs that use Laravel 5, you can now also use it with includes,

@include('views.otherView', ['variable' => 1])

How do I mock a class without an interface?

If worse comes to worse, you can create an interface and adapter pair. You would change all uses of ConcreteClass to use the interface instead, and always pass the adapter instead of the concrete class in production code.

The adapter implements the interface, so the mock can also implement the interface.

It's more scaffolding than just making a method virtual or just adding an interface, but if you don't have access to the source for the concrete class it can get you out of a bind.

500 internal server error at GetResponse()

looking at your error message first of all I would suggest you to recompile your whole application, make sure all the required dlls are there in bin folder when you recompile it.

How to fix div on scroll

I made a mix of the answers here, took the code of @Julian and ideas from the others, seems clearer to me, this is what's left:

fiddle http://jsfiddle.net/wq2Ej/

jquery

//store the element
var $cache = $('.my-sticky-element');

//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').replace(/auto/, 0));
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= vTop) {
      // if so, ad the fixed class
      $cache.addClass('stuck');
    } else {
      // otherwise remove it
      $cache.removeClass('stuck');
    }
  });

css:

.my-sticky-element.stuck {
    position:fixed;
    top:0;
    box-shadow:0 2px 4px rgba(0, 0, 0, .3);
}

How can I validate a string to only allow alphanumeric characters in it?

You could do it easily with an extension function rather than a regex ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    for (int i = 0; i < str.Length; i++)
    {
        if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
            return false;
    }

    return true;
}

Per comment :) ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
}

How to overwrite the previous print to stdout in python?

Here's a cleaner, more "plug-and-play", version of @Nagasaki45's answer. Unlike many other answers here, it works properly with strings of different lengths. It achieves this by clearing the line with just as many spaces as the length of the last line printed print. Will also work on Windows.

def print_statusline(msg: str):
    last_msg_length = len(print_statusline.last_msg) if hasattr(print_statusline, 'last_msg') else 0
    print(' ' * last_msg_length, end='\r')
    print(msg, end='\r')
    sys.stdout.flush()  # Some say they needed this, I didn't.
    print_statusline.last_msg = msg

Usage

Simply use it like this:

for msg in ["Initializing...", "Initialization successful!"]:
    print_statusline(msg)
    time.sleep(1)

This small test shows that lines get cleared properly, even for different lengths:

for i in range(9, 0, -1):
    print_statusline("{}".format(i) * i)
    time.sleep(0.5)

Singleton in Android

EDIT :

The implementation of a Singleton in Android is not "safe" (see here) and you should use a library dedicated to this kind of pattern like Dagger or other DI library to manage the lifecycle and the injection.


Could you post an example from your code ?

Take a look at this gist : https://gist.github.com/Akayh/5566992

it works but it was done very quickly :

MyActivity : set the singleton for the first time + initialize mString attribute ("Hello") in private constructor and show the value ("Hello")

Set new value to mString : "Singleton"

Launch activityB and show the mString value. "Singleton" appears...

Oracle: is there a tool to trace queries, like Profiler for sql server?

I found an easy solution

Step1. connect to DB with an admin user using PLSQL or sqldeveloper or any other query interface

Step2. run the script bellow; in the S.SQL_TEXT column, you will see the executed queries

SELECT            
 S.LAST_ACTIVE_TIME,     
 S.MODULE,
 S.SQL_FULLTEXT, 
 S.SQL_PROFILE,
 S.EXECUTIONS,
 S.LAST_LOAD_TIME,
 S.PARSING_USER_ID,
 S.SERVICE                                                                       
FROM
 SYS.V_$SQL S, 
 SYS.ALL_USERS U
WHERE
 S.PARSING_USER_ID=U.USER_ID 
 AND UPPER(U.USERNAME) IN ('oracle user name here')   
ORDER BY TO_DATE(S.LAST_LOAD_TIME, 'YYYY-MM-DD/HH24:MI:SS') desc;

The only issue with this is that I can't find a way to show the input parameters values(for function calls), but at least we can see what is ran in Oracle and the order of it without using a specific tool.

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

What is the .idea folder?

It contains your local IntelliJ IDE configs. I recommend adding this folder to your .gitignore file:

# intellij configs
.idea/

Simulate Keypress With jQuery

This works:

var event = jQuery.Event('keypress');
event.which = 13; 
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event); 

Hive load CSV with commas in quoted fields

If you can re-create or parse your input data, you can specify an escape character for the CREATE TABLE:

ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';

Will accept this line as 4 fields

1,some text\, with comma in it,123,more text

What is a postback?

The term is also used in web application development when interacting with 3rd party web-service APIs

Many APIs require both an interactive and non-interactive integration. Typically the interactive part is done using redirects (site 1 redirects a user to site 2, where they sign in, and are redirected back). The non-interactive part is done using a 'postback', or an HTTP POST from site 2's servers to site 1's servers.

JavaScript: set dropdown selected item based on option text

A modern alternative:

const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);

How to run docker-compose up -d at system start up?

Use restart: always in your docker compose file.

Docker-compose up -d will launch container from images again. Use docker-compose start to start the stopped containers, it never launches new containers from images.

nginx:   
    restart: always   
    image: nginx   
    ports:
      - "80:80"
      - "443:443"   links:
      - other_container:other_container

Also you can write the code up in the docker file so that it gets created first, if it has the dependency of other containers.

sudo: docker-compose: command not found

On Ubuntu 16.04

Here's how I fixed this issue: Refer Docker Compose documentation

  1. sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose

  2. sudo chmod +x /usr/local/bin/docker-compose

After you do the curl command , it'll put docker-compose into the

/usr/local/bin

which is not on the PATH. To fix it, create a symbolic link:

  1. sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

And now if you do: docker-compose --version

You'll see that docker-compose is now on the PATH

Best way to convert text files between character sets?

Under Linux you can use the very powerful recode command to try and convert between the different charsets as well as any line ending issues. recode -l will show you all of the formats and encodings that the tool can convert between. It is likely to be a VERY long list.

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

In Python try until no error

Here is one that hard fails after 4 attempts, and waits 2 seconds between attempts. Change as you wish to get what you want form this one:

from time import sleep

for x in range(0, 4):  # try 4 times
    try:
        # msg.send()
        # put your logic here
        str_error = None
    except Exception as str_error:
        pass

    if str_error:
        sleep(2)  # wait for 2 seconds before trying to fetch the data again
    else:
        break

Here is an example with backoff:

from time import sleep

sleep_time = 2
num_retries = 4
for x in range(0, num_retries):  
    try:
        # put your logic here
        str_error = None
    except Exception as str_error:
        pass

    if str_error:
        sleep(sleep_time)  # wait before trying to fetch the data again
        sleep_time *= 2  # Implement your backoff algorithm here i.e. exponential backoff
    else:
        break

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

Pull new updates from original GitHub repository into forked GitHub repository

If you're using the GitHub desktop application, there is a synchronise button on the top right corner. Click on it then Update from <original repo> near top left.

If there are no changes to be synchronised, this will be inactive.

Here are some screenshots to make this easy.

Member '<method>' cannot be accessed with an instance reference

I know this is an old thread, but I just spent 3 hours trying to figure out what my issue was. I ordinarily know what this error means, but you can run into this in a more subtle way as well. My issue was my client class (the one calling a static method from an instance class) had a property of a different type but named the same as the static method. The error reported by the compiler was the same as reported here, but the issue was basically name collision.

For anyone else getting this error and none of the above helps, try fully qualifying your instance class with the namespace name. ..() so the compiler can see the exact name you mean.

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

Just found this thread and posted an alternative answer (copied below) here: https://stackoverflow.com/a/37853766/1948625

Specifically on this question, if the dot "." used in the -S value of the command line means the same as 127.0.0.1, then it could be the same issue as the connection string of the other question. Use the hostname instead, or check your hosts file.


Old question, and my symptoms are slightly different, but same error. My connection string was correct (Integrated security, and I don't provide user and pwd) with data source set to 127.0.0.1. It worked fine for years.

But recently I added a line in the static host file for testing purposes (C:\Windows\System32\drivers\etc\hosts)

127.0.0.1           www.blablatestsite.com

Removing this line and the error is gone.

I got a clue from this article (https://support.microsoft.com/en-gb/kb/896861) which talks about hostnames and loopback.

Other possible fix (if you need to keep that line in the hosts file) is to use the hostname (like MYSERVER01) instead of 127.0.0.1 in the data source of the connection string.

Given an RGB value, how do I create a tint (or shade)?

Some definitions

  • A shade is produced by "darkening" a hue or "adding black"
  • A tint is produced by "ligthening" a hue or "adding white"

Creating a tint or a shade

Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:

  • RGB:

    • To shade:

      newR = currentR * (1 - shade_factor)
      newG = currentG * (1 - shade_factor)
      newB = currentB * (1 - shade_factor)
      
    • To tint:

      newR = currentR + (255 - currentR) * tint_factor
      newG = currentG + (255 - currentG) * tint_factor
      newB = currentB + (255 - currentB) * tint_factor
      
    • More generally, the color resulting in layering a color RGB(currentR,currentG,currentB) with a color RGBA(aR,aG,aB,alpha) is:

      newR = currentR + (aR - currentR) * alpha
      newG = currentG + (aG - currentG) * alpha
      newB = currentB + (aB - currentB) * alpha
      

    where (aR,aG,aB) = black = (0,0,0) for shading, and (aR,aG,aB) = white = (255,255,255) for tinting

  • HSV or HSB:

    • To shade: lower the Value / Brightness or increase the Saturation
    • To tint: lower the Saturation or increase the Value / Brightness
  • HSL:
    • To shade: lower the Lightness
    • To tint: increase the Lightness

There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB and want to use the HSV model to shade for example, you can just convert to HSV, do the shading and convert back to RGB. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :

Comparing the models

  • RGB has the advantage of being really simple to implement, but:
    • you can only shade or tint your color relatively
    • you have no idea if your color is already tinted or shaded
  • HSV or HSB is kind of complex because you need to play with two parameters to get what you want (Saturation & Value / Brightness)
  • HSL is the best from my point of view:
    • supported by CSS3 (for webapp)
    • simple and accurate:
      • 50% means an unaltered Hue
      • >50% means the Hue is lighter (tint)
      • <50% means the Hue is darker (shade)
    • given a color you can determine if it is already tinted or shaded
    • you can tint or shade a color relatively or absolutely (by just replacing the Lightness part)

How to insert a data table into SQL Server database table?

From my understanding of the question,this can use a fairly straight forward solution.Anyway below is the method i propose ,this method takes in a data table and then using SQL statements to insert into a table in the database.Please mind that my solution is using MySQLConnection and MySqlCommand replace it with SqlConnection and SqlCommand.

public void InsertTableIntoDB_CreditLimitSimple(System.Data.DataTable tblFormat)
    {
        for (int i = 0; i < tblFormat.Rows.Count; i++)
        {

            String InsertQuery = string.Empty;

            InsertQuery = "INSERT INTO customercredit " +
                          "(ACCOUNT_CODE,NAME,CURRENCY,CREDIT_LIMIT) " +
                          "VALUES ('" + tblFormat.Rows[i]["AccountCode"].ToString() + "','" + tblFormat.Rows[i]["Name"].ToString() + "','" + tblFormat.Rows[i]["Currency"].ToString() + "','" + tblFormat.Rows[i]["CreditLimit"].ToString() + "')";



            using (MySqlConnection destinationConnection = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
            using (var dbcm = new MySqlCommand(InsertQuery, destinationConnection))
            {
                destinationConnection.Open();
                dbcm.ExecuteNonQuery();
            }
        }
    }//CreditLimit

Is there a way to get version from package.json in nodejs code?

Here is how to read the version out of package.json:

fs = require('fs')
json = JSON.parse(fs.readFileSync('package.json', 'utf8'))
version = json.version

EDIT: Wow, this answer was originally from 2012! There are several better answers now. Probably the cleanest is:

const { version } = require('./package.json');

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

Escaping Strings in JavaScript

You can also use this

_x000D_
_x000D_
let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
_x000D_
_x000D_

Regular Expression with wildcards to match any character

Without knowing the exact regex implementation you're making use of, I can only give general advice. (The syntax I will be perl as that's what I know, some languages will require tweaking)

Looking at ABC: (z) jan 02 1999 \n

  • The first thing to match is ABC: So using our regex is /ABC:/

  • You say ABC is always at the start of the string so /^ABC/ will ensure that ABC is at the start of the string.

  • You can match spaces with the \s (note the case) directive. With all directives you can match one or more with + (or 0 or more with *)

  • You need to escape the usage of ( and ) as it's a reserved character. so \(\)

  • You can match any non space or newline character with .

  • You can match anything at all with .* but you need to be careful you're not too greedy and capture everything.

So in order to capture what you've asked. I would use /^ABC:\s*\(.+?\)\s*(.+)$/

Which I read as:

Begins with ABC:

May have some spaces

has (

has some characters

has )

may have some spaces

then capture everything until the end of the line (which is $).

I highly recommend keeping a copy of the following laying about http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

What's the proper way to "go get" a private repository?

After setting up GOPRIVATE and git config ...

People may still meeting problems like this when fetching private source:

https fetch: Get "https://private/user/repo?go-get=1": EOF

They can't use private repo without .git extension.

The reason is the go tool has no idea about the VCS protocol of this repo, git or svn or any other, unlike github.com or golang.org them are hardcoded into go's source.

Then the go tool will do a https query before fetching your private repo:

https://private/user/repo?go-get=1

If your private repo has no support for https request, please use replace to tell it directly :

require private/user/repo v1.0.0

...

replace private/user/repo => private.server/user/repo.git v1.0.0

https://golang.org/cmd/go/#hdr-Remote_import_paths

What does void do in java?

Void: the type modifier void states that the main method does not return any value. All parameters to a method are declared inside a prior of parenthesis. Here String args[ ] declares a parameter named args which contains an array of objects of the class type string.

Listing files in a directory matching a pattern in Java

See File#listFiles(FilenameFilter).

File dir = new File(".");
File [] files = dir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".xml");
    }
});

for (File xmlfile : files) {
    System.out.println(xmlfile);
}

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings

Update: this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }

Removing empty rows of a data file in R

Here are some dplyr options:

# sample data
df <- data.frame(a = c('1', NA, '3', NA), b = c('a', 'b', 'c', NA), c = c('e', 'f', 'g', NA))

library(dplyr)

# remove rows where all values are NA:
df %>% filter_all(any_vars(!is.na(.)))
df %>% filter_all(any_vars(complete.cases(.)))  


# remove rows where only some values are NA:
df %>% filter_all(all_vars(!is.na(.)))
df %>% filter_all(all_vars(complete.cases(.)))  

# or more succinctly:
df %>% filter(complete.cases(.))  
df %>% na.omit

# dplyr and tidyr:
library(tidyr)
df %>% drop_na

How to increase the clickable area of a <a> tag button?

If you're using HTML 5, i.e. the doctype

<!doctype html>

then you can just use block-level links.

<a href="google.com">
  <div class="hello">
    ..
  </div>
</a>

Override devise registrations controller

I believe there is a better solution than rewrite the RegistrationsController. I did exactly the same thing (I just have Organization instead of Company).

If you set properly your nested form, at model and view level, everything works like a charm.

My User model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_many :owned_organizations, :class_name => 'Organization', :foreign_key => :owner_id

  has_many :organization_memberships
  has_many :organizations, :through => :organization_memberships

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :username, :owned_organizations_attributes

  accepts_nested_attributes_for :owned_organizations
  ...
end

My Organization Model:

class Organization < ActiveRecord::Base
  belongs_to :owner, :class_name => 'User'
  has_many :organization_memberships
  has_many :users, :through => :organization_memberships
  has_many :contracts

  attr_accessor :plan_name

  after_create :set_owner_membership, :set_contract
  ...
end

My view : 'devise/registrations/new.html.erb'

<h2>Sign up</h2>

<% resource.owned_organizations.build if resource.owned_organizations.empty? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <p><%= f.label :name %><br />
    <%= f.text_field :name %></p>

  <p><%= f.label :email %><br />
    <%= f.text_field :email %></p>

  <p><%= f.label :username %><br />
    <%= f.text_field :username %></p>

  <p><%= f.label :password %><br />
    <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %></p>

  <%= f.fields_for :owned_organizations do |organization_form| %>

    <p><%= organization_form.label :name %><br />
      <%= organization_form.text_field :name %></p>

    <p><%= organization_form.label :subdomain %><br />
      <%= organization_form.text_field :subdomain %></p>

    <%= organization_form.hidden_field :plan_name, :value => params[:plan] %>

  <% end %>

  <p><%= f.submit "Sign up" %></p>
<% end %>

<%= render :partial => "devise/shared/links" %>

wget/curl large file from google drive

ggID='put_googleID_here'  
ggURL='https://drive.google.com/uc?export=download'  
filename="$(curl -sc /tmp/gcokie "${ggURL}&id=${ggID}" | grep -o '="uc-name.*</span>' | sed 's/.*">//;s/<.a> .*//')"  
getcode="$(awk '/_warning_/ {print $NF}' /tmp/gcokie)"  
curl -Lb /tmp/gcokie "${ggURL}&confirm=${getcode}&id=${ggID}" -o "${filename}"  

How does it work?
Get cookie file and html code with curl.
Pipe html to grep and sed and search for file name.
Get confirm code from cookie file with awk.
Finally download file with cookie enabled, confirm code and filename.

curl -Lb /tmp/gcokie "https://drive.google.com/uc?export=download&confirm=Uq6r&id=0B5IRsLTwEO6CVXFURmpQZ1Jxc0U" -o "SomeBigFile.zip"

If you dont need filename variable curl can guess it
-L Follow redirects
-O Remote-name
-J Remote-header-name

curl -sc /tmp/gcokie "${ggURL}&id=${ggID}" >/dev/null  
getcode="$(awk '/_warning_/ {print $NF}' /tmp/gcokie)"  
curl -LOJb /tmp/gcokie "${ggURL}&confirm=${getcode}&id=${ggID}" 

To extract google file ID from URL you can use:

echo "gURL" | egrep -o '(\w|-){26,}'  
# match more than 26 word characters  

OR

echo "gURL" | sed 's/[^A-Za-z0-9_-]/\n/g' | sed -rn '/.{26}/p'  
# replace non-word characters with new line,   
# print only line with more than 26 word characters 

Change value of input and submit form in JavaScript

Here is simple code. You must set an id for your input. Here call it 'myInput':

var myform = document.getElementById('myform');
myform.onsubmit = function(){
    document.getElementById('myInput').value = '1';
    myform.submit();
};

(HTML) Download a PDF file instead of opening them in browser when clicked

Without html5 attribute one can achieve this by using php:

Create php file named download.php with this code:

<?php
ob_start();
$file = "yourPDF.pdf"

if (file_exists($file)) 
{
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit();
}

Now if you want to automatically start downloading pdf write this javascript:

<script>window.location = "download.php";</script>

If you want this to work on a link, use this...

<a href='javascript:window.location = "download.php"'>
    Download it!
</a>

How do I analyze a program's core dump file with GDB when it has command-line parameters?

From RMS's GDB debugger tutorial:

prompt > myprogram
Segmentation fault (core dumped)
prompt > gdb myprogram
...
(gdb) core core.pid
...

Make sure your file really is a core image -- check it using file.

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

SelectSingleNode returning null for known good xml node path using XPath

just use //id instead of /id. It works fine in my code

How to obtain image size using standard Python class (without using external library)?

Found a nice solution in another Stackoverflow post (using only standard libraries + dealing with jpg as well): JohnTESlade answer

And another solution (the quick way) for those who can afford running 'file' command within python, run:

import os
info = os.popen("file foo.jpg").read()
print info

Output:

foo.jpg: JPEG image data...density 28x28, segment length 16, baseline, precision 8, 352x198, frames 3

All you gotta do now is to format the output to capture the dimensions. 352x198 in my case.

Django - limiting query results

Looks like the solution in the question doesn't work with Django 1.7 anymore and raises an error: "Cannot reorder a query once a slice has been taken"

According to the documentation https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets forcing the “step” parameter of Python slice syntax evaluates the Query. It works this way:

Model.objects.all().order_by('-id')[:10:1]

Still I wonder if the limit is executed in SQL or Python slices the whole result array returned. There is no good to retrieve huge lists to application memory.

Most efficient way to check for DBNull and then assign to a variable?

I always use :

if (row["value"] != DBNull.Value)
  someObject.Member = row["value"];

Found it short and comprehensive.

ipython notebook clear cell output in code

You can use IPython.display.clear_output to clear the output of a cell.

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print("Hello World!")

At the end of this loop you will only see one Hello World!.

Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.

C++ Singleton design pattern

In addition to the other discussion here, it may be worth noting that you can have global-ness, without limiting usage to one instance. For example, consider the case of reference counting something...

struct Store{
   std::array<Something, 1024> data;
   size_t get(size_t idx){ /* ... */ }
   void incr_ref(size_t idx){ /* ... */}
   void decr_ref(size_t idx){ /* ... */}
};

template<Store* store_p>
struct ItemRef{
   size_t idx;
   auto get(){ return store_p->get(idx); };
   ItemRef() { store_p->incr_ref(idx); };
   ~ItemRef() { store_p->decr_ref(idx); };
};

Store store1_g;
Store store2_g; // we don't restrict the number of global Store instances

Now somewhere inside a function (such as main) you can do:

auto ref1_a = ItemRef<&store1_g>(101);
auto ref2_a = ItemRef<&store2_g>(201); 

The refs don't need to store a pointer back to their respective Store because that information is supplied at compile-time. You also don't have to worry about the Store's lifetime because the compiler requires that it is global. If there is indeed only one instance of Store then there's no overhead in this approach; with more than one instance it's up to the compiler to be clever about code generation. If necessary, the ItemRef class can even be made a friend of Store (you can have templated friends!).

If Store itself is a templated class then things get messier, but it is still possible to use this method, perhaps by implementing a helper class with the following signature:

template <typename Store_t, Store_t* store_p>
struct StoreWrapper{ /* stuff to access store_p, e.g. methods returning 
                       instances of ItemRef<Store_t, store_p>. */ };

The user can now create a StoreWrapper type (and global instance) for each global Store instance, and always access the stores via their wrapper instance (thus forgetting about the gory details of the template parameters needed for using Store).

Passing arguments to "make run"

You can pass the variable to the Makefile like below:

run:
    @echo ./prog $$FOO

Usage:

$ make run FOO="the dog kicked the cat"
./prog the dog kicked the cat

or:

$ FOO="the dog kicked the cat" make run
./prog the dog kicked the cat

Alternatively use the solution provided by Beta:

run:
    @echo ./prog $(filter-out $@,$(MAKECMDGOALS))
%:
    @:

%: - rule which match any task name; @: - empty recipe = do nothing

Usage:

$ make run the dog kicked the cat
./prog the dog kicked the cat

How do I detect if I am in release or debug mode?

Make sure that you are importing the correct BuildConfig class And yes, you will have no problems using:

if (BuildConfig.DEBUG) {
   //It's not a release version.
}

Is it possible to animate scrollTop with jQuery?

I have what I believe is a better solution than the $('html, body') hack.

It's not a one-liner, but the issue I had with $('html, body') is that if you log $(window).scrollTop() during the animation, you'll see that the value jumps all over the place, sometimes by hundreds of pixels (though I don't see anything like that happening visually). I needed the value to be predictable, so that I could cancel the animation if the user grabbed the scroll bar or twirled the mousewheel during the auto-scroll.

Here is a function will animate scrolling smoothly:

function animateScrollTop(target, duration) {
    duration = duration || 16;
    var scrollTopProxy = { value: $(window).scrollTop() };
    if (scrollTopProxy.value != target) {
        $(scrollTopProxy).animate(
            { value: target }, 
            { duration: duration, step: function (stepValue) {
                var rounded = Math.round(stepValue);
                $(window).scrollTop(rounded);
            }
        });
    }
}

Below is a more complex version that will cancel the animation on user interaction, as well as refiring until the target value is reached, which is useful when trying to set the scrollTop instantaneously (e.g. simply calling $(window).scrollTop(1000) — in my experience, this fails to work about 50% of the time.)

function animateScrollTop(target, duration) {
    duration = duration || 16;

    var $window = $(window);
    var scrollTopProxy = { value: $window.scrollTop() };
    var expectedScrollTop = scrollTopProxy.value;

    if (scrollTopProxy.value != target) {
        $(scrollTopProxy).animate(
            { value: target },
            {
                duration: duration,

                step: function (stepValue) {
                    var roundedValue = Math.round(stepValue);
                    if ($window.scrollTop() !== expectedScrollTop) {
                        // The user has tried to scroll the page
                        $(scrollTopProxy).stop();
                    }
                    $window.scrollTop(roundedValue);
                    expectedScrollTop = roundedValue;
                },

                complete: function () {
                    if ($window.scrollTop() != target) {
                        setTimeout(function () {
                            animateScrollTop(target);
                        }, 16);
                    }
                }
            }
        );
    }
}

Return row number(s) for a particular value in a column in a dataframe

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
df
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

link_to method and click event in Rails

just use

=link_to "link", "javascript:function()"

How to change the date format of a DateTimePicker in vb.net

Try this code it works:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
    MsgBox(CustomeDate.ToString)

    con.Open()

    dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)

    ds = New System.Data.DataSet
    dadap.Fill(ds)
    Dgview.DataSource = ds.Tables(0)
    con.Close()

Note : if u use dd for date representation it will return nothing while selecting 1 to 9 so use d for selection

'Date time format
'MMM     Three-letter month.
'ddd     Three-letter day of the week.
'd       Day of the month.
'HH      Two-digit hours on 24-hour scale.
'mm      Two-digit minutes.
'yyyy    Four-digit year.

The documentation contains a full list of the date formats.

Add tooltip to font awesome icon

codepen Is perhaps a helpful example.

<div class="social-icons">
  <a class="social-icon social-icon--codepen">
    <i class="fa fa-codepen"></i>
    <div class="tooltip">Codepen</div>
</div>

body {  
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

/* Color Variables */
$color-codepen: #000;

/* Social Icon Mixin */
@mixin social-icon($color) {
  background: $color;
  background: linear-gradient(tint($color, 5%), shade($color, 5%));
  border-bottom: 1px solid shade($color, 20%);
  color: tint($color, 50%);

  &:hover {
    color: tint($color, 80%);
    text-shadow: 0px 1px 0px shade($color, 20%);
  }

  .tooltip {
    background: $color;
    background: linear-gradient(tint($color, 15%), $color);
    color: tint($color, 80%);

    &:after {
      border-top-color: $color;
    }
  }
}

/* Social Icons */
.social-icons {
  display: flex;
}

.social-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  width: 80px;
  height: 80px;
  margin: 0 0.5rem;
  border-radius: 50%;
  cursor: pointer;
  font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
  font-size: 2.5rem;
  text-decoration: none;
  text-shadow: 0 1px 0 rgba(0,0,0,0.2);
  transition: all 0.15s ease;

  &:hover {
    color: #fff;

    .tooltip {
      visibility: visible;
      opacity: 1;
      transform: translate(-50%, -150%);
    }
  }

  &:active {
    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5) inset;
  }

  &--codepen { @include social-icon($color-codepen); }

  i {
    position: relative;
    top: 1px;
  }
}

/* Tooltips */
.tooltip {
  display: block;
  position: absolute;
  top: 0;
  left: 50%;
  padding: 0.8rem 1rem;
  border-radius: 3px;
  font-size: 0.8rem;
  font-weight: bold;
  opacity: 0;
  pointer-events: none;
  text-transform: uppercase;
  transform: translate(-50%, -100%);
  transition: all 0.3s ease;
  z-index: 1;

  &:after {
    display: block;
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 0;
    height: 0;
    content: "";
    border: solid;
    border-width: 10px 10px 0 10px;
    border-color: transparent;
    transform: translate(-50%, 100%);
  }
}

How can I capture the right-click event in JavaScript?

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum
</div>

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('success!');
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

Efficient way of having a function only execute once in a loop

Run the function before the loop. Example:

myFunction()
while True:
    # all the other code being executed in your loop

This is the obvious solution. If there's more than meets the eye, the solution may be a bit more complicated.

How to overcome "'aclocal-1.15' is missing on your system" warning?

The whole point of Autotools is to provide an arcane M4-macro-based language which ultimately compiles to a shell script called ./configure. You can ship this compiled shell script with the source code and that script should do everything to detect the environment and prepare the program for building. Autotools should only be required by someone who wants to tweak the tests and refresh that shell script.

It defeats the point of Autotools if GNU This and GNU That has to be installed on the system for it to work. Originally, it was invented to simplify the porting of programs to various Unix systems, which could not be counted on to have anything on them. Even the constructs used by the generated shell code in ./configure had to be very carefully selected to make sure they would work on every broken old shell just about everywhere.

The problem you're running into is due to some broken Makefile steps invented by people who simply don't understand what Autotools is for and the role of the final ./configure script.

As a workaround, you can go into the Makefile and make some changes to get this out of the way. As an example, I'm building the Git head of GNU Awk and running into this same problem. I applied this patch to Makefile.in, however, and I can sucessfully make gawk:

diff --git a/Makefile.in b/Makefile.in

index 5585046..b8b8588 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -312,12 +312,12 @@ distcleancheck_listfiles = find . -type f -print

 # Directory for gawk's data files. Automake supplies datadir.
 pkgdatadir = $(datadir)/awk
-ACLOCAL = @ACLOCAL@
+ACLOCAL = true
 AMTAR = @AMTAR@
 AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
+AUTOCONF = true
+AUTOHEADER = true
+AUTOMAKE = true
 AWK = @AWK@
 CC = @CC@
 CCDEPMODE = @CCDEPMODE@

Basically, I changed things so that the harmless true shell command is substituted for all the Auto-stuff programs.

The actual build steps for Gawk don't need the Auto-stuff! It's only involved in some rules that get invoked if parts of the Auto-stuff have changed and need to be re-processed. However, the Makefile is structured in such a way that it fails if the tools aren't present.

Before the above patch:

$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && /bin/bash /home/kaz/gawk/missing aclocal-1.15 -I m4
/home/kaz/gawk/missing: line 81: aclocal-1.15: command not found
WARNING: 'aclocal-1.15' is missing on your system.
         You should only need it if you modified 'acinclude.m4' or
         'configure.ac' or m4 files included by 'configure.ac'.
         The 'aclocal' program is part of the GNU Automake package:
         <http://www.gnu.org/software/automake>
         It also requires GNU Autoconf, GNU m4 and Perl in order to run:
         <http://www.gnu.org/software/autoconf>
         <http://www.gnu.org/software/m4/>
         <http://www.perl.org/>
make: *** [aclocal.m4] Error 127

After the patch:

$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && true -I m4
CDPATH="${ZSH_VERSION+.}:" && cd . && true
gcc -std=gnu99 -DDEFPATH='".:/usr/local/share/awk"' -DDEFLIBPATH="\"/usr/local/lib/gawk\"" -DSHLIBEXT="\"so"\" -DHAVE_CONFIG_H -DGAWK -DLOCALEDIR='"/usr/local/share/locale"' -I.     -g -O2 -DNDEBUG -MT array.o -MD -MP -MF .deps/array.Tpo -c -o array.o array.c 
[...]
gcc -std=gnu99  -g -O2 -DNDEBUG  -Wl,-export-dynamic -o gawk array.o awkgram.o builtin.o cint_array.o command.o debug.o dfa.o eval.o ext.o field.o floatcomp.o gawkapi.o gawkmisc.o getopt.o getopt1.o int_array.o io.o main.o mpfr.o msg.o node.o profile.o random.o re.o regex.o replace.o str_array.o symbol.o version.o      -ldl -lm
$ ./gawk --version
GNU Awk 4.1.60, API: 1.2
Copyright (C) 1989, 1991-2015 Free Software Foundation.
[...]

There we go. As you can see, the CDPATH= command lines there are where the Auto-stuff was being invoked, where you see the true commands. These report successful termination, and so it just falls through that junk to do the darned build, which is perfectly configured.

I did make gawk because there are some subdirectories that get built which fail; the trick has to be repeated for their respective Makefiles.

If you're running into this kind of thing with a pristine, official tarball of the program from its developers, then complain. It should just unpack, ./configure and make without you having to patch anything or install any Automake or Autoconf materials.

Ideally, a pull of their Git head should also behave that way.

Regular Expressions- Match Anything

  1. Regex:

    /I bought.*sheep./
    

    Matches - the whole string till the end of line

    I bought sheep. I bought a sheep. I bought five sheep.

  2. Regex:

    /I bought(.*)sheep./
    

    Matches - the whole string and also capture the sub string within () for further use

    I bought sheep. I bought a sheep. I bought five sheep.

    I boughtsheep. I bought a sheep. I bought fivesheep.

    Example using Javascript/Regex

    'I bought sheep. I bought a sheep. I bought five sheep.'.match(/I bought(.*)sheep./)[0];
    

    Output:

    "I bought sheep. I bought a sheep. I bought five sheep."

    'I bought sheep. I bought a sheep. I bought five sheep.'.match(/I bought(.*)sheep./)[1];
    

    Output:

    " sheep. I bought a sheep. I bought five "

Drawable image on a canvas

Drawable d = ContextCompat.getDrawable(context, R.drawable.***)
d.setBounds(left, top, right, bottom);
d.draw(canvas);

MySQL - force not to use cache for testing speed of query

Another alternative that only affects the current connection:

SET SESSION query_cache_type=0;

Insert a line at specific line number with sed or awk

OS X / macOS / FreeBSD sed

The -i flag works differently on macOS sed than in GNU sed.

Here's the way to use it on macOS / OS X:

sed -i '' '8i\
8 This is Line 8' FILE

See man 1 sed for more info.

org.xml.sax.SAXParseException: Content is not allowed in prolog

I encountered similar problem with jenkins junit report plugin. It turns out you have to specify *.xml, even if you create junit xml in home directory. (So Test report XMLs: .xml ..(or targeted_directory/.xml).

Cross Browser Flash Detection in Javascript

Detecting and embedding Flash within a web document is a surprisingly difficult task.

I was very disappointed with the quality and non-standards compliant markup generated from both SWFObject and Adobe's solutions. Additionally, my testing found Adobe's auto updater to be inconsistent and unreliable.

The JavaScript Flash Detection Library (Flash Detect) and JavaScript Flash HTML Generator Library (Flash TML) are a legible, maintainable and standards compliant markup solution.

-"Luke read the source!"

How do I create a master branch in a bare Git repository?

You don't need to use a second repository - you can do commands like git checkout and git commit on a bare repository, if only you supply a dummy work directory using the --work-tree option.

Prepare a dummy directory:

$ rm -rf /tmp/empty_directory
$ mkdir  /tmp/empty_directory

Create the master branch without a parent (works even on a completely empty repo):

$ cd your-bare-repository.git

$ git checkout --work-tree=/tmp/empty_directory --orphan master
Switched to a new branch 'master'                  <--- abort if "master" already exists

Create a commit (it can be a message-only, without adding any files, because what you need is simply having at least one commit):

$ git commit -m "Initial commit" --allow-empty --work-tree=/tmp/empty_directory 

$ git branch
* master

Clean up the directory, it is still empty.

$ rmdir  /tmp/empty_directory

Tested on git 1.9.1. (Specifically for OP, the posh-git is just a PowerShell wrapper for standard git.)

Run jar file in command prompt

java [any other JVM options you need to give it] -jar foo.jar

Replace special characters in a string with _ (underscore)

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g,'_');

String replacement in Objective-C

The problem exists in old versions on the iOS. in the latest, the right-to-left works well. What I did, is as follows:

first I check the iOS version:

if (![self compareCurVersionTo:4 minor:3 point:0])

Than:

// set RTL on the start on each line (except the first)  
myUITextView.text = [myUITextView.text stringByReplacingOccurrencesOfString:@"\n"
                                                           withString:@"\u202B\n"];

Multiple -and -or in PowerShell Where-Object statement

By wrapping your comparisons in {} in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }. Since the -and operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true } which is always true.

Instead of using {}, use parentheses ().

Also you want to use -eq instead of -match since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls').

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public | 
        Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}

A better option is to filter the extensions at the Get-ChildItem command.

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk | 
        Where-Object {$_.creationtime -ge "06/01/2014"}
}

Capitalize the first letter of string in AngularJs

If you are after performance, try to avoid using AngularJS filters as they are applied twice per each expression to check for their stability.

A better way would be to use CSS ::first-letter pseudo-element with text-transform: uppercase;. That can't be used on inline elements such as span, though, so the next best thing would be to use text-transform: capitalize; on the whole block, which capitalizes every word.

Example:

_x000D_
_x000D_
var app = angular.module('app', []);_x000D_
_x000D_
app.controller('Ctrl', function ($scope) {_x000D_
   $scope.msg = 'hello, world.';_x000D_
});
_x000D_
.capitalize {_x000D_
  display: inline-block;  _x000D_
}_x000D_
_x000D_
.capitalize::first-letter {_x000D_
  text-transform: uppercase;_x000D_
}_x000D_
_x000D_
.capitalize2 {_x000D_
  text-transform: capitalize;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="app">_x000D_
    <div ng-controller="Ctrl">_x000D_
        <b>My text:</b> <div class="capitalize">{{msg}}</div>_x000D_
        <p><b>My text:</b> <span class="capitalize2">{{msg}}</span></p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

This means that your server is sending "text/html" instead of the already supported types. My solution was to add "text/html" to acceptableContentTypes set in AFURLResponseSerialization class. Just search for "acceptableContentTypes" and add @"text/html" to the set manually.

Of course, the ideal solution is to change the type sent from the server, but for that you will have to talk with the server team.

Remove all HTMLtags in a string (with the jquery text() function)

I found in my specific case that I just needed to trim the content. Maybe not the answer asked in the question. But I thought I should add this answer anyway.

$(myContent).text().trim()

Wait for shell command to complete

what you proposed with a change at the parenthesis at the Run command worked fine with VBA for me

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Integer
wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

How do I download and save a file locally on iOS using objective C?

I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:

NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
  [urlData writeToFile:filePath atomically:YES];
}

Changing the selected option of an HTML Select element

Excellent answers - here's the D3 version for anyone looking:

<select id="sel">
    <option>Cat</option>
    <option>Dog</option>
    <option>Fish</option>
</select>
<script>
    d3.select('#sel').property('value', 'Fish');
</script>

CSS selector for text input fields?

As @Amir posted above, the best way nowadays – cross-browser and leaving behind IE6 – is to use

[type=text] {}

Nobody mentioned lower CSS specificity (why is that important?) so far, [type=text] features 0,0,1,0 instead of 0,0,1,1 with input[type=text].

Performance-wise there's no negative impact at all any more.

normalize v4.0.0 just released with lowered selector specificity.

What is the purpose of the "role" attribute in HTML?

Is this role attribute necessary?

Answer: Yes.

  • The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
  • Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.

It provides you:

  • Accessibility
  • Device adaptation
  • Server-side processing
  • Complex data description,...etc.

How to get all possible combinations of a list’s elements?

Here are two implementations of itertools.combinations

One that returns a list

def combinations(lst, depth, start=0, items=[]):
    if depth <= 0:
        return [items]
    out = []
    for i in range(start, len(lst)):
        out += combinations(lst, depth - 1, i + 1, items + [lst[i]])
    return out

One returns a generator

def combinations(lst, depth, start=0, prepend=[]):
    if depth <= 0:
        yield prepend
    else:
        for i in range(start, len(lst)):
            for c in combinations(lst, depth - 1, i + 1, prepend + [lst[i]]):
                yield c

Please note that providing a helper function to those is advised because the prepend argument is static and is not changing with every call

print([c for c in combinations([1, 2, 3, 4], 3)])
# [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]

# get a hold of prepend
prepend = [c for c in combinations([], -1)][0]
prepend.append(None)

print([c for c in combinations([1, 2, 3, 4], 3)])
# [[None, 1, 2, 3], [None, 1, 2, 4], [None, 1, 3, 4], [None, 2, 3, 4]]

This is a very superficial case but better be safe than sorry

latex large division sign in a math formula

A possible soluttion that requires tweaking, but is very flexible is to use one of \big, \Big, \bigg,\Bigg in front of your division sign - these will make it progressively larger. For your formula, I think

  $\frac{a_1}{a_2} \Big/ \frac{b_1}{b_2}$

looks nicer than \middle\ which is automatically sized and IMHO is a bit too large.

How can I hash a password in Java?

You can comput hashes using MessageDigest, but this is wrong in terms of security. Hashes are not to be used for storing passwords, as they are easily breakable.

You should use another algorithm like bcrypt, PBKDF2 and scrypt to store you passwords. See here.

load and execute order of scripts

After testing many options I've found that the following simple solution is loading the dynamically loaded scripts in the order in which they are added in all modern browsers

loadScripts(sources) {
    sources.forEach(src => {
        var script = document.createElement('script');
        script.src = src;
        script.async = false; //<-- the important part
        document.body.appendChild( script ); //<-- make sure to append to body instead of head 
    });
}

loadScripts(['/scr/script1.js','src/script2.js'])

Converting file size in bytes to human-readable string

My answer might be late, but I guess it will help someone.

Metric prefix:

/**
 * Format file size in metric prefix
 * @param fileSize
 * @returns {string}
 */
const formatFileSizeMetric = (fileSize) => {
  let size = Math.abs(fileSize);

  if (Number.isNaN(size)) {
    return 'Invalid file size';
  }

  if (size === 0) {
    return '0 bytes';
  }

  const units = ['bytes', 'kB', 'MB', 'GB', 'TB'];
  let quotient = Math.floor(Math.log10(size) / 3);
  quotient = quotient < units.length ? quotient : units.length - 1;
  size /= (1000 ** quotient);

  return `${+size.toFixed(2)} ${units[quotient]}`;
};

Binary prefix:

/**
 * Format file size in binary prefix
 * @param fileSize
 * @returns {string}
 */
const formatFileSizeBinary = (fileSize) => {
  let size = Math.abs(fileSize);

  if (Number.isNaN(size)) {
    return 'Invalid file size';
  }

  if (size === 0) {
    return '0 bytes';
  }

  const units = ['bytes', 'kiB', 'MiB', 'GiB', 'TiB'];
  let quotient = Math.floor(Math.log2(size) / 10);
  quotient = quotient < units.length ? quotient : units.length - 1;
  size /= (1024 ** quotient);

  return `${+size.toFixed(2)} ${units[quotient]}`;
};

Examples:

// Metrics prefix
formatFileSizeMetric(0)      // 0 bytes
formatFileSizeMetric(-1)     // 1 bytes
formatFileSizeMetric(100)    // 100 bytes
formatFileSizeMetric(1000)   // 1 kB
formatFileSizeMetric(10**5)  // 10 kB
formatFileSizeMetric(10**6)  // 1 MB
formatFileSizeMetric(10**9)  // 1GB
formatFileSizeMetric(10**12) // 1 TB
formatFileSizeMetric(10**15) // 1000 TB

// Binary prefix
formatFileSizeBinary(0)     // 0 bytes
formatFileSizeBinary(-1)    // 1 bytes
formatFileSizeBinary(1024)  // 1 kiB
formatFileSizeBinary(2048)  // 2 kiB
formatFileSizeBinary(2**20) // 1 MiB
formatFileSizeBinary(2**30) // 1 GiB
formatFileSizeBinary(2**40) // 1 TiB
formatFileSizeBinary(2**50) // 1024 TiB

Can we add div inside table above every <tr>?

You can't put a div directly inside a table but you can put div inside td or th element.

For that you need to do is make sure the div is inside an actual table cell, a td or th element, so do that:

HTML:-

<tr>
  <td>
    <div>
      <p>I'm text in a div.</p>
    </div>
  </td>
</tr>

For more information :-

http://css-tricks.com/using-divs-inside-tables/

Pandas: how to change all the values of a column?

As @DSM points out, you can do this more directly using the vectorised string methods:

df['Date'].str[-4:].astype(int)

Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):

df['Date'].str.extract('(?P<year>\d{4})').astype(int)

An alternative slightly more flexible way, might be to use apply (or equivalently map) to do this:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer

The lambda function, is taking the input from the Date and converting it to a year.
You could (and perhaps should) write this more verbosely as:

def convert_to_year(date_in_some_format):
    date_as_string = str(date_in_some_format)  # cast to string
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)

Perhaps 'Year' is a better name for this column...

Adding external library in Android studio

There are two simplest ways if one does not work please try the other one.

  1. Add dependency of the library inside dependency inside build.gradle file of the library you are using, and paste your library in External Libraries.

OR

  1. Just Go to your libs folder inside app folder and paste all your .jar e.g Library files there, Now the trick here is that now go inside settings.gradle file now add this line include ':app:libs' after include ':app' it will definitely work.

How do I programmatically set device orientation in iOS 7?

If you want only portrait mode, in iOS 9 (Xcode 7) you can:

  • Going to Info.plist
  • Select "Supported interface orientations" item
  • Delete "Landscape(left home button)" and "Landscape(right home button)"

enter image description here

How can I remove the gloss on a select element in Safari on Mac?

Check out -webkit-appearance: none and its derivatives. Originally described by Chris Coyer here: https://css-tricks.com/almanac/properties/a/appearance/

installing urllib in Python3.6

urllib is a standard python library (built-in) so you don't have to install it. just import it if you need to use request by:

import urllib.request

if it's not work maybe you compiled python in wrong way, so be kind and give us more details.

WPF: ItemsControl with scrollbar (ScrollViewer)

To get a scrollbar for an ItemsControl, you can host it in a ScrollViewer like this:

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <ItemsControl>
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
  </ItemsControl>
</ScrollViewer>

To switch from vertical split to horizontal split fast in Vim

Horizontal to vertical split

Ctrl+W for window command, followed by Shift+H or Shift+L


Vertical to horizontal split

Ctrl+W for window command, followed by Shift+K or Shift+J

Both solutions apply when only two windows exist.


Open help in a vertical split by default

Add both of these lines to .vimrc:

cabbrev help vert help
cabbrev h vert h

:vert[ical] {cmd} always executes the cmd in a vertically split window.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

protected String toCamelCase(String input) {
    if (input == null) {
        return null;
    }

    if (input.length() == 0) {
        return "";
    }

    // lowercase the first character
    String camelCaseStr = input.substring(0, 1).toLowerCase();

    if (input.length() > 1) {
        boolean isStartOfWord = false;

        for (int i = 1; i < input.length(); i++) {
            char currChar = input.charAt(i);
            if (currChar == '_') {
                // new word. ignore underscore
                isStartOfWord = true;
            } else if (Character.isUpperCase(currChar)) {
                // capital letter. if start of word, keep it
                if (isStartOfWord) {
                    camelCaseStr += currChar;
                } else {
                    camelCaseStr += Character.toLowerCase(currChar);
                }
                isStartOfWord = false;
            } else {
                camelCaseStr += currChar;
                isStartOfWord = false;
            }
        }
    }

    return camelCaseStr;
}

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

Is it possible to forward-declare a function in Python?

There is no such thing in python like forward declaration. You just have to make sure that your function is declared before it is needed. Note that the body of a function isn't interpreted until the function is executed.

Consider the following example:

def a():
   b() # won't be resolved until a is invoked.

def b(): 
   print "hello"

a() # here b is already defined so this line won't fail.

You can think that a body of a function is just another script that will be interpreted once you call the function.

How do you set autocommit in an SQL Server session?

Autocommit is SQL Server's default transaction management mode. (SQL 2000 onwards)

Ref: Autocommit Transactions

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Delete the designer.cs file and then right click on the .aspx file and choose "Convert To Web Application". If there is a problem with your control declarations, such as a tag not being well-formed, you will get an error message and you will need to correct the malformed tag before visual studio can successfully re-generate your designer file.

In my case, at this point, I discovered that the problem was that I had declared a button control that that was not inside of a form tag with a runat="server" attribute.

How to set the context path of a web application in Tomcat 7.0

Simplest and flexible solution is below: Inside ${Tomcat_home}/config/server.xml

Change the autoDeploy="false" deployOnStartup="false" under Host element like below This is must.

<Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="false" deployOnStartup="false">

Add below line under Host element.

<Context path="" docBase="ServletInAction.war"  reloadable="true">
            <WatchedResource>WEB-INF/web.xml</WatchedResource>
        </Context>

With the above approach we can add as many applications under webapps with different context path names.

Rock, Paper, Scissors Game Java

Why not check for what the user entered and then ask the user to enter correct input again?

eg:

//Get player's play from input-- note that this is 
// stored as a string 
System.out.println("Enter your play: "); 
response = scan.next();
if(response=="R"||response=="P"||response=="S"){
  personPlay = response;
}else{
  System.out.println("Invaild Input")
}

for the other modifications, please check my total code at pastebin

PostgreSQL: How to change PostgreSQL user password?

Go to your Postgresql Config and Edit pg_hba.conf

sudo vim /etc/postgresql/9.3/main/pg_hba.conf

Then Change this Line :

Database administrative login by Unix domain socket
local      all              postgres                                md5

to :

Database administrative login by Unix domain socket
local   all             postgres                                peer

then Restart the PostgreSQL service via SUDO command then

psql -U postgres

You will be now entered and will See the Postgresql terminal

then enter

\password

and enter the NEW Password for Postgres default user, After Successfully changing the Password again go to the pg_hba.conf and revert the change to "md5"

now you will be logged in as

psql -U postgres

with your new Password.

Let me know if you all find any issue in it.

PHP include relative path

function relativepath($to){
    $a=explode("/",$_SERVER["PHP_SELF"] );
    $index= array_search("$to",$a);
    $str=""; 
    for ($i = 0; $i < count($a)-$index-2; $i++) {
        $str.= "../";
    }
    return $str;
    }

Here is the best solution i made about that, you just need to specify at which level you want to stop, but the problem is that you have to use this folder name one time.

when I run mockito test occurs WrongTypeOfReturnValue Exception

I recently encountered this issue while mocking a function in a Kotlin data class. For some unknown reason one of my test runs ended up in a frozen state. When I ran the tests again some of my tests that had previously passed started to fail with the WrongTypeOfReturnValue exception.

I ensured I was using org.mockito:mockito-inline to avoid the issues with final classes (mentioned by Arvidaa), but the problem remained. What solved it for me was to kill the process and restart Android Studio. This terminated my frozen test run and the following test runs passed without issues.

Checking host availability by using ping in bash scripts

There is advanced version of ping - "fping", which gives possibility to define the timeout in milliseconds.

#!/bin/bash
IP='192.168.1.1'
fping -c1 -t300 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
  echo "Host found"
else
  echo "Host not found"
fi

In Java, how do I parse XML as a String instead of a file?

I'm using this method

public Document parseXmlFromString(String xmlString){
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = new    ByteArrayInputStream(xmlString.getBytes());
    org.w3c.dom.Document document = builder.parse(inputStream);
    return document;
}

Namespace for [DataContract]

DataContractAttribute Class is in the System.Runtime.Serialization namespace.

You should add a reference to System.Runtime.Serialization.dll. That assembly isn't referenced by default though. To add the reference to your project you have to go to References -> Add Reference in the Solution Explorer and add an assembly reference manually.

Write HTML file using Java

if it is becoming repetitive work ; i think you shud do code reuse ! why dont you simply write functions that "write" small building blocks of HTML. get the idea? see Eg. you can have a function to which you could pass a string and it would automatically put that into a paragraph tag and present it. Of course you would also need to write some kind of a basic parser to do this (how would the function know where to attach the paragraph!). i dont think you are a beginner .. so i am not elaborating ... do tell me if you do not understand..

Cross-Origin Read Blocking (CORB)

Response headers are generally set on the server. Set 'Access-Control-Allow-Headers' to 'Content-Type' on server side

jquery.ajax Access-Control-Allow-Origin

http://encosia.com/using-cors-to-access-asp-net-services-across-domains/

refer the above link for more details on Cross domain resource sharing.

you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.

sample below:

ajax call:

$(document).ready(function () {
        $.ajax({
            crossDomain: true,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            async:false,
            url: "<your middle man service url here>/GetQuote?callback=?",
            data: { symbol: 'ctsh' },
            dataType: "jsonp",                
            jsonpCallback: 'fnsuccesscallback'
        });
    });

service (asmx) which will return jsonp:

[WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void GetQuote(String symbol,string callback)
    {          

        WebProxy myProxy = new WebProxy("<proxy url here>", true);

        myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
        StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
        SQ.Proxy = myProxy;
        String result = SQ.GetQuote(symbol);
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        sb.Append(callback + "(");
        sb.Append(js.Serialize(result));
        sb.Append(");");
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Write(sb.ToString());
        Context.Response.End();         
    }

splitting a string based on tab in the file

You can use regexp to do this:

import re
patt = re.compile("[^\t]+")


s = "a\t\tbcde\t\tef"
patt.findall(s)
['a', 'bcde', 'ef']  

Remote branch is not showing up in "git branch -r"

The remote section also specifies fetch rules. You could add something like this into it to fetch all branches from the remote:

fetch = +refs/heads/*:refs/remotes/origin/*

(Or replace origin with bitbucket.)

Please read about it here: 10.5 Git Internals - The Refspec

ALTER TABLE, set null in not null column, PostgreSQL 9.1

Execute the command in this format

ALTER TABLE tablename ALTER COLUMN columnname SET NOT NULL;

for setting the column to not null.

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

Radio buttons and label to display in same line

Put them both to display:inline.

Conditionally change img src based on model data

For angular 4 I have used

<img [src]="data.pic ? data.pic : 'assets/images/no-image.png' " alt="Image" title="Image">

It works for me , I hope it may use to other's also for Angular 4-5. :)

jquery AJAX and json format

$.ajax({
   type: "POST",
   url: hb_base_url + "consumer",
   contentType: "application/json",
   dataType: "json",
   data: {
       data__value = JSON.stringify(
       {
           first_name: $("#namec").val(),
           last_name: $("#surnamec").val(),
           email: $("#emailc").val(),
           mobile: $("#numberc").val(),
           password: $("#passwordc").val()
       })
   },
   success: function(response) {
       console.log(response);
   },
   error: function(response) {
       console.log(response);
   }
});

(RU) ?? ??????? ???? ?????? ????? ???????? ??? - $_POST['data__value']; ???????? ??? ????????? ???????? first_name ?? ???????, ????? ????????:

(EN) On the server, you can get your data as - $_POST ['data__value']; For example, to get the first_name value on the server, write:

$test = json_decode( $_POST['data__value'] );
echo $test->first_name;

How can I make my own event in C#?

I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:

public event EventHandler Foo;

If you need more complicated subscription/unsubscription logic, you can do that explicitly:

public event EventHandler Foo
{
    add
    {
        // Subscription logic here
    }
    remove
    {
        // Unsubscription logic here
    }
}

Lollipop : draw behind statusBar with its color set to transparent

Instead of

<item name="android:statusBarColor">@android:color/transparent</item>

Use the following:

<item name="android:windowTranslucentStatus">true</item>

And make sure to remove the top padding (which is added by default) on your 'MainActivity' layout.

Note that this does not make the status bar fully transparent, and there will still be a "faded black" overlay over your status bar.

Inconsistent Accessibility: Parameter type is less accessible than method

When I received this error, I had a "helper" class that I did not declare as public that caused this issue inside of the class that used the "helper" class. Making the "helper" class public solved this error, as in:

public ServiceClass { public ServiceClass(HelperClass _helper) { } }

public class HelperClass {} // Note the public HelperClass that solved my issue.

This may help someone else who encounters this.

How to hide/show more text within a certain length (like youtube)

If you need some complete solution, you can use this :

http://jsfiddle.net/7Vv8u/2703/

JS (jQuery)

var text = $('.text-overflow'),
     btn = $('.btn-overflow'),
       h = text.scrollHeight; 

if(h > 120) {
    btn.addClass('less');
    btn.css('display', 'block');
}

btn.click(function(e) 
{
  e.stopPropagation();

  if (btn.hasClass('less')) {
      btn.removeClass('less');
      btn.addClass('more');
      btn.text('Show less');

      text.animate({'height': h});
  } else {
      btn.addClass('less');
      btn.removeClass('more');
      btn.text('Show more');
      text.animate({'height': '120px'});
  }  
});

HTML

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<div class="text-overflow">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<a class="btn-overflow" href="#">Show more</a> 

CSS

.text-overflow {
  width:250px;
  height:120px;
  display:block; 
  overflow:hidden;
  word-break: break-word;
  word-wrap: break-word;
}

.btn-overflow {
  display: none;
  text-decoration: none; 
}

How do I resolve this "ORA-01109: database not open" error?

I got a same problem. Below is how I solved the problem. I am working on an oracle database 12c pluggable database(pdb) on a windows 10.

-- using sqlplus to login as sysdba from a terminal; Below is an example:

sqlplus sys/@orclpdb as sysdba

-- First check your database status;

SQL> select name, open_mode from v$pdbs;

-- It shows the database is mounted in my case. If yours is not mounted, you should mount the database first.

-- Next open the database for read/write

SQL> ALTER PLUGGABLE DATABASE OPEN; (or ALTER PLUGGABLE DATABASE YOURDATABASENAME OPEN;)

-- Check the status again.

SQL> select name, open_mode from v$pdbs;

-- Now your dababase should be open for read/write and you should be able to create schemas, etc.

Using Razor within JavaScript

You're trying to jam a square peg in a round hole.

Razor was intended as an HTML-generating template language. You may very well get it to generate JavaScript code, but it wasn't designed for that.

For instance: What if Model.Title contains an apostrophe? That would break your JavaScript code, and Razor won't escape it correctly by default.

It would probably be more appropriate to use a String generator in a helper function. There will likely be fewer unintended consequences of that approach.