Programs & Examples On #Wcm

A subsection of Content Management is Web Content Management or WCM. WCM means maintaining, controlling, changing and reassembling the content on a web-page.

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

How should I make my VBA code compatible with 64-bit Windows?

i found this code (note that some Long are changed to LongPtr):

Declare PtrSafe Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hwnd As LongPtr, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As _
String, ByVal nShowCmd As Long) As LongPtr

source: http://www.cadsharp.com/docs/Win32API_PtrSafe.txt

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

What is exactly the base pointer and stack pointer? To what do they point?

esp stands for "Extended Stack Pointer".....ebp for "Something Base Pointer"....and eip for "Something Instruction Pointer"...... The stack Pointer points to the offset address of the stack segment. The Base Pointer points to the offset address of the extra segment. The Instruction Pointer points to the offset address of the code segment. Now, about the segments...they are small 64KB divisions of the processors memory area.....This process is known as Memory Segmentation. I hope this post was helpful.

T-SQL: Opposite to string concatenation - how to split string into multiple records

I wrote this awhile back. It assumes the delimiter is a comma and that the individual values aren't bigger than 127 characters. It could be modified pretty easily.

It has the benefit of not being limited to 4,000 characters.

Good luck!

ALTER Function [dbo].[SplitStr] ( 
        @txt text 
) 
Returns @tmp Table 
        ( 
                value varchar(127)
        ) 
as 
BEGIN 
        declare @str varchar(8000) 
                , @Beg int 
                , @last int 
                , @size int 

        set @size=datalength(@txt) 
        set @Beg=1 


        set @str=substring(@txt,@Beg,8000) 
        IF len(@str)<8000 set @Beg=@size 
        ELSE BEGIN 
                set @last=charindex(',', reverse(@str)) 
                set @str=substring(@txt,@Beg,8000-@last) 
                set @Beg=@Beg+8000-@last+1 
        END 

        declare @workingString varchar(25) 
                , @stringindex int 



        while @Beg<=@size Begin 
                WHILE LEN(@str) > 0 BEGIN 
                        SELECT @StringIndex = CHARINDEX(',', @str) 

                        SELECT 
                                @workingString = CASE 
                                        WHEN @StringIndex > 0 THEN SUBSTRING(@str, 1, @StringIndex-1) 
                                        ELSE @str 
                                END 

                        INSERT INTO 
                                @tmp(value)
                        VALUES 
                                (cast(rtrim(ltrim(@workingString)) as varchar(127)))
                        SELECT @str = CASE 
                                WHEN CHARINDEX(',', @str) > 0 THEN SUBSTRING(@str, @StringIndex+1, LEN(@str)) 
                                ELSE '' 
                        END 
                END 
                set @str=substring(@txt,@Beg,8000) 

                if @Beg=@size set @Beg=@Beg+1 
                else IF len(@str)<8000 set @Beg=@size 
                ELSE BEGIN 
                        set @last=charindex(',', reverse(@str)) 
                        set @str=substring(@txt,@Beg,8000-@last) 
                        set @Beg=@Beg+8000-@last+1 

                END 
        END     

        return
END 

How to set background color of a View

You can simple use :

view.setBackgroundColor(Color.parseColor("#FFFFFF"));

Text File Parsing with Python

There are a few ways to go about this. One option would be to use inputfile.read() instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

How do I delete NuGet packages that are not referenced by any project in my solution?

If you have removed package using Uninstall-Package utility and deleted the desired package from package directory under solution (and you are still getting error), just open up the *.csproj file in code editor and remove the tag manually. Like for instance, I wanted to get rid of Nuget package Xamarin.Forms.Alias and I removed these lines from *.csproj file.

Removing nuget package from msbuild script

And finally, don't forget to reload your project once prompted in Visual Studio (after changing project file). I tried it on Visual Studio 2015, but it should work on Visual Studio 2010 and onward too.

Hope this helps.

How to upload & Save Files with Desired name

use this for target path for uploading

<?php
$file_name = $_FILES["csvFile"]["name"];
$target_path = $dir = plugin_dir_path( __FILE__ )."\\upload\\". $file_name;
echo $target_path;
move_uploaded_file($_FILES["csvFile"]["tmp_name"],$target_path. $file_name);
?>

Visual Studio 2015 Update 3 Offline Installer (ISO)

You can check Visual Studio Downloads for available Visual Studio Community, Visual Studio Professional, Visual Studio Enterprise and Visual Studio Code download links.


Update!

There is no direct links of Visual Studio 2015 at Visual Studio Downloads anymore. but the below links still works.


OR simply click on direct links below (for .iso/.exe file):


VSCode area:

How to allow only a number (digits and decimal point) to be typed in an input?

This one seems the easiest to me: http://jsfiddle.net/thomporter/DwKZh/

(Code is not mine, I accidentally stumbled upon it)

    angular.module('myApp', []).directive('numbersOnly', function(){
       return {
         require: 'ngModel',
         link: function(scope, element, attrs, modelCtrl) {
           modelCtrl.$parsers.push(function (inputValue) {
               // this next if is necessary for when using ng-required on your input. 
               // In such cases, when a letter is typed first, this parser will be called
               // again, and the 2nd time, the value will be undefined
               if (inputValue == undefined) return '' 
               var transformedInput = inputValue.replace(/[^0-9]/g, ''); 
               if (transformedInput!=inputValue) {
                  modelCtrl.$setViewValue(transformedInput);
                  modelCtrl.$render();
               }         

               return transformedInput;         
           });
         }
       };
    });

Solve error javax.mail.AuthenticationFailedException

trying to connect to host "smtp.gmail.com", port 465, isSSL false

You got your gmail smtp setting wrong. Gmail requires SSL. Please see tutorials on how to send email via Java via Gmail SMTP, eg: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

How many bytes is unsigned long long?

Executive summary: it's 64 bits, or larger.

unsigned long long is the same as unsigned long long int. Its size is platform-dependent, but guaranteed by the C standard (ISO C99) to be at least 64 bits. There was no long long in C89, but apparently even MSVC supports it, so it's quite portable.

In the current C++ standard (issued in 2003), there is no long long, though many compilers support it as an extension. The upcoming C++0x standard will support it and its size will be the same as in C, so at least 64 bits.

You can get the exact size, in bytes (8 bits on typical platforms) with the expression sizeof(unsigned long long). If you want exactly 64 bits, use uint64_t, which is defined in the header <stdint.h> along with a bunch of related types (available in C99, C++11 and some current C++ compilers).

How can I test an AngularJS service from the console?

@JustGoscha's answer is spot on, but that's a lot to type when I want access, so I added this to the bottom of my app.js. Then all I have to type is x = getSrv('$http') to get the http service.

// @if DEBUG
function getSrv(name, element) {
    element = element || '*[ng-app]';
    return angular.element(element).injector().get(name);
}
// @endif

It adds it to the global scope but only in debug mode. I put it inside the @if DEBUG so that I don't end up with it in the production code. I use this method to remove debug code from prouduction builds.

How to remove unused C/C++ symbols with GCC and ld?

You can use strip binary on object file(eg. executable) to strip all symbols from it.

Note: it changes file itself and don't create copy.

Vertical rulers in Visual Studio Code

In addition to global "editor.rulers" setting, it's also possible to set this on a per-language level.

For example, style guides for Python projects often specify either 79 or 120 characters vs. Git commit messages should be no longer than 50 characters.

So in your settings.json, you'd put:

"[git-commit]": {"editor.rulers": [50]},
"[python]": {
    "editor.rulers": [
        79,
        120
    ]
}

How to detect idle time in JavaScript elegantly?

I know it a relatively old question, but I had the same issue and I found a quite good solution.

I used: jquery.idle and I only needed to do:

$(document).idle({
  onIdle: function(){
    alert('You did nothing for 5 seconds');
  },
  idle: 5000
})

See JsFiddle demo.

(Just for Info: see this for back-end event tracking Leads browserload)

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

Subset data to contain only columns whose names match a condition

Using dplyr you can:

df <- df %>% dplyr:: select(grep("ABC", names(df)), grep("XYZ", names(df)))

endforeach in loops?

as an alternative syntax you can write foreach loops like so

foreach($arr as $item):
    //do stuff
endforeach;

This type of syntax is typically used when php is being used as a templating language as such

<?php foreach($arr as $item):?>
    <!--do stuff -->
<?php endforeach; ?>

Pushing from local repository to GitHub hosted remote

This worked for my GIT version 1.8.4:

  1. From the local repository folder, right click and select 'Git Commit Tool'.
  2. There, select the files you want to upload, under 'Unstaged Changes' and click 'Stage Changed' button. (You can initially click on 'Rescan' button to check what files are modified and not uploaded yet.)
  3. Write a Commit Message and click 'Commit' button.
  4. Now right click in the folder again and select 'Git Bash'.
  5. Type: git push origin master and enter your credentials. Done.

stringstream, string, and char* conversion confusion

What you're doing is creating a temporary. That temporary exists in a scope determined by the compiler, such that it's long enough to satisfy the requirements of where it's going.

As soon as the statement const char* cstr2 = ss.str().c_str(); is complete, the compiler sees no reason to keep the temporary string around, and it's destroyed, and thus your const char * is pointing to free'd memory.

Your statement string str(ss.str()); means that the temporary is used in the constructor for the string variable str that you've put on the local stack, and that stays around as long as you'd expect: until the end of the block, or function you've written. Therefore the const char * within is still good memory when you try the cout.

to remove first and last element in array

You used Fruits.shift() method to first element remove . Fruits.pop() method used for last element remove one by one if you used button click. Fruits.slice( start position, delete element)You also used slice method for remove element in middle start.

Python function to convert seconds into minutes, hours, and days

This tidbit is useful for displaying elapsed time to varying degrees of granularity.

I personally think that questions of efficiency are practically meaningless here, so long as something grossly inefficient isn't being done. Premature optimization is the root of quite a bit of evil. This is fast enough that it'll never be your choke point.

intervals = (
    ('weeks', 604800),  # 60 * 60 * 24 * 7
    ('days', 86400),    # 60 * 60 * 24
    ('hours', 3600),    # 60 * 60
    ('minutes', 60),
    ('seconds', 1),
    )

def display_time(seconds, granularity=2):
    result = []

    for name, count in intervals:
        value = seconds // count
        if value:
            seconds -= value * count
            if value == 1:
                name = name.rstrip('s')
            result.append("{} {}".format(value, name))
    return ', '.join(result[:granularity])

..and this provides decent output:

In [52]: display_time(1934815)
Out[52]: '3 weeks, 1 day'

In [53]: display_time(1934815, 4)
Out[53]: '3 weeks, 1 day, 9 hours, 26 minutes'

Bash script to cd to directory with spaces in pathname

Use single quotes, like:

myPath=~/'my dir'

cd $myPath

Reading RFID with Android phones

NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.

You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.

I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.

If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.

ARM compilation error, VFP registers used by executable, not object file

"Note that the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries." https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html arm-none-eabi-gcc.exe

Silicon Labs "kjostera" "Employee" response to EFR32 Flex Gecko (crossreference Cortex-M4F): "So code compiled with the softfp ABI is not link time compatible with code compiled with hardfp ABI. So since we currently only support RAIL library compiled using the softfp ABI, this means that you will have to build your application as well using the softfp ABI." "Note that using softfp ABI does not mean that your code cannot use FPU instructions. Any code doing floating point arithmetic will use the FPU when the compiler thinks that it makes sense." "kjostera" then goes on to demonstrate that the GCC 7 generated Assembly for both the case of -mfloat-abi=softfp and -mfloat-abi=hard, the vmul.f32 instruction is invoked and the instruction count is 10 for softfp and 9 for hard. https://www.silabs.com/community/mcu/32-bit/forum.topic.html/enable_fpu_in_rail-p-SEYr https://www.silabs.com/documents/public/data-sheets/efr32fg1-datasheet.pdf https://www.silabs.com/documents/public/reference-manuals/efr32xg12-rm.pdf https://www.silabs.com/documents/public/reference-manuals/efr32xg13-rm.pdf https://www.silabs.com/documents/public/reference-manuals/efr32xg14-rm.pdf

Timer function to provide time in nano seconds using C++

Minimalistic copy&paste-struct + lazy usage

If the idea is to have a minimalistic struct that you can use for quick tests, then I suggest you just copy and paste anywhere in your C++ file right after the #include's. This is the only instance in which I sacrifice Allman-style formatting.

You can easily adjust the precision in the first line of the struct. Possible values are: nanoseconds, microseconds, milliseconds, seconds, minutes, or hours.

#include <chrono>
struct MeasureTime
{
    using precision = std::chrono::microseconds;
    std::vector<std::chrono::steady_clock::time_point> times;
    std::chrono::steady_clock::time_point oneLast;
    void p() {
        std::cout << "Mark " 
                << times.size()/2
                << ": " 
                << std::chrono::duration_cast<precision>(times.back() - oneLast).count() 
                << std::endl;
    }
    void m() {
        oneLast = times.back();
        times.push_back(std::chrono::steady_clock::now());
    }
    void t() {
        m();
        p();
        m();
    }
    MeasureTime() {
        times.push_back(std::chrono::steady_clock::now());
    }
};

Usage

MeasureTime m; // first time is already in memory
doFnc1();
m.t(); // Mark 1: next time, and print difference with previous mark
doFnc2();
m.t(); // Mark 2: next time, and print difference with previous mark
doStuff = doMoreStuff();
andDoItAgain = doStuff.aoeuaoeu();
m.t(); // prints 'Mark 3: 123123' etc...

Standard output result

Mark 1: 123
Mark 2: 32
Mark 3: 433234

If you want summary after execution

If you want the report afterwards, because for example your code in between also writes to standard output. Then add the following function to the struct (just before MeasureTime()):

void s() { // summary
    int i = 0;
    std::chrono::steady_clock::time_point tprev;
    for(auto tcur : times)
    {
        if(i > 0)
        {
            std::cout << "Mark " << i << ": "
                    << std::chrono::duration_cast<precision>(tprev - tcur).count()
                    << std::endl;
        }
        tprev = tcur;
        ++i;
    }
}

So then you can just use:

MeasureTime m;
doFnc1();
m.m();
doFnc2();
m.m();
doStuff = doMoreStuff();
andDoItAgain = doStuff.aoeuaoeu();
m.m();
m.s();

Which will list all the marks just like before, but then after the other code is executed. Note that you shouldn't use both m.s() and m.t().

Set JavaScript variable = null, or leave undefined?

You can use ''; to declaring NULL variable in Javascript

Check if MySQL table exists or not

$query = mysqli_query('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME IN ("table1","table2","table3") AND TABLE_SCHEMA="yourschema"');
$tablesExists = array();
while( null!==($row=mysqli_fetch_row($query)) ){
    $tablesExists[] = $row[0];
}

ios app maximum memory budget

Working with the many answers above, I have implemented Apples new method os_proc_available_memory() for iOS 13+ coupled with NSByteCountFormatter which offers a number of useful formatting options for nicer output of the memory:

#include <os/proc.h>

....

- (NSString *)memoryStringForBytes:(unsigned long long)memoryBytes {
    NSByteCountFormatter *byteFormatter = [[NSByteCountFormatter alloc] init];
    byteFormatter.allowedUnits = NSByteCountFormatterUseGB;
    byteFormatter.countStyle = NSByteCountFormatterCountStyleMemory;
    NSString *memoryString = [byteFormatter stringFromByteCount:memoryBytes];
    return memoryString;
}

- (void)memoryLoggingOutput {
    if (@available(iOS 13.0, *)) {
        NSLog(@"Physical memory available: %@", [self memoryStringForBytes:[NSProcessInfo processInfo].physicalMemory]);
        NSLog(@"Memory A (brackets): %@", [self memoryStringForBytes:(long)os_proc_available_memory()]);
        NSLog(@"Memory B (no brackets): %@", [self memoryStringForBytes:(long)os_proc_available_memory]);
    }
}

Important note: Do not forget the () at the end. I have included both NSLog options in in the memoryLoggingOutput method because it does not warn you that they are missing and failure to include the brackets returns an unexpected yet constant result.

The string returned from the method memoryStringForBytes outputs values like so:

NSLog(@"%@", [self memoryStringForBytes:(long)os_proc_available_memory()]); // 1.93 GB
// 2 seconds later
NSLog(@"%@", [self memoryStringForBytes:(long)os_proc_available_memory()]); // 1.84 GB

Phone number formatting an EditText in Android

Follow the instructions in this Answer to format the EditText mask.

https://stackoverflow.com/a/34907607/1013929

And after that, you can catch the original numbers from the masked string with:

String phoneNumbers = maskedString.replaceAll("[^\\d]", "");

How to set 00:00:00 using moment.js

You've not shown how you're creating the string 2016-01-12T23:00:00.000Z, but I assume via .format().

Anyway, .set() is using your local time zone, but the Z in the time string indicates zero time, otherwise known as UTC.

https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators

So I assume your local timezone is 23 hours from UTC?

saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format() call that outputs using your local timezone, rather than UTC.

http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/

What is Mocking?

Other answers explain what mocking is. Let me walk you through it with different examples. And believe me, it's actually far more simpler than you think.

tl;dr It's an instance of the original class. It has other data injected into so you avoid testing the injected parts and solely focus on testing the implementation details of your class/functions.

Simple example:

class Foo {
    func add (num1: Int, num2: Int) -> Int { // Line A 
        return num1 + num2 // Line B
    }
}

let unit = Foo() // unit under test
assertEqual(unit.add(1,5),6)

As you can see, I'm not testing LineA ie I'm not validating the input parameters. I'm not validating to see if num1, num2 are an Integer. I have no asserts against that.

I'm only testing to see if LineB (my implementation) given the mocked values 1 and 5 is doing as I expect.

Obviously in the real word this can become much more complex. The parameters can be a custom object like a Person, Address, or the implementation details can be more than a single +. But the logic of testing would be the same.

Non-coding Example:

Assume you're building a machine that identifies the type and brand name of electronic devices for an airport security. The machine does this by processing what it sees with its camera.

Now your manager walks in the door and asks you to unit-test it.

Then you as a developer you can either bring 1000 real objects, like a MacBook pro, Google Nexus, a banana, an iPad etc in front of it and test and see if it all works.

But you can also use mocked objects, like an identical looking MacBook pro (with no real internal parts) or a plastic banana in front of it. You can save yourself from investing in 1000 real laptops and rotting bananas.

The point is you're not trying to test if the banana is fake or not. Nor testing if the laptop is fake or not. All you're doing is testing if your machine once it sees a banana it would say not an electronic device and for a MacBook Pro it would say: Laptop, Apple. To the machine, the outcome of its detection should be the same for fake/mocked electronics and real electronics. If your machine also factored in the internals of a laptop (x-ray scan) or banana then your mocks' internals need to look the same as well. But you could also use a gadget with a friend motherboard. Had your machine tested whether or not devices can power on then well you'd need real devices.

The logic mentioned above applies to unit-testing of actual code as well. That is a function should work the same with real values you get from real input (and interactions) or mocked values you inject during unit-testing. And just as how you save yourself from using a real banana or MacBook, with unit-tests (and mocking) you save yourself from having to do something that causes your server to return a status code of 500, 403, 200, etc (forcing your server to trigger 500 is only when server is down, while 200 is when server is up. It gets difficult to run 100 network focused tests if you have to constantly wait 10 seconds between switching over server up and down). So instead you inject/mock a response with status code 500, 200, 403, etc and test your unit/function with a injected/mocked value.

Be aware:

Sometimes you don't correctly mock the actual object. Or you don't mock every possibility. E.g. your fake laptops are dark, and your machine accurately works with them, but then it doesn't work accurately with white fake laptops. Later when you ship this machine to customers they complain that it doesn't work all the time. You get random reports that it's not working. It takes you 3 months of time to finally figure out that the color of fake laptops need to be more varied so you can test your modules appropriately.

For a true coding example, your implementation may be different for status code 200 with image data returned vs 200 with image data not returned. For this reason it's good to use an IDE that provides code coverage e.g. the image below shows that your unit-tests don't ever go through the lines marked with brown.

enter image description here

image source

Real world coding Example:

Let's say you are writing an iOS application and have network calls.Your job is to test your application. To test/identify whether or not the network calls work as expected is NOT YOUR RESPONSIBILITY . It's another party's (server team) responsibility to test it. You must remove this (network) dependency and yet continue to test all your code that works around it.

A network call can return different status codes 404, 500, 200, 303, etc with a JSON response.

Your app is suppose to work for all of them (in case of errors, your app should throw its expected error). What you do with mocking is you create 'imaginary—similar to real' network responses (like a 200 code with a JSON file) and test your code without 'making the real network call and waiting for your network response'. You manually hardcode/return the network response for ALL kinds of network responses and see if your app is working as you expect. (you never assume/test a 200 with incorrect data, because that is not your responsibility, your responsibility is to test your app with a correct 200, or in case of a 400, 500, you test if your app throws the right error)

This creating imaginary—similar to real is known as mocking.

In order to do this, you can't use your original code (your original code doesn't have the pre-inserted responses, right?). You must add something to it, inject/insert that dummy data which isn't normally needed (or a part of your class).

So you create an instance the original class and add whatever (here being the network HTTPResponse, data OR in the case of failure, you pass the correct errorString, HTTPResponse) you need to it and then test the mocked class.

Long story short, mocking is to simplify and limit what you are testing and also make you feed what a class depends on. In this example you avoid testing the network calls themselves, and instead test whether or not your app works as you expect with the injected outputs/responses —— by mocking classes

Needless to say, you test each network response separately.


Now a question that I always had in my mind was: The contracts/end points and basically the JSON response of my APIs get updated constantly. How can I write unit tests which take this into consideration?

To elaborate more on this: let’s say model requires a key/field named username. You test this and your test passes. 2 weeks later backend changes the key's name to id. Your tests still passes. right? or not?

Is it the backend developer’s responsibility to update the mocks. Should it be part of our agreement that they provide updated mocks?

The answer to the above issue is that: unit tests + your development process as a client-side developer should/would catch outdated mocked response. If you ask me how? well the answer is:

Our actual app would fail (or not fail yet not have the desired behavior) without using updated APIs...hence if that fails...we will make changes on our development code. Which again leads to our tests failing....which we’ll have to correct it. (Actually if we are to do the TDD process correctly we are to not write any code about the field unless we write the test for it...and see it fail and then go and write the actual development code for it.)

This all means that backend doesn’t have to say: “hey we updated the mocks”...it eventually happens through your code development/debugging. ??Because it’s all part of the development process! Though if backend provides the mocked response for you then it's easier.

My whole point on this is that (if you can’t automate getting updated mocked API response then) some human interaction is required ie manual updates of JSONs and having short meetings to make sure their values are up to date will become part of your process

This section was written thanks to a slack discussion in our CocoaHead meetup group


For iOS devs only:

A very good example of mocking is this Practical Protocol-Oriented talk by Natasha Muraschev. Just skip to minute 18:30, though the slides may become out of sync with the actual video ???

I really like this part from the transcript:

Because this is testing...we do want to make sure that the get function from the Gettable is called, because it can return and the function could theoretically assign an array of food items from anywhere. We need to make sure that it is called;

How to include route handlers in multiple files in Express?

I wrote a small plugin for doing this! got sick of writing the same code over and over.

https://www.npmjs.com/package/js-file-req

Hope it helps.

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

What is a 'multi-part identifier' and why can't it be bound?

When you type the FROM table those errors will disappear. Type FROM below what your typing then Intellisense will work and multi-part identifier will work.

Cmake doesn't find Boost

Maybe

brew install boost

will help you.

implements Closeable or implements AutoCloseable

The try-with-resources Statement.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }

}

Please refer to the docs.

How do I uninstall a package installed using npm link?

The package can be uninstalled using the same uninstall or rm command that can be used for removing installed packages. The only thing to keep in mind is that the link needs to be uninstalled globally - the --global flag needs to be provided.

In order to uninstall the globally linked foo package, the following command can be used (using sudo if necessary, depending on your setup and permissions)

sudo npm rm --global foo

This will uninstall the package.

To check whether a package is installed, the npm ls command can be used:

npm ls --global foo

TimeSpan to DateTime conversion

First, convert the timespan to a string, then to DateTime, then back to a string:

Convert.ToDateTime(timespan.SelectedTime.ToString()).ToShortTimeString();

How do I know which version of Javascript I'm using?

Wikipedia (or rather, the community on Wikipedia) keeps a pretty good up-to-date list here.

  • Most browsers are on 1.5 (though they have features of later versions)
  • Mozilla progresses with every dot release (they maintain the standard so that's not surprising)
  • Firefox 4 is on JavaScript 1.8.5
  • The other big off-the-beaten-path one is IE9 - it implements ECMAScript 5, but doesn't implement all the features of JavaScript 1.8.5 (not sure what they're calling this version of JScript, engine codenamed Chakra, yet).

Error: Local workspace file ('angular.json') could not be found

I was getting the same error messages. It was a silly mistake on my end, I was not running ng serve in the directory where my Angular project is. Make sure you are in the correct directory (project directory) before running this command.

Java code To convert byte to Hexadecimal

Use

Integer.toHexString((int)b);

C# Iterate through Class properties

You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.

For a hint, you could possibly do something like:

Record record = new Record();

PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
    property.SetValue(record, value);
}

Where value is the value you're wanting to write in (so from your resultItems array).

Preferred Java way to ping an HTTP URL for availability

You could also use HttpURLConnection, which allows you to set the request method (to HEAD for example). Here's an example that shows how to send a request, read the response, and disconnect.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Try like this,

jQuery('.leaderMultiSelctdropdown').select2('data');

How to get size of mysql database?

To get a result in MB:

SELECT
SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024), 2)) AS "SIZE IN MB"
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = "SCHEMA-NAME";

To get a result in GB:

SELECT
SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024 / 1024), 2)) AS "SIZE IN GB"
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = "SCHEMA-NAME";

If statement with String comparison fails

Strings in java are objects, so when comparing with ==, you are comparing references, rather than values. The correct way is to use equals().

However, there is a way. If you want to compare String objects using the == operator, you can make use of the way the JVM copes with strings. For example:

String a = "aaa";
String b = "aaa";
boolean b = a == b;

b would be true. Why?

Because the JVM has a table of String constants. So whenever you use string literals (quotes "), the virtual machine returns the same objects, and therefore == returns true.

You can use the same "table" even with non-literal strings by using the intern() method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:

String a = new String("aa");
String b = new String("aa");
boolean check1 = a == b; // false
boolean check1 = a.intern() == b.intern(); // true

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

How do I restrict a float value to only two places after the decimal point in C?

Use float roundf(float x).

"The round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction." C11dr §7.12.9.5

#include <math.h>
float y = roundf(x * 100.0f) / 100.0f; 

Depending on your float implementation, numbers that may appear to be half-way are not. as floating-point is typically base-2 oriented. Further, precisely rounding to the nearest 0.01 on all "half-way" cases is most challenging.

void r100(const char *s) {
  float x, y;
  sscanf(s, "%f", &x);
  y = round(x*100.0)/100.0;
  printf("%6s %.12e %.12e\n", s, x, y);
}

int main(void) {
  r100("1.115");
  r100("1.125");
  r100("1.135");
  return 0;
}

 1.115 1.115000009537e+00 1.120000004768e+00  
 1.125 1.125000000000e+00 1.129999995232e+00
 1.135 1.134999990463e+00 1.139999985695e+00

Although "1.115" is "half-way" between 1.11 and 1.12, when converted to float, the value is 1.115000009537... and is no longer "half-way", but closer to 1.12 and rounds to the closest float of 1.120000004768...

"1.125" is "half-way" between 1.12 and 1.13, when converted to float, the value is exactly 1.125 and is "half-way". It rounds toward 1.13 due to ties to even rule and rounds to the closest float of 1.129999995232...

Although "1.135" is "half-way" between 1.13 and 1.14, when converted to float, the value is 1.134999990463... and is no longer "half-way", but closer to 1.13 and rounds to the closest float of 1.129999995232...

If code used

y = roundf(x*100.0f)/100.0f;

Although "1.135" is "half-way" between 1.13 and 1.14, when converted to float, the value is 1.134999990463... and is no longer "half-way", but closer to 1.13 but incorrectly rounds to float of 1.139999985695... due to the more limited precision of float vs. double. This incorrect value may be viewed as correct, depending on coding goals.

How to force a UIViewController to Portrait orientation in iOS 6

I have a very good approach mixing https://stackoverflow.com/a/13982508/2516436 and https://stackoverflow.com/a/17578272/2516436

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    NSUInteger orientations = UIInterfaceOrientationMaskAllButUpsideDown;


    if(self.window.rootViewController){
        UIViewController *presentedViewController = [self topViewControllerWithRootViewController:self.window.rootViewController];
        orientations = [presentedViewController supportedInterfaceOrientations];
    }

    return orientations;
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}

and return whatever orientations you want to support for each UIViewController

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

How to set the LDFLAGS in CMakeLists.txt?

Look at:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

import { HttpClientModule } from '@angular/common/http';

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below

http.get('friends.json').subscribe(result => this.result =result);

How to convert Seconds to HH:MM:SS using T-SQL

This is what I use (typically for html table email reports)

declare @time int, @hms varchar(20)
set @time = 12345
set @hms = cast(cast((@Time)/3600 as int) as varchar(3)) 
  +':'+ right('0'+ cast(cast(((@Time)%3600)/60 as int) as varchar(2)),2) 
  +':'+ right('0'+ cast(((@Time)%3600)%60 as varchar(2)),2) +' (hh:mm:ss)'
select @hms

Rails: Why "sudo" command is not recognized?

sudo is a command for Linux so it cant be used in windows so you will get that error

How to check the version of scipy

From the python command prompt:

import scipy
print scipy.__version__

In python 3 you'll need to change it to:

print (scipy.__version__)

Developing C# on Linux

I would suggest using MonoDevelop.

It is pretty much explicitly designed for use with Mono, and all set up to develop in C#.

The simplest way to install it on Ubuntu would be to install the monodevelop package in Ubuntu. (link on Mono on ubuntu.com) (However, if you want to install a more recent version, I am not sure which PPA would be appropriate)

However, I would not recommend developing with the WinForms toolkit - I do not expect it to have the same behavior in Windows and Mono (the implementations are pretty different). For an overview of the UI toolkits that work with Mono, you can go to the information page on Mono-project.

How to output (to a log) a multi-level array in a format that is human-readable?

http://php.net/manual/en/function.print-r.php This function can be used to format output,

$output = print_r($array,1);

$output is a string variable, it can be logged like every other string. In pure php you can use trigger_error

Ex. trigger_error($output);

http://php.net/manual/en/function.trigger-error.php

if you need to format it also in html, you can use <pre> tag

How to check if curl is enabled or disabled

var_dump(extension_loaded('curl'));

Shall we always use [unowned self] inside closure in Swift

No, there are definitely times where you would not want to use [unowned self]. Sometimes you want the closure to capture self in order to make sure that it is still around by the time the closure is called.

Example: Making an asynchronous network request

If you are making an asynchronous network request you do want the closure to retain self for when the request finishes. That object may have otherwise been deallocated but you still want to be able to handle the request finishing.

When to use unowned self or weak self

The only time where you really want to use [unowned self] or [weak self] is when you would create a strong reference cycle. A strong reference cycle is when there is a loop of ownership where objects end up owning each other (maybe through a third party) and therefore they will never be deallocated because they are both ensuring that each other stick around.

In the specific case of a closure, you just need to realize that any variable that is referenced inside of it, gets "owned" by the closure. As long as the closure is around, those objects are guaranteed to be around. The only way to stop that ownership, is to do the [unowned self] or [weak self]. So if a class owns a closure, and that closure captures a strong reference to that class, then you have a strong reference cycle between the closure and the class. This also includes if the class owns something that owns the closure.

Specifically in the example from the video

In the example on the slide, TempNotifier owns the closure through the onChange member variable. If they did not declare self as unowned, the closure would also own self creating a strong reference cycle.

Difference between unowned and weak

The difference between unowned and weak is that weak is declared as an Optional while unowned is not. By declaring it weak you get to handle the case that it might be nil inside the closure at some point. If you try to access an unowned variable that happens to be nil, it will crash the whole program. So only use unowned when you are positive that variable will always be around while the closure is around

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Give Safe User Permission To Use Port 80

Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/

Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port - where port number > 1024.

A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``

Now, when you tell a Node application that you want it to run on port 80, it will not complain.

Check this reference link

How to test the `Mosquitto` server?

If you wish to have an GUI based broker testing without installing any tool you can use Hive Mqtt web socket for testing your Mosquitto server

just visit http://www.hivemq.com/demos/websocket-client/ and enter server connection details.

If you got connected means your server is configured properly.

You can also test publish and subscribe of messages using this mqtt web socket

How to ignore a property in class if null, using json.net

With Json.NET

 public class Movie
 {
            public string Name { get; set; }
            public string Description { get; set; }
            public string Classification { get; set; }
            public string Studio { get; set; }
            public DateTime? ReleaseDate { get; set; }
            public List<string> ReleaseCountries { get; set; }
 }

 Movie movie = new Movie();
 movie.Name = "Bad Boys III";
 movie.Description = "It's no Bad Boys";

 string ignored = JsonConvert.SerializeObject(movie,
            Formatting.Indented,
            new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

The result will be:

{
   "Name": "Bad Boys III",
   "Description": "It's no Bad Boys"
 }

Using multiple IF statements in a batch file

Batch files have really very limited logic powers so the best you can hope to come up with is a good workaround that indirectly achieves what you want. That's not to say that you should feel they are inferior to a real language - they still demand the same attention to detail and manual debugging as a real application. It's just that you'll need to work a lot harder to make them do what you want in a robust manner.

For the OP's question it sounds like you require two specific files to exist. Just use a tally:

IF EXIST somefile.txt (
    set /a file1_status=1
)

IF EXIST someotehrfile.txt (
    set /a file2_status=1
)

set /a file_status_result=file1_status + file2_status

if %file_status_result% equ 2 (
    goto somefileexists
)

goto exit

:somefileexists
IF EXIST someotherfile.txt SET var=...

:exit

My example uses 3 variables, but you could just add 1 to file_result_status if the file exists. But if you want more granular control later in your batch file you can record the result for each file as I have done so you don't have to keep checking if a file exists later on.

Maximum filename length in NTFS (Windows XP and Windows Vista)?

It's 257 characters. To be precise: NTFS itself does impose a maximum filename-length of several thousand characters (around 30'000 something). However, Windows imposes a 260 maximum length for the Path+Filename. The drive+folder takes up at least 3 characters, so you end up with 257.

Proper use of 'yield return'

Return the list directly. Benefits:

  • It's more clear
  • The list is reusable. (the iterator is not) not actually true, Thanks Jon

You should use the iterator (yield) from when you think you probably won't have to iterate all the way to the end of the list, or when it has no end. For example, the client calling is going to be searching for the first product that satisfies some predicate, you might consider using the iterator, although that's a contrived example, and there are probably better ways to accomplish it. Basically, if you know in advance that the whole list will need to be calculated, just do it up front. If you think that it won't, then consider using the iterator version.

Html helper for <input type="file" />

You can also use:

@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <p>
        <input type="file" id="fileUpload" name="fileUpload" size="23" />
    </p>
    <p>
        <input type="submit" value="Upload file" /></p> 
}

Get request URL in JSP which is forwarded by Servlet

Try this,

<c:set var="pageUrl" scope="request">
    <c:out value="${pageContext.request.scheme}://${pageContext.request.serverName}"/>
    <c:if test="${pageContext.request.serverPort != '80'}">
        <c:out value=":${pageContext.request.serverPort}"/>
    </c:if>
    <c:out value="${requestScope['javax.servlet.forward.request_uri']}"/>
</c:set>

I would like to put it in my base template and use in whole app whenever i need to.

How to use template module with different set of variables?

I had a similar problem to solve, here is a simple solution of how to pass variables to template files, the trick is to write the template file taking advantage of the variable. You need to create a dictionary (list is also possible), which holds the set of variables corresponding to each of the file. Then within the template file access them.

see below:

the template file: test_file.j2
# {{ ansible_managed }} created by [email protected]

{% set dkey  = (item | splitext)[0]  %}
{% set fname = test_vars[dkey].name  %}
{% set fip   = test_vars[dkey].ip    %}
{% set fport = test_vars[dkey].port  %}
filename: {{ fname }}
ip address: {{ fip }}
port: {{ fport }}

the playbook

---
#
# file: template_test.yml
# author: [email protected]
#
# description: playbook to demonstrate passing variables to template files
#
# this playbook will create 3 files from a single template, with different
# variables passed for each of the invocation
#
# usage:
# ansible-playbook -i "localhost," template_test.yml

- name: template variables testing
  hosts: all
  gather_facts: false

  vars:
    ansible_connection: local
    dest_dir: "/tmp/ansible_template_test/"
    test_files:
      - file_01.txt
      - file_02.txt
      - file_03.txt
    test_vars:
      file_01:
        name: file_01.txt
        ip: 10.0.0.1
        port: 8001
      file_02:
        name: file_02.txt
        ip: 10.0.0.2
        port: 8002
      file_03:
        name: file_03.txt
        ip: 10.0.0.3
        port: 8003

  tasks:
    - name: copy the files
      template:
        src: test_file.j2
        dest: "{{ dest_dir }}/{{ item }}"
      with_items:
        - "{{ test_files }}"

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

Look at your actual html code and check that the weird symbols are not originating there. This issue came up when I started coding in Notepad++ halfway after coding in Notepad. It seems to me that the older version of Notepad I was using may have used different encoding to Notepad's++ UTF-8 encoding. After I transferred my code from Notepad to Notepad++, the apostrophes got replaced with weird symbols, so I simply had to remove the symbols from my Notepad++ code.

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

Fast check for NaN in NumPy

There are two general approaches here:

  • Check each array item for nan and take any.
  • Apply some cumulative operation that preserves nans (like sum) and check its result.

While the first approach is certainly the cleanest, the heavy optimization of some of the cumulative operations (particularly the ones that are executed in BLAS, like dot) can make those quite fast. Note that dot, like some other BLAS operations, are multithreaded under certain conditions. This explains the difference in speed between different machines.

enter image description here

import numpy
import perfplot


def min(a):
    return numpy.isnan(numpy.min(a))


def sum(a):
    return numpy.isnan(numpy.sum(a))


def dot(a):
    return numpy.isnan(numpy.dot(a, a))


def any(a):
    return numpy.any(numpy.isnan(a))


def einsum(a):
    return numpy.isnan(numpy.einsum("i->", a))


perfplot.show(
    setup=lambda n: numpy.random.rand(n),
    kernels=[min, sum, dot, any, einsum],
    n_range=[2 ** k for k in range(20)],
    logx=True,
    logy=True,
    xlabel="len(a)",
)

Sql script to find invalid email addresses

select * from users 
WHERE NOT
(     CHARINDEX(' ',LTRIM(RTRIM([Email]))) = 0 
AND  LEFT(LTRIM([Email]),1) <> '@' 
AND  RIGHT(RTRIM([Email]),1) <> '.' 
AND  CHARINDEX('.',[Email],CHARINDEX('@',[Email])) - CHARINDEX('@',[Email]) > 1 
AND  LEN(LTRIM(RTRIM([Email]))) - LEN(REPLACE(LTRIM(RTRIM([Email])),'@','')) = 1 
AND  CHARINDEX('.',REVERSE(LTRIM(RTRIM([Email])))) >= 3 
AND  (CHARINDEX('.@',[Email]) = 0 AND CHARINDEX('..',[Email]) = 0) 

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, you can. The ability to compare values to zeros implicitly has been inherited from C, and is there in all versions of C++. You can also use if (!pointer) to check pointers for NULL.

How does functools partial do what it does?

In my opinion, it's a way to implement currying in python.

from functools import partial
def add(a,b):
    return a + b

def add2number(x,y,z):
    return x + y + z

if __name__ == "__main__":
    add2 = partial(add,2)
    print("result of add2 ",add2(1))
    add3 = partial(partial(add2number,1),2)
    print("result of add3",add3(1))

The result is 3 and 4.

jQuery Remove string from string

Pretty sure nobody answer your question to your exact terms, you want it for dynamic text

var newString = myString.substring( myString.indexOf( "," ) +1, myString.length );

It takes a substring from the first comma, to the end

Convert array of indices to 1-hot encoded numpy array

  • p will be a 2d ndarray.
  • We want to know which value is the highest in a row, to put there 1 and everywhere else 0.

clean and easy solution:

max_elements_i = np.expand_dims(np.argmax(p, axis=1), axis=1)
one_hot = np.zeros(p.shape)
np.put_along_axis(one_hot, max_elements_i, 1, axis=1)

How do you find out the caller function in JavaScript?

Works great for me, and you can chose how much you want to go back in the functions:

function getCaller(functionBack= 0) {
    const back = functionBack * 2;
    const stack = new Error().stack.split('at ');
    const stackIndex = stack[3 + back].includes('C:') ? (3 + back) : (4 + back);
    const isAsync = stack[stackIndex].includes('async');
    let result;
    if (isAsync)
      result = stack[stackIndex].split(' ')[1].split(' ')[0];
    else
      result = stack[stackIndex].split(' ')[0];
    return result;
}

Android: show soft keyboard automatically when focus is on an EditText

Let me point some additional info to the solution of yuku, because I found it hard to get this working! How do I get the AlertDialog object from my AlertDialog.Builder? Well, it's the result of my alert.show() execution:

final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
alert.setView(input);

// do what you need, like setting positive and negative buttons...

final AlertDialog dialog = alert.show();

input.setOnFocusChangeListener(new OnFocusChangeListener() {
   @Override
   public void onFocusChange(View v, boolean hasFocus) {
      if(hasFocus) {
         dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
      }
   }
});

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

just run these command

sudo apt-get install phpmyadmin php-mbstring php-gettext

sudo service apache2 restart

Or you can follow this post...

Check This Post

Python: list of lists

Time traveller here

List_of_list =[([z for z in range(x-2,x+1) if z >= 0],y) for y in range(10) for x in range(10)]

This should do the trick. And the output is this:

[([0], 0), ([0, 1], 0), ([0, 1, 2], 0), ([1, 2, 3], 0), ([2, 3, 4], 0),  ([3, 4, 5], 0), ([4, 5, 6], 0), ([5, 6, 7], 0), ([6, 7, 8], 0), ([7, 8, 9], 0), ([0], 1), ([0, 1], 1), ([0, 1, 2], 1), ([1, 2, 3], 1), ([2, 3, 4], 1), ([3, 4, 5], 1), ([4, 5, 6], 1), ([5, 6, 7], 1), ([6, 7, 8], 1), ([7, 8, 9], 1), ([0], 2), ([0, 1], 2), ([0, 1, 2], 2), ([1, 2, 3], 2), ([2, 3, 4], 2), ([3, 4, 5], 2), ([4, 5, 6], 2), ([5, 6, 7], 2), ([6, 7, 8], 2), ([7, 8, 9], 2), ([0], 3), ([0, 1], 3), ([0, 1, 2], 3), ([1, 2, 3], 3), ([2, 3, 4], 3), ([3, 4, 5], 3), ([4, 5, 6], 3), ([5, 6, 7], 3), ([6, 7, 8], 3), ([7, 8, 9], 3), ([0], 4), ([0, 1], 4), ([0, 1, 2], 4), ([1, 2, 3], 4), ([2, 3, 4], 4), ([3, 4, 5], 4), ([4, 5, 6], 4), ([5, 6, 7], 4), ([6, 7, 8], 4), ([7, 8, 9], 4), ([0], 5), ([0, 1], 5), ([0, 1, 2], 5), ([1, 2, 3], 5), ([2, 3, 4], 5), ([3, 4, 5], 5), ([4, 5, 6], 5), ([5, 6, 7], 5), ([6, 7, 8], 5), ([7, 8, 9], 5), ([0], 6), ([0, 1], 6), ([0, 1, 2], 6), ([1, 2, 3], 6), ([2, 3, 4], 6), ([3, 4, 5], 6), ([4, 5, 6], 6), ([5, 6, 7], 6), ([6, 7, 8], 6), ([7, 8, 9], 6), ([0], 7), ([0, 1], 7), ([0, 1, 2], 7), ([1, 2, 3], 7), ([2, 3, 4], 7), ([3, 4, 5], 7), ([4, 5, 6], 7), ([5, 6, 7], 7), ([6, 7, 8], 7), ([7, 8, 9], 7), ([0], 8), ([0, 1], 8), ([0, 1, 2], 8), ([1, 2, 3], 8), ([2, 3, 4], 8), ([3, 4, 5], 8), ([4, 5, 6], 8), ([5, 6, 7], 8), ([6, 7, 8], 8), ([7, 8, 9], 8), ([0], 9), ([0, 1], 9), ([0, 1, 2], 9), ([1, 2, 3], 9), ([2, 3, 4], 9), ([3, 4, 5], 9), ([4, 5, 6], 9), ([5, 6, 7], 9), ([6, 7, 8], 9), ([7, 8, 9], 9)]    

This is done by list comprehension(which makes looping elements in a list via one line code possible). The logic behind this one-line code is the following:

(1) for x in range(10) and for y in range(10) are employed for two independent loops inside a list

(2) (a list, y) is the general term of the loop, which is why it is placed before two for's in (1)

(3) the length of the list in (2) cannot exceed 3, and the list depends on x, so

[z for z in range(x-2,x+1)] 

is used

(4) because z starts from zero but range(x-2,x+1) starts from -2 which isn't what we want, so a conditional statement if z >= 0 is placed at the end of the list in (2)

[z for z in range(x-2,x+1) if z >= 0] 

Flask Python Buttons

Apply (different) name attribute to both buttons like

<button name="one">

and catch them in request.data.

How to permanently remove few commits from remote branch

 git reset --soft commit_id
 git stash save "message"
 git reset --hard commit_id
 git stash apply stash stash@{0}
 git push --force

`IF` statement with 3 possible answers each based on 3 different ranges

=IF(X2>=85,0.559,IF(X2>=80,0.327,IF(X2>=75,0.255,-1)))

Explanation:

=IF(X2>=85,                  'If the value is in the highest bracket
      0.559,                 'Use the appropriate number
      IF(X2>=80,             'Otherwise, if the number is in the next highest bracket
           0.327,            'Use the appropriate number
           IF(X2>=75,        'Otherwise, if the number is in the next highest bracket
              0.255,         'Use the appropriate number
              -1             'Otherwise, we're not in any of the ranges (Error)
             )
        )
   )

Algorithm/Data Structure Design Interview Questions

This doesn't necessarily touch on OOP capabilities but in our last set of interviews we used a selection of buggy code from the Bug of the Month list. Watching the candidates find the bugs shows their analytical capabilities, shows the know how to interpret somebody elses code

Transparent background on winforms?

I've tried the solutions above (and also) many other solutions from other posts.

In my case, I did it with the following setup:

public partial class WaitingDialog : Form
{
    public WaitingDialog()
    {
        InitializeComponent();

        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        this.BackColor = Color.Transparent;

        // Other stuff
    }

    protected override void OnPaintBackground(PaintEventArgs e) { /* Ignore */ }
}

As you can see, this is a mix of previously given answers.

NuGet behind a proxy

Apart from the suggestions from @arcain I had to add the following Windows Azure Content Delivery Network url to our proxy server's the white-list:

.msecnd.net

OR is not supported with CASE Statement in SQL Server

CASE WHEN ebv.db_no IN (22978, 23218, 23219) THEN 'WECS 9500' 
 ELSE 'WECS 9520' 
END as wecs_system 

Bash script prints "Command Not Found" on empty lines

You may want to update you .bashrc and .bash_profile files with aliases to recognize the command you are entering.

.bashrc and .bash_profile files are hidden files probably located on your C: drive where you save your program files.

What's the difference between nohup and ampersand

The nohup command is a signal masking utility and catches the hangup signal. Where as ampersand doesn’t catch the hang up signals. The shell will terminate the sub command with the hang up signal when running a command using & and exiting the shell. This can be prevented by using nohup, as it catches the signal. Nohup command accept hang up signal which can be sent to a process by the kernel and block them. Nohup command is helpful in when a user wants to start long running application log out or close the window in which the process was initiated. Either of these actions normally prompts the kernel to hang up on the application, but a nohup wrapper will allow the process to continue. Using the ampersand will run the command in a child process and this child of the current bash session. When you exit the session, all of the child processes of that process will be killed. The ampersand relates to job control for the active shell. This is useful for running a process in a session in the background.

Clearing Magento Log Data

After clean the logs using any of the methods described above you can also disable them in your app/etc/local.xml

...
<frontend>
<events>
 <frontend>
  <events>
    <!-- disable Mage_Log -->
    <controller_action_predispatch>
        <observers><log><type>disabled</type></log></observers>
    </controller_action_predispatch>
    <controller_action_postdispatch>
        <observers><log><type>disabled</type></log></observers>
    </controller_action_postdispatch>
    <customer_login>
      <observers>
        <log>
          <type>disabled</type>
        </log>
      </observers>
    </customer_login>
    <customer_logout>
      <observers>
        <log>
          <type>disabled</type>
        </log>
      </observers>
    </customer_logout>
    <sales_quote_save_after>
       <observers>
          <log>
              <type>disabled</type>
          </log>
        </observers>
   </sales_quote_save_after>
   <checkout_quote_destroy>
     <observers>
       <log>
         <type>disabled</type>
       </log>
     </observers>
   </checkout_quote_destroy>
</events>
</frontend>
</config>

asynchronous vs non-blocking

Synchronous is defined as happening at the same time.

Asynchronous is defined as not happening at the same time.

This is what causes the first confusion. Synchronous is actually what is known as parallel. While asynchronous is sequential, do this, then do that.

Now the whole problem is about modeling an asynchronous behaviour, because you've got some operation that needs the response of another before it can begin. Thus it's a coordination problem, how will you know that you can now start that operation?

The simplest solution is known as blocking.

Blocking is when you simply choose to wait for the other thing to be done and return you a response before moving on to the operation that needed it.

So if you need to put butter on toast, and thus you first need to toast the bred. The way you'd coordinate them is that you'd first toast the bred, then stare endlessly at the toaster until it pops the toast, and then you'd proceed to put butter on them.

It's the simplest solution, and works very well. There's no real reason not to use it, unless you happen to also have other things you need to be doing which don't require coordination with the operations. For example, doing some dishes. Why wait idle staring at the toaster constantly for the toast to pop, when you know it'll take a bit of time, and you could wash a whole dish while it finishes?

That's where two other solutions known respectively as non-blocking and asynchronous come into play.

Non-blocking is when you choose to do other unrelated things while you wait for the operation to be done. Checking back on the availability of the response as you see fit.

So instead of looking at the toaster for it to pop. You go and wash a whole dish. And then you peek at the toaster to see if the toasts have popped. If they havn't, you go wash another dish, checking back at the toaster between each dish. When you see the toasts have popped, you stop washing the dishes, and instead you take the toast and move on to putting butter on them.

Having to constantly check on the toasts can be annoying though, imagine the toaster is in another room. In between dishes you waste your time going to that other room to check on the toast.

Here comes asynchronous.

Asynchronous is when you choose to do other unrelated things while you wait for the operation to be done. Instead of checking on it though, you delegate the work of checking to something else, could be the operation itself or a watcher, and you have that thing notify and possibly interupt you when the response is availaible so you can proceed to the other operation that needed it.

Its a weird terminology. Doesn't make a whole lot of sense, since all these solutions are ways to create asynchronous coordination of dependent tasks. That's why I prefer to call it evented.

So for this one, you decide to upgrade your toaster so it beeps when the toasts are done. You happen to be constantly listening, even while you are doing dishes. On hearing the beep, you queue up in your memory that as soon as you are done washing your current dish, you'll stop and go put the butter on the toast. Or you could choose to interupt the washing of the current dish, and deal with the toast right away.

If you have trouble hearing the beep, you can have your partner watch the toaster for you, and come tell you when the toast is ready. Your partner can itself choose any of the above three strategies to coordinate its task of watching the toaster and telling you when they are ready.

On a final note, it's good to understand that while non-blocking and async (or what I prefer to call evented) do allow you to do other things while you wait, you don't have too. You can choose to constantly loop on checking the status of a non-blocking call, doing nothing else. That's often worse than blocking though (like looking at the toaster, then away, then back at it until its done), so a lot of non-blocking APIs allow you to transition into a blocking mode from it. For evented, you can just wait idle until you are notified. The downside in that case is that adding the notification was complex and potentially costly to begin with. You had to buy a new toaster with beep functionality, or convince your partner to watch it for you.

And one more thing, you need to realize the trade offs all three provide. One is not obviously better than the others. Think of my example. If your toaster is so fast, you won't have time to wash a dish, not even begin washing it, that's how fast your toaster is. Getting started on something else in that case is just a waste of time and effort. Blocking will do. Similarly, if washing a dish will take 10 times longer then the toasting. You have to ask yourself what's more important to get done? The toast might get cold and hard by that time, not worth it, blocking will also do. Or you should pick faster things to do while you wait. There's more obviously, but my answer is already pretty long, my point is you need to think about all that, and the complexities of implementing each to decide if its worth it, and if it'll actually improve your throughput or performance.

Edit:

Even though this is already long, I also want it to be complete, so I'll add two more points.

  1. There also commonly exists a fourth model known as multiplexed. This is when while you wait for one task, you start another, and while you wait for both, you start one more, and so on, until you've got many tasks all started and then, you wait idle, but on all of them. So as soon as any is done, you can proceed with handling its response, and then go back to waiting for the others. It's known as multiplexed, because while you wait, you need to check each task one after the other to see if they are done, ad vitam, until one is. It's a bit of an extension on top of normal non-blocking.

In our example it would be like starting the toaster, then the dishwasher, then the microwave, etc. And then waiting on any of them. Where you'd check the toaster to see if it's done, if not, you'd check the dishwasher, if not, the microwave, and around again.

  1. Even though I believe it to be a big mistake, synchronous is often used to mean one thing at a time. And asynchronous many things at a time. Thus you'll see synchronous blocking and non-blocking used to refer to blocking and non-blocking. And asynchronous blocking and non-blocking used to refer to multiplexed and evented.

I don't really understand how we got there. But when it comes to IO and Computation, synchronous and asynchronous often refer to what is better known as non-overlapped and overlapped. That is, asynchronous means that IO and Computation are overlapped, aka, happening concurrently. While synchronous means they are not, thus happening sequentially. For synchronous non-blocking, that would mean you don't start other IO or Computation, you just busy wait and simulate a blocking call. I wish people stopped misusing syncronous and asynchronous like that. So I'm not encouraging it.

Long press on UITableView

Looks to be more efficient to add the recognizer directly to the cell as shown here:

Tap&Hold for TableView Cells, Then and Now

(scroll to the example at the bottom)

What is the best way to delete a value from an array in Perl?

Just to be sure I have benchmarked grep and map solutions, first searching for indexes of matched elements (those to remove) and then directly removing the elements by grep without searching for the indexes. I appears that the first solution proposed by Sam when asking his question was already the fastest.

    use Benchmark;
    my @A=qw(A B C A D E A F G H A I J K L A M N);
    my @M1; my @G; my @M2;
    my @Ashrunk;
    timethese( 1000000, {
      'map1' => sub {
          my $i=0;
          @M1 = map { $i++; $_ eq 'A' ? $i-1 : ();} @A;
      },
      'map2' => sub {
          my $i=0;
          @M2 = map { $A[$_] eq 'A' ? $_ : () ;} 0..$#A;
      },
      'grep' => sub {
          @G = grep { $A[$_] eq 'A' } 0..$#A;
      },
      'grem' => sub {
          @Ashrunk = grep { $_ ne 'A' } @A;
      },
    });

The result is:

Benchmark: timing 1000000 iterations of grem, grep, map1, map2...
  grem:  4 wallclock secs ( 3.37 usr +  0.00 sys =  3.37 CPU) @ 296823.98/s (n=1000000)
  grep:  3 wallclock secs ( 2.95 usr +  0.00 sys =  2.95 CPU) @ 339213.03/s (n=1000000)
  map1:  4 wallclock secs ( 4.01 usr +  0.00 sys =  4.01 CPU) @ 249438.76/s (n=1000000)
  map2:  2 wallclock secs ( 3.67 usr +  0.00 sys =  3.67 CPU) @ 272702.48/s (n=1000000)
M1 = 0 3 6 10 15
M2 = 0 3 6 10 15
G = 0 3 6 10 15
Ashrunk = B C D E F G H I J K L M N

As shown by elapsed times, it's useless to try to implement a remove function using either grep or map defined indexes. Just grep-remove directly.

Before testing I was thinking "map1" would be the most efficient... I should more often rely on Benchmark I guess. ;-)

how to remove the bold from a headline?

style is accordingly vis css. An example

<h1 class="mynotsoboldtitle">Im not bold</h1>
<style>
.mynotsoboldtitle { font-weight:normal; }
</style>

Pause in Python

An external WConio module can help here: http://newcenturycomputers.net/projects/wconio.html

import WConio
WConio.getch()

What is the command for cut copy paste a file from one directory to other directory

use the xclip which is command line interface to X selections

install

apt-get install xclip

usage

echo "test xclip " > /tmp/test.xclip
xclip -i < /tmp/test.xclip
xclip -o > /tmp/test.xclip.out

cat /tmp/test.xclip.out   # "test xclip"

enjoy.

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

Maybe it will useful:

    function parseJson(code)
{
    try {
        return JSON.parse(code);
    } catch (e) {
        return code;
    }
}
function parseJsonJQ(code)
{
    try {
        return $.parseJSON(code);
    } catch (e) {
        return code;
    }
}

var str =  "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";
alert(typeof parseJson(str));
alert(typeof parseJsonJQ(str));
var str_b  = "c";
alert(typeof parseJson(str_b));
alert(typeof parseJsonJQ(str_b));

output:

IE7: string,object,string,string

CHROME: object,object,string,string

How can I count the occurrences of a list item?

To count the number of diverse elements having a common type:

li = ['A0','c5','A8','A2','A5','c2','A3','A9']

print sum(1 for el in li if el[0]=='A' and el[1] in '01234')

gives

3 , not 6

Calculate days between two Dates in Java 8

You can use until():

LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);

System.out.println("Until christmas: " + independenceDay.until(christmas));
System.out.println("Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));

Node.js - EJS - including a partial

In oficial documentation https://github.com/mde/ejs#includes show that includes works like that:

<%- include('../partials/head') %>

Join two sql queries

Some DBMSs support the FROM (SELECT ...) AS alias_name syntax.

Think of your two original queries as temporary tables. You can query them like so:

SELECT t1.Activity, t1."Total Amount 2009", t2."Total Amount 2008"
FROM (query1) as t1, (query2) as t2
WHERE t1.Activity = t2.Activity

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

What worked for me is that i hadn't set the local_listener, to see if the local listener is set login to sqlplus / as sysdba, make sure the database is open and run the following command show parameter local_listener, if the value is empty, then you will have to set the local_listener with the following SQL command ALTER SYSTEM SET LOCAL_LISTENER='<LISTENER_NAME_GOES_HERE>'

How can I read the contents of an URL with Python?

None of these answers are very good for Python 3 (tested on latest version at the time of this post).

This is how you do it...

import urllib.request

try:
   with urllib.request.urlopen('http://www.python.org/') as f:
      print(f.read().decode('utf-8'))
except urllib.error.URLError as e:
   print(e.reason)

The above is for contents that return 'utf-8'. Remove .decode('utf-8') if you want python to "guess the appropriate encoding."

Documentation: https://docs.python.org/3/library/urllib.request.html#module-urllib.request

How do I install TensorFlow's tensorboard?

If your Tensorflow install is located here:

/usr/local/lib/python2.7/dist-packages/tensorflow

then the python command to launch Tensorboard is:

$ python /usr/local/lib/python2.7/dist-packages/tensorflow/tensorboard/tensorboard.py --logdir=/home/user/Documents/.../logdir

The installation from pip allows you to use:

$ tensorboard --logdir=/home/user/Documents/.../logdir

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

Go to the XML layout Text where the widget (button or other View) indicates error, focus the cursor there and press alt+enter and select missing constraints attributes.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

your $(this).val() has no scope in your ajax call, because its not in change event function scope

May be you implemented that ajax call in your change event itself first, in that case it works fine. but when u created a function and calling that funciton in change event, scope for $(this).val() is not valid.

simply get the value using id selector instead of

$(#CourseSelect).val()

whole code should be like this:

 $(document).ready(function () 
{
    $("#CourseSelect").change(loadTeachers);
    loadTeachers();
});

function loadTeachers()
{
    $.ajax({ type:'GET', url:'/Manage/getTeachers/' + $(#CourseSelect).val(), dataType:'json', cache:false,
        success:function(data)
        { 
            $('#TeacherSelect').get(0).options.length = 0;    

            $.each(data, function(i, teacher) 
            {
                var option = $('<option />');
                option.val(teacher.employeeId);
                option.text(teacher.name);
                $('#TeacherSelect').append(option);
            });
        }, error:function(){ alert("Error while getting results"); }
    });
}

Remove blank attributes from an Object in Javascript

you can do shorter with ! condition

var r = {a: null, b: undefined, c:1};
for(var k in r)
   if(!r[k]) delete r[k];

Remember in usage : as @semicolor announce in comments: This would also delete properties if the value is an empty string, false or zero

Removing App ID from Developer Connection

When I do what explains some answers:

Screen Shot 1

The result is:

Screen Shot 2

So, anybody can explain really really how to delete an old App ID?

My opinion is: Apple does not let you remove them. I suppose it is a way to maintain the traceability or the historical of the published.

And of course: application is no longer available in the App Store. It was available (in the past), yes.

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

You guys copied the wrong code.

Go into the "/build" folder and grab the jquery.datetimepicker.full.js or jquery.datetimepicker.full.min.js if you want the minified version. It should fix it! :)

Get timezone from users browser using moment(timezone).js

You can also get your wanted time using the following JS code:

new Date(`${post.data.created_at} GMT+0200`)

In this example, my received dates were in GMT+0200 timezone. Instead of it can be every single timezone. And the returned data will be the date in your timezone. Hope this will help anyone to save time

Multiple lines of text in UILabel

This code is returning size height according to text

+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
 {
    CGFloat result = font.pointSize+4;
    if (text) 
{
        CGSize size;

        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, 999)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height+1);
        result = MAX(size.height, result); //At least one row
    }
    return result;
}

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

The onunload event is not called in all browsers. Worse, you cannot check the return value of onbeforeunload event. That prevents us from actually preforming a logout function.

However, you can hack around this.

Call logout first thing in the onbeforeunload event. then prompt the user. If the user cancels their logout, automatically login them back in, by using the onfocus event. Kinda backwards, but I think it should work.

'use strict';

var reconnect = false;

window.onfocus = function () {
  if (reconnect) {
    reconnect = false;
    alert("Perform an auto-login here!");
  }
};

window.onbeforeunload = function () {
  //logout();
  var msg = "Are you sure you want to leave?";
  reconnect = true;
  return msg;
};

How to tell if a string contains a certain character in JavaScript?

Try this:

if ('Hello, World!'.indexOf('orl') !== -1)
    alert("The string 'Hello World' contains the substring 'orl'!");
else
    alert("The string 'Hello World' does not contain the substring 'orl'!");

Here is an example: http://jsfiddle.net/oliverni/cb8xw/

How to fix "unable to write 'random state' " in openssl

I did not find where the .rnd file is so I ran the cmd as administrator and it worked like a charm.

Soft keyboard open and close listener in an activity in Android

The below code is working for me,

mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (mainLayout != null) {
                int heightDiff = mainLayout.getRootView().getHeight() - mainLayout.getHeight();
                if (heightDiff > dpToPx(getActivity(), 200)) { 
                   //keyboard is open
                } else {
                   //keyboard is hide
                }
            }
        }
    });

Adding a y-axis label to secondary y-axis in matplotlib

There is a straightforward solution without messing with matplotlib: just pandas.

Tweaking the original example:

table = sql.read_frame(query,connection)

ax = table[0].plot(color=colors[0],ylim=(0,100))
ax2 = table[1].plot(secondary_y=True,color=colors[1], ax=ax)

ax.set_ylabel('Left axes label')
ax2.set_ylabel('Right axes label')

Basically, when the secondary_y=True option is given (eventhough ax=ax is passed too) pandas.plot returns a different axes which we use to set the labels.

I know this was answered long ago, but I think this approach worths it.

Compute elapsed time

Try this...

function Test()
{
    var s1 = new StopWatch();

    s1.Start();        

    // Do something.

    s1.Stop();

    alert( s1.ElapsedMilliseconds );
} 

// Create a stopwatch "class." 
StopWatch = function()
{
    this.StartMilliseconds = 0;
    this.ElapsedMilliseconds = 0;
}  

StopWatch.prototype.Start = function()
{
    this.StartMilliseconds = new Date().getTime();
}

StopWatch.prototype.Stop = function()
{
    this.ElapsedMilliseconds = new Date().getTime() - this.StartMilliseconds;
}

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

You might also consider removing the need for duplicated parameter names in your Sql by changing your Sql to

table.Variable2 LIKE '%' || :VarB || '%'

and then getting your client to provide '%' for any value of VarB instead of null. In some ways I think this is more natural.

You could also change the Sql to

table.Variable2 LIKE '%' || IfNull(:VarB, '%') || '%'

What do 'lazy' and 'greedy' mean in the context of regular expressions?

Greedy means it will consume your pattern until there are none of them left and it can look no further.

Lazy will stop as soon as it will encounter the first pattern you requested.

One common example that I often encounter is \s*-\s*? of a regex ([0-9]{2}\s*-\s*?[0-9]{7})

The first \s* is classified as greedy because of * and will look as many white spaces as possible after the digits are encountered and then look for a dash character "-". Where as the second \s*? is lazy because of the present of *? which means that it will look the first white space character and stop right there.

Cell color changing in Excel using C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

How can I reverse a NSArray in Objective-C?

As for me, have you considered how the array was populated in the first place? I was in the process of adding MANY objects to an array, and decided to insert each one at the beginning, pushing any existing objects up by one. Requires a mutable array, in this case.

NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithCapacity:1];
[myMutableArray insertObject:aNewObject atIndex:0];

Angularjs $http post file and form data

You can also upload using HTML5. You can use this AJAX uploader.

The JS code is basically:

  $scope.doPhotoUpload = function () {
    // ..
    var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
    myUploader.send();
    // ..
  }

Which reads from an HTML input element

<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">

Signed to unsigned conversion in C - is it always safe?

What implicit conversions are going on here,

i will be converted to an unsigned integer.

and is this code safe for all values of u and i?

Safe in the sense of being well-defined yes (see https://stackoverflow.com/a/50632/5083516 ).

The rules are written in typically hard to read standards-speak but essentially whatever representation was used in the signed integer the unsigned integer will contain a 2's complement representation of the number.

Addition, subtraction and multiplication will work correctly on these numbers resulting in another unsigned integer containing a twos complement number representing the "real result".

division and casting to larger unsigned integer types will have well-defined results but those results will not be 2's complement representations of the "real result".

(Safe, in the sense that even though result in this example will overflow to some huge positive number, I could cast it back to an int and get the real result.)

While conversions from signed to unsigned are defined by the standard the reverse is implementation-defined both gcc and msvc define the conversion such that you will get the "real result" when converting a 2's complement number stored in an unsigned integer back to a signed integer. I expect you will only find any other behaviour on obscure systems that don't use 2's complement for signed integers.

https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation https://msdn.microsoft.com/en-us/library/0eex498h.aspx

Which data structures and algorithms book should I buy?

If you want the algorithms to be implemented specifically in Java then there is Mitchell Waite's Series book "Data Structures & Algorithms in Java". It starts from basic data structures like linked lists, stacks and queues, and the basic algorithms for sorting and searching. Working your way through it you will eventually get to Tree data structures, Red-Black trees, 2-3 trees and Graphs.

All-in-all its not an extremely theoretical book, but if you just want an introduction in a language you are familiar with then its a good book. At the end of the day, if you want a deeper understanding of algorithms you're going to have to learn some of the more theoretical concepts, and read one of the classics, like Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms.

Right HTTP status code to wrong input

Codes starting with 4 (4xx) are meant for client errors. Maybe 400 (Bad Request) could be suitable to this case? Definition in http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html says:

"The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. "

Where is Developer Command Prompt for VS2013?

For some reason, it doesn't properly add an icon when running Windows 8+. Here's how I solved it:

Using Windows Explorer, navigate to:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2013

In that folder, you'll see a shortcut named Visual Studio Tools that maps to (assuming default installation):

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts

Double-click the shortcut (or go to the folder above).

From that folder, copy the shortcut named Developer Command Prompt for VS2013 (and any others you find useful) to the first directory (for the Start Menu). You'll likely be prompted for administrative access (do so).

Once you've done that, you'll now have an icon available for the 2013 command prompt.

Class has no initializers Swift

Not a specific answer to your question but I had got this error when I hadn't set an initial value for an enum while declaring it as a property. I assigned a initial value to the enum to resolve this error. Posting here as it might help someone.

What is a 'workspace' in Visual Studio Code?

I just installed Visual Studio Code v1.25.1. on a Windows 7 Professional SP1 machine. I wanted to understand workspaces in detail, so I spent a few hours figuring out how they work in this version of Visual Studio Code. I thought the results of my research might be of interest to the community.

First, workspaces are referred to by Microsoft in the Visual Studio Code documentation as "multi-root workspaces." In plain English that means "a multi-folder (A.K.A "root") work environment." A Visual Studio Code workspace is simply a collection of folders - any collection you desire, in any order you wish. The typical collection of folders constitutes a software development project. However, a folder collection could be used for anything else for which software code is being developed.

The mechanics behind how Visual Studio Code handles workspaces is a bit complicated. I think the quickest way to convey what I learned is by giving you a set of instructions that you can use to see how workspaces work on your computer. I am assuming that you are starting with a fresh install of Visual Studio Code v1.25.1. If you are using a production version of Visual Studio Code I don't recommend that you follow my instructions because you may lose some or all of your existing Visual Studio Code configuration! If you already have a test version of Visual Studio Code v1.25.1 installed, **and you are willing to lose any configuration that already exists, the following must be done to revert your Visual Studio Code to a fresh installation state:

Delete the following folder (if it exists):

  C:\Users\%username%\AppData\Roaming\Code\Workspaces (where "%username%" is the name of the currently logged-on user)

You will be adding folders to Visual Studio Code to create a new workspace. If any of the folders you intend to use to create this new workspace have previously been used with Visual Studio Code, please delete the ".vscode" subfolder (if it exists) within each of the folders that will be used to create the new workspace.

Launch Visual Studio Code. If the Welcome page is displayed, close it. Do the same for the Panel (a horizontal pane) if it is displayed. If you received a message that Git isn't installed click "Remind me later." If displayed, also close the "Untitled" code page that was launched as the default code page. If the Explorer pane is not displayed click "View" on the main menu then click "Explorer" to display the Explorer pane. Inside the Explorer pane you should see three (3) View headers - Open Editors, No Folder Opened, and Outline (located at the very bottom of the Explorer pane). Make sure that, at a minimum, the open editors and no folder opened view headers are displayed.

Visual Studio Code displays a button that reads "Open Folder." Click this button and select a folder of your choice. Visual Studio Code will refresh and the name of your selected folder will have replaced the "No Folder Opened" View name. Any folders and files that exist within your selected folder will be displayed beneath the View name.

Now open the Visual Studio Code Preferences Settings file. There are many ways to do this. I'll use the easiest to remember which is menu FilePreferencesSettings. The Settings file is displayed in two columns. The left column is a read-only listing of the default values for every Visual Studio Code feature. The right column is used to list the three (3) types of user settings. At this point in your test only two user settings will be listed - User Settings and Workspace Settings. The User Settings is displayed by default. This displays the contents of your User Settings .json file. To find out where this file is located, simply hover your mouse over the "User Settings" listing that appears under the OPEN EDITORS View in Explorer. This listing in the OPEN EDITORS View is automatically selected when the "User Settings" option in the right column is selected. The path should be:

C:\Users\%username%\AppData\Roaming\Code\User\settings.json

This settings.json file is where the User Settings for Visual Studio Code are stored.

Now click the Workspace Settings option in the right column of the Preferences listing. When you do this, a subfolder named ".vscode" is automatically created in the folder you added to Explore a few steps ago. Look at the listing of your folder in Explorer to confirm that the .vscode subfolder has been added. Inside the new .vscode subfolder is another settings.json file. This file contains the workspace settings for the folder you added to Explorer a few steps ago.

At this point you have a single folder whose User Settings are stored at:

C:\Users\%username%\AppData\Roaming\Code\User\settings.json

and whose Workspace Settings are stored at:

C:\TheLocationOfYourFolder\settings.json

This is the configuration when a single folder is added to a new installation of Visual Studio Code. Things get messy when we add a second (or greater) folder. That's because we are changing Visual Studio Code's User Settings and Workspace Settings to accommodate multiple folders. In a single-folder environment only two settings.json files are needed as listed above. But in a multi-folder environment a .vscode subfolder is created in each folder added to Explorer and a new file, "workspaces.json," is created to manage the multi-folder environment. The new "workspaces.json" file is created at:

c:\Users\%username%\AppData\Roaming\Code\Workspaces\%workspace_id%\workspaces.json

The "%workspaces_id%" is a folder with a unique all-number name.

In the Preferences right column there now appears three user setting options - User Settings, Workspace Settings, and Folder Settings. The function of User Settings remains the same as for a single-folder environment. However, the settings file behind the Workspace Settings has been changed from the settings.json file in the single folder's .vscode subfolder to the workspaces.json file located at the workspaces.json file path shown above. The settings.json file located in each folder's .vscode subfolder is now controlled by a third user setting, Folder Options. This is a drop-down selection list that allows for the management of each folder's settings.json file located in each folder's .vscode subfolder. Please note: the .vscode subfolder will not be created in newly-added explorer folders until the newly-added folder has been selected at least once in the folder options user setting.

Notice that the Explorer single folder name has bee changed to "UNTITLED (WORKSPACE)." This indicates the following:

  1. A multi-folder workspace has been created with the name "UNTITLED (WORKSPACE)
  2. The workspace is named "UNTITLED (WORKSPACE)" to communicate that the workspace has not yet been saved as a separate, unique, workspace file
  3. The UNTITLED (WORKSPACE) workspace can have folders added to it and removed from it but it will function as the ONLY workspace environment for Visual Studio Code

The full functionality of Visual Studio Code workspaces is only realized when a workspace is saved as a file that can be reloaded as needed. This provides the capability to create unique multi-folder workspaces (e.g., projects) and save them as files for later use! To do this select menu FileSave Workspace As from the main menu and save the current workspace configuration as a unique workspace file. If you need to create a workspace "from scratch," first save your current workspace configuration (if needed) then right-click each Explorer folder name and click "Remove Folder from Workspace." When all folders have been removed from the workspace, add the folders you require for your new workspace. When you finish adding new folders, simply save the new workspace as a new workspace file.

An important note - Visual Studio Code doesn't "revert" to single-folder mode when only one folder remains in Explorer or when all folders have been removed from Explorer when creating a new workspace "from scratch." The multi-folder workspace configuration that utilizes three user preferences remains in effect. This means that unless you follow the instructions at the beginning of this post, Visual Studio Code can never be returned to a single-folder mode of operation - it will always remain in multi-folder workspace mode.

error: package com.android.annotations does not exist

You shouldn't edit any code manually jetify should do this job for you, if you are running/building from cli using react-native you dont' need to do anything but if you are running/building Andriod studio you need to run jetify as pre-build, here is how can you automate this:

1- From the above menu go to edit configurations:

enter image description here

2- Add the bottom of the screen you will find before launch click on the plus and choose Run External Tool

enter image description here

2- Fill the following information, note that the working directory is your project root directory (not the android directory):

enter image description here

3- Make sure this run before anything else, in the end, your configuration should look something like this: enter image description here

Pyspark: Filter dataframe based on multiple conditions

You can also write like below (without pyspark.sql.functions):

df.filter('d<5 and (col1 <> col3 or (col1 = col3 and col2 <> col4))').show()

Result:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

How to execute cmd commands via Java

try {
    String command = "Command here";
    Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + command);
} catch (IOException e) {
    e.printStackTrace();
}

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

Bootstrap 3 Navbar Collapse

I think I found a simple solution to changing the collapse breakpoint, only through css.

I hope others can confirm it since I didn't test it thoroughly and I'm not sure if there are side effects to this solution.

You have to change the media query values for the following class definitions:

@media (min-width: BREAKPOINT px ){
    .navbar-toggle{display:none}
}

@media (min-width: BREAKPOINT px){
    .navbar-collapse{
        width:auto;
        border-top:0;box-shadow:none
    }
    .navbar-collapse.collapse{
        display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important
    }
    .navbar-collapse.in{
        overflow-y:visible
   }
   .navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{
        padding-left:0;padding-right:0
    }
}

This is what worked for me on my current project, but I still need to change some css definitions to arrange the menu properly for all screen sizes.

Hope this helps.

Sorting hashmap based on keys

Use a TreeMap with a custom comparator.

class MyComparator implements Comparator<String>
    {
        public int compare(String o1,String o2)
        {
            // Your logic for comparing the key strings
        }
    }

TreeMap<String, Float> tm = new TreeMap<String , Float>(new MyComparator());

As you add new elements, they will be automatically sorted.

In your case, it might not even be necessary to implement a comparator because String ordering might be sufficient. But if you want to implement special cases, like lower case alphas appear before upper case, or treat the numbers a certain way, use the comparator.

How to pass credentials to the Send-MailMessage command for sending emails

It took me a while to combine everything, make it a bit secure, and have it work with Gmail. I hope this answer saves someone some time.

Create a file with the encrypted server password:

In Powershell, enter the following command (replace myPassword with your actual password):

"myPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\EmailPassword.txt"

Create a powershell script (Ex. sendEmail.ps1):

$User = "[email protected]"
$File = "C:\EmailPassword.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)
$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Email Subject" 
$Body = "Email body text" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\fileIwantToSend.csv"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password); 
$SMTPClient.Send($SMTPMessage)

Automate with Task Scheduler:

Create a batch file (Ex. emailFile.bat) with the following:

powershell -ExecutionPolicy ByPass -File C:\sendEmail.ps1

Create a task to run the batch file. Note: you must have the task run with the same user account that you used to encrypted the password! (Aka, probably the logged in user)

That's all; you now have a way to automate and schedule sending an email and an attachment with Windows Task Scheduler and Powershell. No 3rd party software and the password is not stored as plain text (though granted, not terribly secure either).

You can also read this article on the level of security this provides for your email password.

A process crashed in windows .. Crash dump location

a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).

If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP

How can I get the active screen dimensions?

Beware of the scale factor of your windows (100% / 125% / 150% / 200%). You can get the real screen size by using the following code:

SystemParameters.FullPrimaryScreenHeight
SystemParameters.FullPrimaryScreenWidth

Tomcat 8 Maven Plugin for Java 8

An other solution (if possible) would be to use TomEE instead of Tomcat, which has a working maven plugin:

<plugin>
    <groupId>org.apache.tomee.maven</groupId>
    <artifactId>tomee-maven-plugin</artifactId>
    <version>7.1.1</version>
</plugin>

Version 7.1.1 wraps a Tomcat 8.5.41

Getting the exception value in Python

For python2, It's better to use e.message to get the exception message, this will avoid possible UnicodeDecodeError. But yes e.message will be empty for some kind of exceptions like OSError, in which case we can add a exc_info=True to our logging function to not miss the error.
For python3, I think it's safe to use str(e).

In the shell, what does " 2>&1 " mean?

File descriptor 1 is the standard output (stdout).
File descriptor 2 is the standard error (stderr).

Here is one way to remember this construct (although it is not entirely accurate): at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows and precedes is a file descriptor and not a filename. So the construct becomes: 2>&1.

Consider >& as redirect merger operator.

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

Because TRUNCATE TABLE is a DDL command, it cannot check to see whether the records in the table are being referenced by a record in the child table.

This is why DELETE works and TRUNCATE TABLE doesn't: because the database is able to make sure that it isn't being referenced by another record.

Could not find folder 'tools' inside SDK

If you install Eclipse properly then:

  1. Start Eclipse
  2. From the menu bar, select Window > Preferences > Android
  3. For Android location, browse the folder in which you install Android SDKs.
  4. In Android SDKs folder, rename the folder platforms-tools to tools.
  5. Select the folder Android SDKs through Preferences dialog box.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

I have been getting similar error, and just want to share with you. maybe it will help someone.

If you want to use EntityManagerFactory to get an EntityManager, make sure that you will use:

<persistence-unit name="name" transaction-type="RESOURCE_LOCAL">

and not:

<persistence-unit name="name" transaction-type="JPA">

in persistance.xml

clean and rebuild project, it should help.

Should you use .htm or .html file extension? What is the difference, and which file is correct?

If you plan on putting the files on a machine supporting only 8.3 naming convention, you should limit the extension to 3 characters.

Otherwise, better choose the more descriptive .html version.

Replace characters from a column of a data frame R

chartr is also convenient for these types of substitutions:

chartr("_", "-", data1$c)
#  [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"

Thus, you can just do:

data1$c <- chartr("_", "-", data1$c)

How can I tell Moq to return a Task?

Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync

Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods

Few examples found in previous responses done with SetupAsync extension:

mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());

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

Use max-width property of CSS, like this :

img{
  max-width:100%;
}

How to run Java program in terminal with external library JAR

You can do :

1) javac -cp /path/to/jar/file Myprogram.java

2) java -cp .:/path/to/jar/file Myprogram

So, lets suppose your current working directory in terminal is src/Report/

javac -cp src/external/myfile.jar Reporter.java

java -cp .:src/external/myfile.jar Reporter

Take a look here to setup Classpath

Android: How can I pass parameters to AsyncTask's onPreExecute()?

1) For me that's the most simple way passing parameters to async task is like this

// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);

Declare and use the async task like here

private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {

    @Override
    protected Void doInBackground(Boolean...pParams) 
    {
        Boolean param1, param2, param3;

        //

          param1=pParams[0];    
          param2=pParams[1];
          param3=pParams[2];    
      ....
}                           

2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.

 /* Generic Async Task    */
interface MyGenericMethod {
    int execute(String param);
}

protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
    public String mParam;                           // member variable to parameterize the function
    @Override
    protected Void doInBackground(MyGenericMethod... params) {
        //  do something here
        params[0].execute("Myparameter");
        return null;
    }       
}

// to start the asynctask do something like that
public void startAsyncTask()
{
    // 
    AsyncTask<MyGenericMethod, Void, Void>  mytest = new testtask().execute(new MyGenericMethod() {
        public int execute(String param) {
            //body
            return 1;
        }
    });     
}

are there dictionaries in javascript like python?

Use JavaScript objects. You can access their properties like keys in a dictionary. This is the foundation of JSON. The syntax is similar to Python dictionaries. See: JSON.org

connect to host localhost port 22: Connection refused

For what its worth I got the following error trying to ssh into my local machine, running Ubuntu 16.04 Xenial, from a vm.

 ssh: connect to host 192.168.144.18 port 22: Connection refused

It got immediately fixed with:

sudo apt-get install ssh

Take note, Before fix: 'which sshd' returned nothing and 'which ssh' returned

/usr/bin/ssh

And After the fix: 'which sshd' returned

/usr/sbin/sshd

How to set a value for a selectize.js input?

I had a similar problem. My data is provided by a remote server. I want some value to be entered in the selectize box, but it is not sure in advance whether this value is a valid one on the server.

So I want the value to be entered in the box, and I want selectize to show the possible options just if like the user had entered the value.

I ended up using this hack (which it is probably unsupported):

var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();

How can I sort one set of data to match another set of data in Excel?

You could also use INDEX MATCH, which is more "powerful" than vlookup. This would give you exactly what you are looking for:

enter image description here

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

Replace all occurrences of a String using StringBuilder?

How about create a method and let String.replaceAll do it for you:

public static void replaceAll(StringBuilder sb, String regex, String replacement)
{
    String aux = sb.toString();
    aux = aux.replaceAll(regex, replacement);
    sb.setLength(0);
    sb.append(aux);     
}

Django DB Settings 'Improperly Configured' Error

In your python shell/ipython do:

from django.conf import settings

settings.configure()

How to create an empty file at the command line in Windows?

Open file :

type file.txt

New file :

Way 1 : type nul > file.txt
Way 2 : echo This is a sample text file > sample.txt
Way 3 : notepad myfile.txt <press enter>

Edit content:

notepad file.txt

Copy

copy file1.txt file1Copy.txt

Rename

rename file1.txt file1_rename.txt

Delete file :

del file.txt

fs: how do I locate a parent folder?

Use path.join http://nodejs.org/docs/v0.4.10/api/path.html#path.join

var path = require("path"),
    fs = require("fs");

fs.readFile(path.join(__dirname, '..', '..', 'foo.bar'));

path.join() will handle leading/trailing slashes for you and just do the right thing and you don't have to try to remember when trailing slashes exist and when they dont.

Adding an assets folder in Android Studio

To specify any additional asset folder I've used this with my Gradle. This adds moreAssets, a folder in the project root, to the assets.

android {
    sourceSets {
        main.assets.srcDirs += '../moreAssets'
    }
}

How to create a file in memory for user to download, but not through server?

The package js-file-download from github.com/kennethjiang/js-file-download handles edge cases for browser support:

View source to see how it uses techniques mentioned on this page.

Installation

yarn add js-file-download
npm install --save js-file-download

Usage

import fileDownload from 'js-file-download'

// fileDownload(data, filename, mime)
// mime is optional

fileDownload(data, 'filename.csv', 'text/csv')

Running a cron every 30 seconds

Run in a shell loop, example:

#!/bin/sh    
counter=1
while true ; do
 echo $counter
 counter=$((counter+1))
 if [[ "$counter" -eq 60 ]]; then
  counter=0
 fi
 wget -q http://localhost/tool/heartbeat/ -O - > /dev/null 2>&1 &
 sleep 1
done

Java, How do I get current index/key in "for each" loop

###################################################
###################################################
###################################################
AVOID THIS
###################################################
###################################################
###################################################

/*for (Song s: songList){
    System.out.println(s + "," + songList.indexOf(s); 
}*/

it is possible in linked list.

you have to make toString() in song class. if you don't it will print out reference of the song.

probably irrelevant for you by now. ^_^

How do you get the logical xor of two variables in Python?

Bitwise exclusive-or is already built-in to Python, in the operator module (which is identical to the ^ operator):

from operator import xor
xor(bool(a), bool(b))  # Note: converting to bools is essential

How to add icon to mat-icon-button

the above CSS can be written in SASS as follows (and it actually includes all button types, instead of just button.mat-button)

button,
a {
    &.mat-button,
    &.mat-raised-button,
    &.mat-flat-button,
    &.mat-stroked-button {
        .mat-icon {
            vertical-align: top;
            font-size: 1.25em;
        }
    }
}

Convert Long into Integer

Assuming not null longVal

Integer intVal = ((Number)longVal).intValue();

It works for example y you get an Object that can be an Integer or a Long. I know that is ugly, but it happens...

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

Groovy Shell warning "Could not open/create prefs root node ..."

I was getting the following message:

Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002

and it was gone after creating one of these registry keys, mine is 64 bit so I tried only that.

32 bit Windows
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

64 bit Windows
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

"for" vs "each" in Ruby

Your first example,

@collection.each do |item|
  # do whatever
end

is more idiomatic. While Ruby supports looping constructs like for and while, the block syntax is generally preferred.

Another subtle difference is that any variable you declare within a for loop will be available outside the loop, whereas those within an iterator block are effectively private.

Escape double quotes in parameter

I'm calling powershell from cmd, and passing quotes and neither escapes here worked. The grave accent worked to escape double quotes on this Win 10 surface pro.

>powershell.exe "echo la`"" >> test
>type test
la"

Below are outputs I got for other characters to escape a double quote:

la\
la^
la
la~

Using another quote to escape a quote resulted in no quotes. As you can see, the characters themselves got typed, but didn't escape the double quotes.

Open Sublime Text from Terminal in macOS

I am using mac airbook open your terminal and type

 sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/bin/subl

Then type simple subl and file name

 subl index.py

How do change the color of the text of an <option> within a <select>?

You can't have HTML code inside the options, they can only contain text, but you can apply the class to the option instead:

<option selected="selected" class="grey_color">select one option</option>

Demo: http://jsfiddle.net/Guffa/hUpAB/9/

Note:

  • The support for styling options varies between browsers. In modern brosers you generally can expect support for coloring but not for font size. A browser in a phone for example usually doesn't display the options in a dropdown, so the styling would not be relevant at all.
  • You should not have html and head tags in the HTML code in jsfiddle.
  • You should name your classes for what the represent, not how they look.

How to sort two lists (which reference each other) in the exact same way

I have used the answer given by senderle for a long time until I discovered np.argsort. Here is how it works.

# idx works on np.array and not lists.
list1 = np.array([3,2,4,1])
list2 = np.array(["three","two","four","one"])
idx   = np.argsort(list1)

list1 = np.array(list1)[idx]
list2 = np.array(list2)[idx]

I find this solution more intuitive, and it works really well. The perfomance:

def sorting(l1, l2):
    # l1 and l2 has to be numpy arrays
    idx = np.argsort(l1)
    return l1[idx], l2[idx]

# list1 and list2 are np.arrays here...
%timeit sorting(list1, list2)
100000 loops, best of 3: 3.53 us per loop

# This works best when the lists are NOT np.array
%timeit zip(*sorted(zip(list1, list2)))
100000 loops, best of 3: 2.41 us per loop

# 0.01us better for np.array (I think this is negligible)
%timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100000 loops, best for 3 loops: 1.96 us per loop

Even though np.argsort isn't the fastest one, I find it easier to use.

Making an iframe responsive

DA is right. In your own fiddle, the iframe is indeed responsive. You can verify that in firebug by checking iframe box-sizing. But some elements inside that iframe is not responsive, so they "stick out" when window size is small. For example, div#products-post-wrapper's width is 8800px.

What are the special dollar sign shell variables?

Take care with some of the examples; $0 may include some leading path as well as the name of the program. Eg save this two line script as ./mytry.sh and the execute it.

#!/bin/bash

echo "parameter 0 --> $0" ; exit 0

Output:

parameter 0 --> ./mytry.sh

This is on a current (year 2016) version of Bash, via Slackware 14.2

How to change value of object which is inside an array using JavaScript or jQuery?

Let you want to update value of array[2] = "data"

    for(i=0;i<array.length;i++){
      if(i == 2){
         array[i] = "data";
        }
    }

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

1) When to use include directive ?

To prevent duplication of same output logic across multiple jsp's of the web app ,include mechanism is used ie.,to promote the re-usability of presentation logic include directive is used

  <%@ include file="abc.jsp" %>

when the above instruction is received by the jsp engine,it retrieves the source code of the abc.jsp and copy's the same inline in the current jsp. After copying translation is performed for the current page

Simply saying it is static instruction to jsp engine ie., whole source code of "abc.jsp" is copied into the current page

2) When to use include action ?

include tag doesn't include the source code of the included page into the current page instead the output generated at run time by the included page is included into the current page response

include tag functionality is similar to that of include mechanism of request dispatcher of servlet programming

include tag is run-time instruction to jsp engine ie., rather copying whole code into current page a method call is made to "abc.jsp" from current page

Android Fragment no view found for ID?

I had this same issue, let me post my code so that you can all see it, and not do the same thing that I did.

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

    fragManager = getSupportFragmentManager();

    Fragment answerPad=getDefaultAnswerPad();
    setAnswerPad(answerPad);
    setContentView(R.layout.abstract_test_view);
}
protected void setAnswerPad(AbstractAnswerFragment pad)
{
    fragManager.beginTransaction()
        .add(R.id.AnswerArea, pad, "AnswerArea")
        .commit();
    fragManager.executePendingTransactions();
}

Note that I was setting up fragments before I setContentView. Ooops.

How can I tell which button was clicked in a PHP form submit?

All you need to give the name attribute to the each button. And you need to address each button press from the PHP script. But be careful to give each button a unique name. Because the PHP script only take care of the name most of the time

<input type="submit" name="Submit_this" id="This" />

AngularJS - Trigger when radio button is selected

i prefer to use ng-value with ng-if, [ng-value] will handle trigger changes

<input type="radio"  name="isStudent" ng-model="isStudent" ng-value="true" />

//to show and hide input by removing it from the DOM, that's make me secure from malicious data

<input type="text" ng-if="isStudent"  name="textForStudent" ng-model="job">

SQL Server SELECT into existing table

select *
into existing table database..existingtable
from database..othertables....

If you have used select * into tablename from other tablenames already, next time, to append, you say select * into existing table tablename from other tablenames

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Use the following:

driver.findElement(By.id("id")).sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.DELETE), "Your Value");

Checking if a website is up via Python

In my opinion, caisah's answer misses an important part of your question, namely dealing with the server being offline.

Still, using requests is my favorite option, albeit as such:

import requests

try:
    requests.get(url)
except requests.exceptions.ConnectionError:
    print(f"URL {url} not reachable")

How to get CPU temperature?

There is a blog post with some C# sample code on how to do it here.

Have Excel formulas that return 0, make the result blank

The normal way would be the IF statement, though simpler than your example:

=IF(INDEX(a,b,c),INDEX(a,b,c),"")

No need to do gyrations with the formula, since zero values trigger the false condition.

How to iterate over the keys and values with ng-repeat in AngularJS?

    Use below code it is working to display your key and value here is key start with 1:
         <tr ng-repeat="(key,value) in alert_list" >
                   <td>{{key +1}}</td>
                   <td>{{value.title}}</td>
                 </tr>
Below is document link for it. 

https://docs.angularjs.org/api/ng/directive/ngRepeat

Getting the text from a drop-down box

This should return the text value of the selected value

var vSkill = document.getElementById('newSkill');

var vSkillText = vSkill.options[vSkill.selectedIndex].innerHTML;

alert(vSkillText);

Props: @Tanerax for reading the question, knowing what was asked and answering it before others figured it out.

Edit: DownModed, cause I actually read a question fully, and answered it, sad world it is.

how to use #ifdef with an OR condition?

OR condition in #ifdef

#if defined LINUX || defined ANDROID
// your code here
#endif /* LINUX || ANDROID */

or-

#if defined(LINUX) || defined(ANDROID)
// your code here
#endif /* LINUX || ANDROID */

Both above are the same, which one you use simply depends on your taste.


P.S.: #ifdef is simply the short form of #if defined, however, does not support complex condition.


Further-

  • AND: #if defined LINUX && defined ANDROID
  • XOR: #if defined LINUX ^ defined ANDROID

How can I bind to the change event of a textarea in jQuery?

Use an input event.

var button = $("#buttonId");
$("#textareaID").on('input',function(e){
  if(e.target.value === ''){
    // Textarea has no value
    button.hide();
  } else {
    // Textarea has a value
    button.show();
  }
});

What does ':' (colon) do in JavaScript?

It is part of the object literal syntax. The basic format is:

var obj = { field_name: "field value", other_field: 42 };

Then you can access these values with:

obj.field_name; // -> "field value"
obj["field_name"]; // -> "field value"

You can even have functions as values, basically giving you the methods of the object:

obj['func'] = function(a) { return 5 + a;};
obj.func(4);  // -> 9

Java 8 LocalDate Jackson format

Just an update of Christopher answer.

Since the version 2.6.0

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.9.0</version>
</dependency>

Use the JavaTimeModule instead of JSR310Module (deprecated).

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {  
    private final ObjectMapper MAPPER;

    public ObjectMapperContextResolver() {
        MAPPER = new ObjectMapper();
        MAPPER.registerModule(new JavaTimeModule());
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return MAPPER;
    }  
}

According to the documentation, the new JavaTimeModule uses same standard settings to default to serialization that does NOT use Timezone Ids, and instead only uses ISO-8601 compliant Timezone offsets.

Behavior may be changed using SerializationFeature.WRITE_DATES_WITH_ZONE_ID

Better way to right align text in HTML Table

What you really want here is:

<col align="right"/>

but it looks like Gecko doesn't support this yet: it's been an open bug for over a decade.

(Geez, why can't Firefox have decent standards support like IE6?)

Bootstrap modal - close modal when "call to action" button is clicked

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

Just in case someone is using Bootstrap, I was able to add more than one class:

<a href="" class="baseclass" th:classappend="${isAdmin} ?: 'text-danger font-italic' "></a>

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

It is a new signing mechanism introduced in Android 7.0, with additional features designed to make the APK signature more secure.

It is not mandatory. You should check BOTH of those checkboxes if possible, but if the new V2 signing mechanism gives you problems, you can omit it.

So you can just leave V2 unchecked if you encounter problems, but should have it checked if possible.

UPDATED: This is now mandatory when targeting Android 11.

Messages Using Command prompt in Windows 7

Open Notepad and write this

@echo off
:A
Cls
echo MESSENGER
set /p n=User:
set /p m=Message:
net send %n% %m%
Pause
Goto A

and then save as "Messenger.bat" and close the Notepad
Step 1:

when you open that saved notepad file it will open as a file Messenger command prompt with this details.

Messenger
User:

after "User" write the ip of the computer you want to contact and then press enter.

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

How can you get the active users connected to a postgreSQL database via SQL?

(question) Don't you get that info in

select * from pg_user;

or using the view pg_stat_activity:

select * from pg_stat_activity;

Added:

the view says:

One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.

can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...

something like that.

Java, return if trimmed String in List contains String

Try this:

for(String str: myList) {
    if(str.trim().equals("A"))
       return true;
}
return false;

You need to use str.equals or str.equalsIgnoreCase instead of contains because contains in string works not the same as contains in List

List<String> s = Arrays.asList("BAB", "SAB", "DAS");
s.contains("A"); // false
"BAB".contains("A"); // true

PHP Get URL with Parameter

Finally found this method:

basename($_SERVER['REQUEST_URI']);

This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10).

target="_blank" vs. target="_new"

target="_blank" opens a new tab in most browsers.

Create auto-numbering on images/figures in MS Word

Office 2007

Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.