Programs & Examples On #Log4r

Log4r is a logging library for Ruby akin to Log4j for those coming from Java.

Read text from response

This article gives a good overview of using the HttpWebResponse object:How to use HttpWebResponse

Relevant bits below:

HttpWebResponse webresponse;

webresponse = (HttpWebResponse)webrequest.GetResponse();

Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(),enc);

string Response = loResponseStream.ReadToEnd();

loResponseStream.Close();
webresponse.Close();

return Response;

How can I develop for iPhone using a Windows development machine?

I use Flutter. I develop on my Windows machine and test on an Android emulator. When I'm ready to test on iOS, I run the code on macOS. From my experience, a Flutter app runs exactly the same on Android and iOS. If you don't have a Mac, you can download VirtualBox and install macOS on it. On VirtualBox, macOS runs exactly as it does on a real Mac, and you can build your app on it.

Error when testing on iOS simulator: Couldn't register with the bootstrap server

In most worst condition Reset content and setting of iOS Simulater, and most of the time in my case, quitting XCode along with simulator, always work works for me with XCode4.6 (that frequently get hanged)

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

Here is some SQL that actually make sense:

SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL

Simple is always better.

AngularJS ng-class if-else expression

you could try by using a function like that :

<div ng-class='whatClassIsIt(call.State)'>

Then put your logic in the function itself :

    $scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
     else
         return "ClassC";
    }

I made a fiddle with an example : http://jsfiddle.net/DotDotDot/nMk6M/

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

document.getElementsByClassName returns a NodeList, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()

or if you want plain JS try :

function toggle_by_class(cls, on) {
    var lst = document.getElementsByClassName(cls);
    for(var i = 0; i < lst.length; ++i) {
        lst[i].style.display = on ? '' : 'none';
    }
}

python, sort descending dataframe with pandas

New syntax (either):

 test = df.sort_values(['one'], ascending=[False])
 test = df.sort_values(['one'], ascending=[0])

How to get PID of process I've just started within java program?

There is an open-source library that has such a function, and it has cross-platform implementations: https://github.com/OpenHFT/Java-Thread-Affinity

It may be overkill just to get the PID, but if you want other things like CPU and thread id, and specifically thread affinity, it may be adequate for you.

To get the current thread's PID, just call Affinity.getAffinityImpl().getProcessId().

This is implemented using JNA (see arcsin's answer).

Display Image On Text Link Hover CSS Only

add

.hover_img a:hover span {
    display: block;
    width: 350px;
}

to show hover image full size in table change 350 to your size.

Get a filtered list of files in a directory

You can use pathlib that is available in Python standard library 3.4 and above.

from pathlib import Path

files = [f for f in Path.cwd().iterdir() if f.match("145592*.jpg")]

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

I think thats correct. RTSP may use RTP internally.

iPhone X / 8 / 8 Plus CSS media queries

I noticed that the answers here are using: device-width, device-height, min-device-width, min-device-height, max-device-width, max-device-height.

Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width, max-width and so on. For extra assurance, you can set the min and max to the same px amount. For example:

iPhone X

@media only screen 
    and (width : 375px) 
    and (height : 635px)
    and (orientation : portrait)  
    and (-webkit-device-pixel-ratio : 3) { }

You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight. Here are a few useful links on this subject:

bash: npm: command not found?

You need to install Node . Visiti this link

[1]: https://nodejs.org/en/ and follow the instructions.

Android REST client, Sample?

There is another library with much cleaner API and type-safe data. https://github.com/kodart/Httpzoid

Here is a simple usage example

Http http = HttpFactory.create(context);
http.post("http://example.com/users")
    .data(new User("John"))
    .execute();

Or more complex with callbacks

Http http = HttpFactory.create(context);
http.post("http://example.com/users")
    .data(new User("John"))
    .handler(new ResponseHandler<Void>() {
        @Override
        public void success(Void ignore, HttpResponse response) {
        }

        @Override
        public void error(String message, HttpResponse response) {
        }

        @Override
        public void failure(NetworkError error) {
        }

        @Override
        public void complete() {
        }
    }).execute();

It is fresh new, but looks very promising.

jQuery Force set src attribute for iframe

You cannot set FIX iframe's src or prevent javascript/form submit to change its location. However you can put script to onload of the page and change action of each dynamic link.

List<object>.RemoveAll - How to create an appropriate Predicate

Little bit off topic but say i want to remove all 2s from a list. Here's a very elegant way to do that.

void RemoveAll<T>(T item,List<T> list)
{
    while(list.Contains(item)) list.Remove(item);
}

With predicate:

void RemoveAll<T>(Func<T,bool> predicate,List<T> list)
{
    while(list.Any(predicate)) list.Remove(list.First(predicate));
}

+1 only to encourage you to leave your answer here for learning purposes. You're also right about it being off-topic, but I won't ding you for that because of there is significant value in leaving your examples here, again, strictly for learning purposes. I'm posting this response as an edit because posting it as a series of comments would be unruly.

Though your examples are short & compact, neither is elegant in terms of efficiency; the first is bad at O(n2), the second, absolutely abysmal at O(n3). Algorithmic efficiency of O(n2) is bad and should be avoided whenever possible, especially in general-purpose code; efficiency of O(n3) is horrible and should be avoided in all cases except when you know n will always be very small. Some might fling out their "premature optimization is the root of all evil" battle axes, but they do so naïvely because they do not truly understand the consequences of quadratic growth since they've never coded algorithms that have to process large datasets. As a result, their small-dataset-handling algorithms just run generally slower than they could, and they have no idea that they could run faster. The difference between an efficient algorithm and an inefficient algorithm is often subtle, but the performance difference can be dramatic. The key to understanding the performance of your algorithm is to understand the performance characteristics of the primitives you choose to use.

In your first example, list.Contains() and Remove() are both O(n), so a while() loop with one in the predicate & the other in the body is O(n2); well, technically O(m*n), but it approaches O(n2) as the number of elements being removed (m) approaches the length of the list (n).

Your second example is even worse: O(n3), because for every time you call Remove(), you also call First(predicate), which is also O(n). Think about it: Any(predicate) loops over the list looking for any element for which predicate() returns true. Once it finds the first such element, it returns true. In the body of the while() loop, you then call list.First(predicate) which loops over the list a second time looking for the same element that had already been found by list.Any(predicate). Once First() has found it, it returns that element which is passed to list.Remove(), which loops over the list a third time to yet once again find that same element that was previously found by Any() and First(), in order to finally remove it. Once removed, the whole process starts over at the beginning with a slightly shorter list, doing all the looping over and over and over again starting at the beginning every time until finally no more elements matching the predicate remain. So the performance of your second example is O(m*m*n), or O(n3) as m approaches n.

Your best bet for removing all items from a list that match some predicate is to use the generic list's own List<T>.RemoveAll(predicate) method, which is O(n) as long as your predicate is O(1). A for() loop technique that passes over the list only once, calling list.RemoveAt() for each element to be removed, may seem to be O(n) since it appears to pass over the loop only once. Such a solution is more efficient than your first example, but only by a constant factor, which in terms of algorithmic efficiency is negligible. Even a for() loop implementation is O(m*n) since each call to Remove() is O(n). Since the for() loop itself is O(n), and it calls Remove() m times, the for() loop's growth is O(n2) as m approaches n.

Programmatically get own phone number in iOS

At the risk of getting negative marks, I want to suggest that the highest ranking solution (currently the first response) violates the latest SDK Agreement as of Nov 5, 2009. Our application was just rejected for using it. Here's the response from Apple:

"For security reasons, iPhone OS restricts an application (including its preferences and data) to a unique location in the file system. This restriction is part of the security feature known as the application's "sandbox." The sandbox is a set of fine-grained controls limiting an application's access to files, preferences, network resources, hardware, and so on."

The device's phone number is not available within your application's container. You will need to revise your application to read only within your directory container and resubmit your binary to iTunes Connect in order for your application to be reconsidered for the App Store.

This was a real disappointment since we wanted to spare the user having to enter their own phone number.

What is a monad?

http://code.google.com/p/monad-tutorial/ is a work in progress to address exactly this question.

How can I use nohup to run process as a background process in linux?

In general, I use nohup CMD & to run a nohup background process. However, when the command is in a form that nohup won't accept then I run it through bash -c "...".

For example:

nohup bash -c "(time ./script arg1 arg2 > script.out) &> time_n_err.out" &

stdout from the script gets written to script.out, while stderr and the output of time goes into time_n_err.out.

So, in your case:

nohup bash -c "(time bash executeScript 1 input fileOutput > scrOutput) &> timeUse.txt" &

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

Remove border from buttons

$(".myButtonClass").css(["border:none; background-color:white; padding:0"]);

What does the M stand for in C# Decimal literal notation?

From C# specifications:

var f = 0f; // float
var d = 0d; // double
var m = 0m; // decimal (money)
var u = 0u; // unsigned int
var l = 0l; // long
var ul = 0ul; // unsigned long

Note that you can use an uppercase or lowercase notation.

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

It may be because of you assigned more than 50 % RAM memory to your emulator.

Open Oracle VM --> Settings --> General And then Decrease memory assigned to the device.

And in Newer Versions, Open Oracle VM --> Settings --> System --> MotherBoard Tab And then Decrease memory assigned to the device

How can I position my jQuery dialog to center?

I have to call function dialog() twice to position the dialog (jQuery v1.11.2 / jQueryUI v1.10.4).

$("#myDialog").dialog({
    /* initial dialog parameters */
}).dialog({
    position: {
        my: "center center",
        at: "center center",
        of: window
    }
});

How to programmatically add controls to a form in VB.NET

Yes.

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim MyTextbox as New Textbox
    With MyTextbox
       .Size = New Size(100,20)
       .Location = New Point(20,20)
    End With
    AddHandler MyTextbox.TextChanged, AddressOf MyTextbox_Changed
    Me.Controls.Add(MyTextbox)

'Without a help environment for an intelli sense substitution
'the address name and the methods name
'cannot be wrote in exchange for each other.
'Until an equality operation is prior for an exchange i have to work
'on an as is base substituted.

End Sub

Friend Sub MyTextbox_Changed(sender as Object, e as EventArgs)
   'Write code here.
End Sub

Why can't I use switch statement on a String?

If you are not using JDK7 or higher, you can use hashCode() to simulate it. Because String.hashCode() usually returns different values for different strings and always returns equal values for equal strings, it is fairly reliable (Different strings can produce the same hash code as @Lii mentioned in a comment, such as "FB" and "Ea") See documentation.

So, the code would look like this:

String s = "<Your String>";

switch(s.hashCode()) {
case "Hello".hashCode(): break;
case "Goodbye".hashCode(): break;
}

That way, you are technically switching on an int.

Alternatively, you could use the following code:

public final class Switch<T> {
    private final HashMap<T, Runnable> cases = new HashMap<T, Runnable>(0);

    public void addCase(T object, Runnable action) {
        this.cases.put(object, action);
    }

    public void SWITCH(T object) {
        for (T t : this.cases.keySet()) {
            if (object.equals(t)) { // This means that the class works with any object!
                this.cases.get(t).run();
                break;
            }
        }
    }
}

Android Studio - How to Change Android SDK Path

For projects default:

  1. Close current Project (File->Close project)

You'll get a Welcome to Android Studio Dialog. In that:

  1. Click on Configure -> Project Defaults -> Project Structure

  2. Click on SDK Location in the left column

  3. Put the path to the Android SDK in "Android SDK location" field.

(Example SDK location: C:\android-sdk; I have sub-folders like add-ons, platforms etc under C:\android-sdk)

  1. Click OK to save changes

  2. Have fun!

Following steps were for older versions(<1.0) of Android Studio

  1. In the middle column Click on Android SDK (with Android icon) OR click + on the top if you don't see an entry with Android icon.

  2. Change SDK Home Path and select valid Target.

How do you change the formatting options in Visual Studio Code?

If we are talking Visual Studio Code nowadays you set a default formatter in your settings.json:

  // Defines a default formatter which takes precedence over all other formatter settings. 
  // Must be the identifier of an extension contributing a formatter.
  "editor.defaultFormatter": null,

Point to the identifier of any installed extension, i.e.

"editor.defaultFormatter": "esbenp.prettier-vscode"

You can also do so format-specific:

"[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[sass]": {
    "editor.defaultFormatter": "michelemelluso.code-beautifier"
},

Also see here.


You could also assign other keys for different formatters in your keyboard shortcuts (keybindings.json). By default, it reads:

{
  "key": "shift+alt+f",
  "command": "editor.action.formatDocument",
  "when": "editorHasDocumentFormattingProvider && editorHasDocumentFormattingProvider && editorTextFocus && !editorReadonly"
}

Lastly, if you decide to use the Prettier plugin and prettier.rc, and you want for example different indentation for html, scss, json...

{
    "semi": true,
    "singleQuote": false,
    "trailingComma": "none",
    "useTabs": false,

    "overrides": [
        {
            "files": "*.component.html",
            "options": {
                "parser": "angular",
                "tabWidth": 4
            }
        },
        {
            "files": "*.scss",
            "options": {
                "parser": "scss",
                "tabWidth": 2
            }
        },
        {
            "files": ["*.json", ".prettierrc"],
            "options": {
                "parser": "json",
                "tabWidth": 4
            }
        }
    ]
}

How do I check if a string is a number (float)?

str.isnumeric()

Return True if all characters in the string are numeric characters, and there is at least one character, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

str.isdecimal()

Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

Both available for string types from Python 3.0.

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

I've come to this same question over & over again, also due to same reason. So let me answer this by saying what wrong I was doing. Might be helpful for someone.

I was creating component via angular-cli by command

ng g c components/something/something

What it did, was created the component as I wanted.

Also, While creating the component, it added the component in the App Module's declarations array.

If this is the case, please remove it. And Voila! It might work.

String isNullOrEmpty in Java?

public static boolean isNull(String str) {
        return str == null ? true : false;
    }

    public static boolean isNullOrBlank(String param) {
        if (isNull(param) || param.trim().length() == 0) {
            return true;
        }
        return false;
    }

Efficiently counting the number of lines of a text file. (200mb+)

Using a loop of fgets() calls is fine solution and the most straightforward to write, however:

  1. even though internally the file is read using a buffer of 8192 bytes, your code still has to call that function for each line.

  2. it's technically possible that a single line may be bigger than the available memory if you're reading a binary file.

This code reads a file in chunks of 8kB each and then counts the number of newlines within that chunk.

function getLines($file)
{
    $f = fopen($file, 'rb');
    $lines = 0;

    while (!feof($f)) {
        $lines += substr_count(fread($f, 8192), "\n");
    }

    fclose($f);

    return $lines;
}

If the average length of each line is at most 4kB, you will already start saving on function calls, and those can add up when you process big files.

Benchmark

I ran a test with a 1GB file; here are the results:

             +-------------+------------------+---------+
             | This answer | Dominic's answer | wc -l   |
+------------+-------------+------------------+---------+
| Lines      | 3550388     | 3550389          | 3550388 |
+------------+-------------+------------------+---------+
| Runtime    | 1.055       | 4.297            | 0.587   |
+------------+-------------+------------------+---------+

Time is measured in seconds real time, see here what real means

Using C# regular expressions to remove HTML tags

Add .+? in <[^>]*> and try this regex (base on this):

<[^>].+?>

c# .net regex demo enter image description here

Read all worksheets in an Excel workbook into an R list with data.frames

Note that most of XLConnect's functions are already vectorized. This means that you can read in all worksheets with one function call without having to do explicit vectorization:

require(XLConnect)
wb <- loadWorkbook(system.file("demoFiles/mtcars.xlsx", package = "XLConnect"))
lst = readWorksheet(wb, sheet = getSheets(wb))

With XLConnect 0.2-0 lst will already be a named list.

How to change package name in android studio?

First click once on your package and then click setting icon on Android Studio.

Close/Unselect Compact Empty Middle Packages

Then, right click your package and rename it.

Thats all.

enter image description here

Postgres and Indexes on Foreign Keys and Primary Keys

I love how this is explained in the article Cool performance features of EclipseLink 2.5

Indexing Foreign Keys

The first feature is auto indexing of foreign keys. Most people incorrectly assume that databases index foreign keys by default. Well, they don't. Primary keys are auto indexed, but foreign keys are not. This means any query based on the foreign key will be doing full table scans. This is any OneToMany, ManyToMany or ElementCollection relationship, as well as many OneToOne relationships, and most queries on any relationship involving joins or object comparisons. This can be a major perform issue, and you should always index your foreign keys fields.

ASP.NET MVC 3 - redirect to another action

Your method needs to return a ActionResult type:

public ActionResult Index()
{
    //All we want to do is redirect to the class selection page
    return RedirectToAction("SelectClasses", "Registration");
}

How can I add shadow to the widget in flutter?

Maybe it is sufficient if you wrap a Card around the Widget and play a bit with the elevation prop.

I use this trick to make my ListTile look nicer in Lists.

For your code it could look like this:

return Card(
   elevation: 3, // PLAY WITH THIS VALUE 
   child: Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
         // ... MORE OF YOUR CODE 
      ],
   ),
);

WCF Exception: Could not find a base address that matches scheme http for the endpoint

My issue was also caused by missing https binding in IIS: Selected default website > On the far right pane selected Bindings > add > https

Choose 'IIS Express Development Certificate' and set port to 443

Least common multiple for 3 or more numbers

ES6 style

function gcd(...numbers) {
  return numbers.reduce((a, b) => b === 0 ? a : gcd(b, a % b));
}

function lcm(...numbers) {
  return numbers.reduce((a, b) => Math.abs(a * b) / gcd(a, b));
}

Current time formatting with Javascript

function formatTime(date){

  d = new Date(date);
  var h=d.getHours(),m=d.getMinutes(),l="AM";
  if(h > 12){
    h = h - 12;
  }
  if(h < 10){
    h = '0'+h;
  }
  if(m < 10){
    m = '0'+m;
  }
  if(d.getHours() >= 12){
    l="PM"
  }else{
    l="AM"
  }

  return h+':'+m+' '+l;

}

Usage & result:

var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"

Image overlay on responsive sized images bootstrap

When you specify position:absolute it positions itself to the next-highest element with position:relative. In this case, that's the .project div.

If you give the image's immediate parent div a style of position:relative, the overlay will key to that instead of the div which includes the text. For example: http://jsfiddle.net/7gYUU/1/

 <div class="parent">
    <img src="http://placehold.it/500x500" class="img-responsive"/>
    <div class="fa fa-plus project-overlay"></div>
 </div>

.parent {
   position: relative;
}

Android Recyclerview GridLayoutManager column spacing

thanks edwardaa's answer https://stackoverflow.com/a/30701422/2227031

Another point to note is that:

if total spacing and total itemWidth are not equal to the screen width, you also need to adjust itemWidth, for example, on adapter onBindViewHolder method

Utils.init(_mActivity);
int width = 0;
if (includeEdge) {
    width = ScreenUtils.getScreenWidth() - spacing * (spanCount + 1);
} else {
    width = ScreenUtils.getScreenWidth() - spacing * (spanCount - 1);
}
int itemWidth = width / spanCount;

ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) holder.imageViewAvatar.getLayoutParams();
// suppose the width and height are the same
layoutParams.width = itemWidth;
layoutParams.height = itemWidth;
holder.imageViewAvatar.setLayoutParams(layoutParams);

Sorting Values of Set

Strings are sorted lexicographically. The behavior you're seeing is correct.

Define your own comparator to sort the strings however you prefer.

It would also work the way you're expecting (5 as the first element) if you changed your collections to Integer instead of using String.

adb connection over tcp not working now

Thanks to sud007 for this answer. In my case, I only need this part of the solution:

In CMD/Terminal:

$ adb kill-server

$ adb tcpip 5555
restarting in TCP mode port: 5555

$ adb connect 192.168.XXX.XXX

This bug brings more errors than unable to connect to 192.168.XXX.XXX:5555: Connection refused. In my case, I could connect to the device, but when you try to run the app. AndroidStudio stay in Installing APK forever. In this case, I needed to restart the phone too.

Define an alias in fish shell

For posterity, fish aliases are just functions:

$ alias foo="echo bar"
$ type foo
foo is a function with definition
function foo
    echo bar $argv; 
end

To remove it

$ unalias foo
/usr/bin/unalias: line 2: unalias: foo: not found
$ functions -e foo
$ type foo
type: Could not find “foo”

How to change a dataframe column from String type to Double type in PySpark?

Preserve the name of the column and avoid extra column addition by using the same name as input column:

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

Blur the edges of an image or background image with CSS

If what you're looking for is simply to blur the image edges you can simply use the box-shadow with an inset.

Working example: http://jsfiddle.net/d9Q5H/1/

Screenshot

HTML:

<div class="image-blurred-edge"></div>

CSS

.image-blurred-edge {
    background-image: url('http://lorempixel.com/200/200/city/9');
    width: 200px;
    height: 200px;
    /* you need to match the shadow color to your background or image border for the desired effect*/
    box-shadow: 0 0 8px 8px white inset;
}

IE prompts to open or save json result from server

Sadly, this is just another annoying quirk of using Internet Explorer.

enter image description here

The simple solution is to run a small .reg file on your PC, to tell IE to automatically open .json files, rather than nag about whether to open/save it.

I've put a copy of the file you'll need here:

JSON mime type

You'll need to have Admin rights to run this.

Removing all script tags from html with JS Regular Expression

/(?:(?!</s\w)<[^<])</s\w*/gi; - Removes any sequence in any combination with

What is the lifetime of a static variable in a C++ function?

The existing explanations aren't really complete without the actual rule from the Standard, found in 6.7:

The zero-initialization of all block-scope variables with static storage duration or thread storage duration is performed before any other initialization takes place. Constant initialization of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope. Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

PHP string "contains"

You can use stristr() or strpos(). Both return false if nothing is found.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

What is difference between sleep() method and yield() method of multi threading?

Yield: It is a hint (not guaranteed) to the scheduler that you have done enough and that some other thread of same priority might run and use the CPU.

Thread.sleep();

Sleep: It blocks the execution of that particular thread for a given time.

TimeUnit.MILLISECONDS.sleep(1000);

Combine or merge JSON on node.js without jQuery

If you need special behaviors like nested object extension or array replacement you can use Node.js's extendify.

var extendify = require('extendify');

_.extend = extendify({
    inPlace: false,
    arrays : 'replace',
    isDeep: true
});

obj1 = {
    a:{
        arr: [1,2]
    },
    b: 4
};

obj2 = {
    a:{
        arr: [3]
    }
};

res = _.extend(obj1,obj2);
console.log(JSON.stringify(res)); //{'a':{'arr':[3]},'b':4}

What is the difference between bool and Boolean types in C#

Note that Boolean will only work were you have using System; (which is usually, but not necessarily, included) (unless you write it out as System.Boolean). bool does not need using System;

MySQL count occurrences greater than 2

SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1

The executable was signed with invalid entitlements

Had this issue occur when everything seemed to be setup correctly, build setting were pointing to correct provisioning profile, code signing was properly setup, etc.

Issue occurred because I had just created a new scheme and hadn't regenerated my CocoaPods for the new configurations. As you can see from the image, the new ad-hoc configuration is pointing to the Pods.production configuration, instead of a Pods.ad-hoc configuration (and test respectively)

Demonstrating a mis-match of ad-hoc configuration and scheme configuration

To fix:

  • Set the offending configuration to None -- cocoapods wouldn't generate the configs unless I did this
  • Close XCode
  • Run pod install
  • Re-open XCode and set the new scheme's configurations to the newly generated configurations.

That's it!

How can I easily add storage to a VirtualBox machine with XP installed?

For Windows users there's an additional user friendly option: CloneVDI Tool by mpack. It's a GUI front-end to VBoxManage that makes things a little easier to work with.

http://forums.virtualbox.org/viewtopic.php?f=6&t=22422

As Alexander M. mentioned, you'll still have to use GParted, Partition Magic or a similar partition editor to grow your partition to the newly allocated physical drive. To do this just download the GParted iso, mount it as a bootable drive in the VirtualBox and boot from it.

http://gparted.sourceforge.net/download.php

Center Plot title in ggplot2

As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot:

theme(plot.title = element_text(hjust = 0.5))

However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with

theme_update(plot.title = element_text(hjust = 0.5))

Once you have run this line, all plots created afterwards will use the theme setting plot.title = element_text(hjust = 0.5) as their default:

theme_update(plot.title = element_text(hjust = 0.5))
ggplot() + ggtitle("Default is now set to centered")

enter image description here

To get back to the original ggplot2 default settings you can either restart the R session or choose the default theme with

theme_set(theme_gray())

AngularJS Folder Structure

I like this entry about angularjs structure

It's written by one of the angularjs developers, so should give you a good insight

Here's an excerpt:

root-app-folder
+-- index.html
+-- scripts
¦   +-- controllers
¦   ¦   +-- main.js
¦   ¦   +-- ...
¦   +-- directives
¦   ¦   +-- myDirective.js
¦   ¦   +-- ...
¦   +-- filters
¦   ¦   +-- myFilter.js
¦   ¦   +-- ...
¦   +-- services
¦   ¦   +-- myService.js
¦   ¦   +-- ...
¦   +-- vendor
¦   ¦   +-- angular.js
¦   ¦   +-- angular.min.js
¦   ¦   +-- es5-shim.min.js
¦   ¦   +-- json3.min.js
¦   +-- app.js
+-- styles
¦   +-- ...
+-- views
    +-- main.html
    +-- ...

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
Response.BinaryWrite(fileContent);

And

<asp:LinkButton OnClientClick="openInNewTab();" OnClick="CodeBehindMethod".../>

In javaScript:

<script type="text/javascript">
    function openInNewTab() {
        window.document.forms[0].target = '_blank'; 
        setTimeout(function () { window.document.forms[0].target = ''; }, 0);
    }
</script>

Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.

What are the parameters for the number Pipe - Angular 2

The parameter has this syntax:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

So your example of '1.2-2' means:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

There's a strong chance that the privileges to select from table1 have been granted to a role, and the role has been granted to you. Privileges granted to a role are not available to PL/SQL written by a user, even if the user has been granted the role.

You see this a lot for users that have been granted the dba role on objects owned by sys. A user with dba role will be able to, say, SELECT * from V$SESSION, but will not be able to write a function that includes SELECT * FROM V$SESSION.

The fix is to grant explicit permissions on the object in question to the user directly, for example, in the case above, the SYS user has to GRANT SELECT ON V_$SESSION TO MyUser;

How to fill the whole canvas with specific color?

You can change the background of the canvas by doing this:

<head>
    <style>
        canvas {
            background-color: blue;
        }
    </style>
</head>

Compiler error: "initializer element is not a compile-time constant"

Because you are asking the compiler to initialize a static variable with code that is inherently dynamic.

FormData.append("key", "value") is not working

You might have been having the same problem I was initially having. I was trying to use FormData to grab all my input files to upload an image, but at the same time I wanted to append a session ID to the information passed along to the server. All this time, I thought by appending the information, you would be able to see it in the server by accessing the object. I was wrong. When you append to FormData, the way to check the appended information on the server is by a simple $_POST['*your appended data*'] query. like so:

js:

$('form').submit(function(){
    var sessionID = 8;
    var formData = new FormData(this);
    formData.append('id', sessionID);

    $.ajax({
        url: "yoururl.php",
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(data){
            alert(data);
        }
    });
});

then on php:

$sessionID = $_POST['id'];
$files = $_FILES['image'];

$foreach ($files as $key=>val){
    //...
}

Sleeping in a batch file

Over at Server Fault, a similar question was asked, and the solution there was:

choice /d y /t 5 > nul

What is the order of precedence for CSS?

First of all, based on your @extend directive, it seems you're not using pure CSS, but a preprocessor such as SASS os Stylus.

Now, when we talk about "order of precedence" in CSS, there is a general rule involved: whatever rules set after other rules (in a top-down fashion) are applied. In your case, just by specifying .smallbox after .smallbox-paysummary you would be able to change the precedence of your rules.

However, if you wanna go a bit further, I suggest this reading: CSS cascade W3C specification. You will find that the precedence of a rule is based on:

  1. The current media type;
  2. Importance;
  3. Origin;
  4. Specificity of the selector, and finally our well-known rule:
  5. Which one is latter specified.

Handling a Menu Item Click Event - Android

This is how it looks like in Kotlin

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
<item
    android:id="@+id/action_logout"
    android:orderInCategory="101"
    android:title="@string/sign_out"
    app:showAsAction="never" />

Then in MainActivity

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.main, menu)
    return true
}

This is onOptionsItemSelected function

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when(item.itemId){
        R.id.action_settings -> {
            true
        }
        R.id.action_logout -> {
            signOut()
            true
        }
        else -> return super.onOptionsItemSelected(item)
    }
}

For starting new activity

private fun signOut(){
    MySharedPreferences.clearToken()
    startSplashScreenActivity()
}

private fun startSplashScreenActivity(){
    val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
    startActivity(intent)
    finish()
}

IIS AppPoolIdentity and file system write access permissions

I tried this to fix access issues to an IIS website, which manifested as something like the following in the Event Logs ? Windows ? Application:

Log Name:      Application
Source:        ASP.NET 4.0.30319.0
Date:          1/5/2012 4:12:33 PM
Event ID:      1314
Task Category: Web Event
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      SALTIIS01

Description:
Event code: 4008 
Event message: File authorization failed for the request. 
Event time: 1/5/2012 4:12:33 PM 
Event time (UTC): 1/6/2012 12:12:33 AM 
Event ID: 349fcb2ec3c24b16a862f6eb9b23dd6c 
Event sequence: 7 
Event occurrence: 3 
Event detail code: 0 

Application information: 
    Application domain: /LM/W3SVC/2/ROOT/Application/SNCDW-19-129702818025409890 
    Trust level: Full 
    Application Virtual Path: /Application/SNCDW 
    Application Path: D:\Sites\WCF\Application\SNCDW\ 
    Machine name: SALTIIS01 

Process information: 
    Process ID: 1896 
    Process name: w3wp.exe 
    Account name: iisservice 

Request information: 
    Request URL: http://webservicestest/Application/SNCDW/PC.svc 
    Request path: /Application/SNCDW/PC.svc 
    User host address: 10.60.16.79 
    User: js3228 
    Is authenticated: True 
    Authentication Type: Negotiate 
    Thread account name: iisservice 

In the end I had to give the Windows Everyone group read access to that folder to get it to work properly.

Spring Boot - Cannot determine embedded database driver class for database type NONE

I solve my problem just adding @AutoConfigureTestDatabase(replace=Replace.NONE)

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class TestClienteRepository {

}

facebook: permanent Page Access Token?

Another PHP answer to make lives easier. Updated for Facebook Graph API 2.9 . Just fill 'er up and load.

<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
    'usertoken'=>'',
    'appid'=>'',
    'appsecret'=>'',
    'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
    $longtoken=$r->access_token;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/me?access_token={$longtoken}")); // get user id
    $userid=$r->id;
    $r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$userid}?fields=access_token&access_token={$longtoken}")); // get permanent token
    if($r->id==$args['pageid']) $finaltoken=$r->access_token;
    return $finaltoken;
}
?>

Addendum: (alternative)

Graph 2.9 onwards , you can skip much of the hassle of getting a long access token by simply clicking Extend Access Token at the bottom of the Access Token Debugger tool, after having debugged a short access token. Armed with information about pageid and longlivedtoken, run the php below to get permanent access token.

<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
    'longlivedtoken'=>'',
    'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$args['pageid']}?fields=access_token&access_token={$args['longlivedtoken']}"));
return $r->access_token;
}
?>

Although the second code saves you a lot of hassle, I recommend running the first php code unless you are in a lot of hurry because it cross-checks pageid and userid. The second code will not end up working if you choose user token by mistake.

Thanks to dw1 and Rob

How can I include css files using node, express, and ejs?

1.Create a new folder named 'public' if none exists.

2.Create a new folder named 'css' under the newly created 'public' folder

3.create your css file under the public/css path

4.On your html link css i.e <link rel="stylesheet" type="text/css" href="/css/style.css">

// note the href uses a slash(/) before and you do not need to include the 'public'

5.On your app.js include : app.use(express.static('public'));

Boom.It works!!

Simplest way to restart service on a remote computer

DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ...

    The option <server> has the form "\\ServerName"
    Further help on commands can be obtained by typing: "sc [command]"
    Commands:
      query-----------Queries the status for a service, or
                      enumerates the status for types of services.
      queryex---------Queries the extended status for a service, or
                      enumerates the status for types of services.
      start-----------Starts a service.
      pause-----------Sends a PAUSE control request to a service.
      interrogate-----Sends an INTERROGATE control request to a service.
      continue--------Sends a CONTINUE control request to a service.
      stop------------Sends a STOP request to a service.
      config----------Changes the configuration of a service (persistant).
      description-----Changes the description of a service.
      failure---------Changes the actions taken by a service upon failure.
      qc--------------Queries the configuration information for a service.
      qdescription----Queries the description for a service.
      qfailure--------Queries the actions taken by a service upon failure.
      delete----------Deletes a service (from the registry).
      create----------Creates a service. (adds it to the registry).
      control---------Sends a control to a service.
      sdshow----------Displays a service's security descriptor.
      sdset-----------Sets a service's security descriptor.
      GetDisplayName--Gets the DisplayName for a service.
      GetKeyName------Gets the ServiceKeyName for a service.
      EnumDepend------Enumerates Service Dependencies.

    The following commands don't require a service name:
    sc <server> <command> <option>
      boot------------(ok | bad) Indicates whether the last boot should
                      be saved as the last-known-good boot configuration
      Lock------------Locks the Service Database
      QueryLock-------Queries the LockStatus for the SCManager Database

EXAMPLE: sc start MyService

How to add external JS scripts to VueJS Components

The top answer of create tag in mounted is good, but it has some problems: If you change your link multiple times, it will repeat create tag over and over.

So I created a script to resolve this, and you can delete the tag if you want.

It's very simple, but can save your time to create it by yourself.

// PROJECT/src/assets/external.js

function head_script(src) {
    if(document.querySelector("script[src='" + src + "']")){ return; }
    let script = document.createElement('script');
    script.setAttribute('src', src);
    script.setAttribute('type', 'text/javascript');
    document.head.appendChild(script)
}

function body_script(src) {
    if(document.querySelector("script[src='" + src + "']")){ return; }
    let script = document.createElement('script');
    script.setAttribute('src', src);
    script.setAttribute('type', 'text/javascript');
    document.body.appendChild(script)
}

function del_script(src) {
    let el = document.querySelector("script[src='" + src + "']");
    if(el){ el.remove(); }
}


function head_link(href) {
    if(document.querySelector("link[href='" + href + "']")){ return; }
    let link = document.createElement('link');
    link.setAttribute('href', href);
    link.setAttribute('rel', "stylesheet");
    link.setAttribute('type', "text/css");
    document.head.appendChild(link)
}

function body_link(href) {
    if(document.querySelector("link[href='" + href + "']")){ return; }
    let link = document.createElement('link');
    link.setAttribute('href', href);
    link.setAttribute('rel', "stylesheet");
    link.setAttribute('type', "text/css");
    document.body.appendChild(link)
}

function del_link(href) {
    let el = document.querySelector("link[href='" + href + "']");
    if(el){ el.remove(); }
}

export {
    head_script,
    body_script,
    del_script,
    head_link,
    body_link,
    del_link,
}

And you can use it like this:

// PROJECT/src/views/xxxxxxxxx.vue

......

<script>
    import * as external from '@/assets/external.js'
    export default {
        name: "xxxxxxxxx",
        mounted(){
            external.head_script('/assets/script1.js');
            external.body_script('/assets/script2.js');
            external.head_link('/assets/style1.css');
            external.body_link('/assets/style2.css');
        },
        destroyed(){
            external.del_script('/assets/script1.js');
            external.del_script('/assets/script2.js');
            external.del_link('/assets/style1.css');
            external.del_link('/assets/style2.css');
        },
    }
</script>

......

How do I perform a JAVA callback between classes?

In this particular case, the following should work:

serverConnectionHandler = new ServerConnections(_address) {
    public void newConnection(Socket _socket) {
        System.out.println("A function of my child class was called.");
    }
};

It's an anonymous subclass.

How to convert UTF-8 byte[] to string?

Using (byte)b.ToString("x2"), Outputs b4b5dfe475e58b67

public static class Ext {

    public static string ToHexString(this byte[] hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return string.Empty;

        var s = new StringBuilder();
        foreach (byte b in hex) {
            s.Append(b.ToString("x2"));
        }
        return s.ToString();
    }

    public static byte[] ToHexBytes(this string hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return new byte[0];

        int l = hex.Length / 2;
        var b = new byte[l];
        for (int i = 0; i < l; ++i) {
            b[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
        }
        return b;
    }

    public static bool EqualsTo(this byte[] bytes, byte[] bytesToCompare)
    {
        if (bytes == null && bytesToCompare == null) return true; // ?
        if (bytes == null || bytesToCompare == null) return false;
        if (object.ReferenceEquals(bytes, bytesToCompare)) return true;

        if (bytes.Length != bytesToCompare.Length) return false;

        for (int i = 0; i < bytes.Length; ++i) {
            if (bytes[i] != bytesToCompare[i]) return false;
        }
        return true;
    }

}

Delete statement in SQL is very slow

After inspecting an SSIS Package(due to a SQL Server executing commands really slow), that was set up in a client of ours about 5-4 years before the time of me writing this, I found out that there were the below tasks: 1) insert data from an XML file into a table called [Importbarcdes].

2) merge command on an another target table, using as source the above mentioned table.

3) "delete from [Importbarcodes]", to clear the table of the row that was inserted after the XML file was read by the task of the SSIS Package.

After a quick inspection all statements(SELECT, UPDATE, DELETE etc.) on the table ImportBarcodes that had only 1 row, took about 2 minutes to execute.

Extended Events showed a whole lot PAGEIOLATCH_EX wait notifications.

No indexes were present of the table and no triggers were registered.

Upon close inspection of the properties of the table, in the Storage Tab and under general section, the Data Space field showed more than 6 GIGABYTES of space allocated in pages.

What happened:

The query ran for a good portion of time each day for the last 4 years, inserting and deleting data in the table, leaving unused pagefiles behind with out freeing them up.

So, that was the main reason of the wait events that were captured by the Extended Events Session and the slowly executed commands upon the table.

Running ALTER TABLE ImportBarcodes REBUILD fixed the issue freeing up all the unused space. TRUNCATE TABLE ImportBarcodes did a similar thing, with the only difference of deleting all pagefiles and data.

Reversing a linked list in Java, recursively

public class Singlelinkedlist {
  public static void main(String[] args) {
    Elem list  = new Elem();
    Reverse(list); //list is populate some  where or some how
  }

  //this  is the part you should be concerned with the function/Method has only 3 lines

  public static void Reverse(Elem e){
    if (e!=null)
      if(e.next !=null )
        Reverse(e.next);
    //System.out.println(e.data);
  }
}

class Elem {
  public Elem next;    // Link to next element in the list.
  public String data;  // Reference to the data.
}

select and echo a single field from mysql db using PHP

And escape your values with mysql_real_escape_string since PHP6 won't do that for you anymore! :)

Check whether a string is not null and not empty

It is a bit too late, but here is a functional style of checking:

Optional.ofNullable(str)
    .filter(s -> !(s.trim().isEmpty()))
    .ifPresent(result -> {
       // your query setup goes here
    });

Unique Key constraints for multiple columns in Entity Framework

Recently added a composite key with the uniqueness of 2 columns using the approach that 'chuck' recommended, thank @chuck. Only this approached looked cleaner to me:

public int groupId {get; set;}

[Index("IX_ClientGrouping", 1, IsUnique = true)]
public int ClientId { get; set; }

[Index("IX_ClientGrouping", 2, IsUnique = true)]
public int GroupName { get; set; }

How to make Bootstrap Panel body with fixed height

You can use max-height in an inline style attribute, as below:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

To use scrolling with content that overflows a given max-height, you can alternatively try the following:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>

To restrict the height to a fixed value you can use something like this.

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

Specify the same value for both max-height and min-height (either in pixels or in points – as long as it’s consistent).

You can also put the same styles in css class in a stylesheet (or a style tag as shown below) and then include the same in your tag. See below:

Style Code:

.fixed-panel {
  min-height: 10;
  max-height: 10;
  overflow-y: scroll;
}

Apply Style :

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>

Hope this helps with your need.

In Java, what is the best way to determine the size of an object?

I accidentally found a java class "jdk.nashorn.internal.ir.debug.ObjectSizeCalculator", already in jdk, which is easy to use and seems quite useful for determining the size of an object.

System.out.println(ObjectSizeCalculator.getObjectSize(new gnu.trove.map.hash.TObjectIntHashMap<String>(12000, 0.6f, -1)));
System.out.println(ObjectSizeCalculator.getObjectSize(new HashMap<String, Integer>(100000)));
System.out.println(ObjectSizeCalculator.getObjectSize(3));
System.out.println(ObjectSizeCalculator.getObjectSize(new int[]{1, 2, 3, 4, 5, 6, 7 }));
System.out.println(ObjectSizeCalculator.getObjectSize(new int[100]));

results:

164192
48
16
48
416

Ansible: Store command's stdout in new variable?

You have to store the content as a fact:

- set_fact:
    string_to_echo: "{{ command_output.stdout }}"

How to configure log4j.properties for SpringJUnit4ClassRunner?

I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.

What is username and password when starting Spring Boot with Tomcat?

Addition to accepted answer -

If password not seen in logs, enable "org.springframework.boot.autoconfigure.security" logs.

If you fine-tune your logging configuration, ensure that the org.springframework.boot.autoconfigure.security category is set to log INFO messages, otherwise the default password will not be printed.

https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/htmlsingle/#boot-features-security

How to change value of a request parameter in laravel

Use add

$request->request->add(['img' => $img]);

Eclipse change project files location

Using Neon - just happened to me too. You would have to delete the Eclipse version (not from disk) in your Project Explorer and import the projects as existing projects. Of course, ensure that the project folders as a whole were moved and that the Eclipse meta files are still there as mentioned by @koenpeters.

Refactor does not handle this.

Using ConfigurationManager to load config from an arbitrary location

This should do the trick :

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "newAppConfig.config);

Source : https://www.codeproject.com/Articles/616065/Why-Where-and-How-of-NET-Configuration-Files

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

Calling a function on bootstrap modal open

you can use show instead of shown for making the function to load just before modal open, instead of after modal open.

$('#code').on('show.bs.modal', function (e) {
  // do something...
})

fitting data with numpy

Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.

from numpy.polynomial import Polynomial

p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())

p uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with

pnormal = p.convert(domain=(-1, 1))

trigger body click with jQuery

You should have something like this:

$('body').click(function() {
   // do something here
});

The callback function will be called when the user clicks somewhere on the web page. You can trigger the callback programmatically with:

$('body').trigger('click');

PL/SQL block problem: No data found error

This data not found causes because of some datatype we are using .

like select empid into v_test

above empid and v_test has to be number type , then only the data will be stored .

So keep track of the data type , when getting this error , may be this will help

How to copy multiple files in one layer using a Dockerfile?

simple

COPY README.md  package.json gulpfile.js __BUILD_NUMBER ./

from the doc

If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.

jQuery to remove an option from drop down list, given option's text/value

I know it is very late but following approach can also be used:

<select id="type" name="type" >
    <option value="Permanent" id="permanent">I am here to stay.</option>
    <option value="toremove" id="toremove">Remove me!</option>
    <option value="Other" id="other">Other</option>
</select>

and if I have to remove second option (id=toremove), the script would look like

$('#toremove').hide();

How to uninstall / completely remove Oracle 11g (client)?

There are some more actions you should consider:

  • Remove Registry Entries for MS Distributed Transaction Coordinator (MSDTC)

    Note: on the Internet I found this step only at a single (private) page. I don't know if it is required/working or if it breaks anything on your PC.

    • Open Regedit
    • Navigate to HKEY_LOCAL_MACHINE\Software\Microsoft\MSDTC\MTxOCI
    • Add an x before each string for OracleOciLib, OracleSqlLib, and OracleXaLib
    • Navigate to HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\MSDTC\MTxOCI
    • Add an x before each string for OracleOciLib, OracleSqlLib, and OracleXaLib

    Otherwise these files, if they exist, will still be in use next time you reboot, and unable to be deleted.

  • Remove environment variable ORACLE_HOME, ORACLE_BASE, TNS_ADMIN, NLS_LANG if exist

    Check also Oracle doc to find all Oracle related environment variables, however apart from variables listed above they are very rarely used on Windows Client: Oracle Environment Variables

  • Unregister oci.dll

    • Open a command line window (Start Menu -> Run... -> cmd)
    • Enter regsvr32 /u oci.dll, resp. %windir%\SysWOW64\regsvr32 /u oci.dll

    • In some cases the file %ORACLE_HOME%\bin\oci.dll is locked and you cannot delete it. In such case rename the file (e.g. to oci.dll.x) and reboot the PC, afterwards you can delete it.

  • Remove Oracle .NET assemblies from Global Assembly Cache (GAC). You do this typically with the gacutil utility, if available on your system. Would be like this:

    gacutil /u Policy.10.1.Oracle.DataAccess
    gacutil /u Policy.10.2.Oracle.DataAccess
    gacutil /u Policy.1.102.Oracle.DataAccess
    gacutil /u Policy.1.111.Oracle.DataAccess
    
    gacutil /u Policy.2.102.Oracle.DataAccess
    gacutil /u Policy.2.111.Oracle.DataAccess
    gacutil /u Policy.2.112.Oracle.DataAccess
    gacutil /u Policy.2.121.Oracle.DataAccess
    gacutil /u Policy.2.122.Oracle.DataAccess
    
    gacutil /u Policy.4.112.Oracle.DataAccess
    gacutil /u Policy.4.121.Oracle.DataAccess
    gacutil /u Policy.4.122.Oracle.DataAccess
    
    gacutil /u Oracle.DataAccess
    gacutil /u Oracle.DataAccess.resources
    
    gacutil /u Policy.4.121.Oracle.ManagedDataAccess
    gacutil /u Policy.4.122.Oracle.ManagedDataAccess
    gacutil /u Oracle.ManagedDataAccess
    gacutil /u Oracle.ManagedDataAccess.resources
    gacutil /u Oracle.ManagedDataAccessDTC
    gacutil /u Oracle.ManagedDataAccessIOP
    gacutil /u Oracle.ManagedDataAccess.EntityFramework
    
    • Entry System.Data.OracleClient should not be removed, this one is installed by Microsoft - not an Oracle component!

    • Instead of gacutil /u ... you can also use OraProvCfg /action:ungac /providerpath:... if OraProvCfg is still available on your system. You may find it at %ORACLE_HOME%\odp.net\managed\x64\OraProvCfg.exe.

  • With a text editor, open XML Config file %SYSTEMROOT%\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config and delete branch <oracle.manageddataaccess.client>, if existing.

    • Do the same with:

      %SYSTEMROOT%\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config
      %SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
      %SYSTEMROOT%\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
      %SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319\Config\web.config
      

    Instead of editing the XML Config file manually you can also run (if OraProvCfg.exe is still available on your system):

    %ORACLE_HOME%\odp.net\managed\x64\OraProvCfg.exe /action:unconfig /product:odpm /frameworkversion:v4.0.30319 
    %ORACLE_HOME%\odp.net\managed\x86\OraProvCfg.exe /action:unconfig /product:odpm /frameworkversion:v4.0.30319
    %ORACLE_HOME%\odp.net\managed\x64\OraProvCfg.exe /action:unconfig /product:odp /frameworkversion:v4.0.30319 
    %ORACLE_HOME%\odp.net\managed\x86\OraProvCfg.exe /action:unconfig /product:odp /frameworkversion:v4.0.30319
    
  • Check following Registry Keys and delete them if existing

    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess.EntityFramework6
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\odp.net.managed
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.DataAccess.EntityFramework6\
    
    HKLM\SOFTWARE\Microsoft\.NETFramework\v2.0.50727\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess.EntityFramework6
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\odp.net.managed
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.DataAccess.EntityFramework6\
    
    HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\Oracle Data Provider for .NET, Managed Driver
    HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\Oracle Data Provider for .NET, Unmanaged Driver
    HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\Oracle Provider for OLE DB
    
  • Delete the Inventory folder, typically C:\Program Files\Oracle\Inventory and C:\Program Files (x86)\Oracle\Inventory

  • Delete temp folders %TEMP%\deinstall\, %TEMP%\OraInstall\ and %TEMP%\CVU* (e.g %TEMP%\CVU_11.1.0.2.0_domscheit) if existing.

jQuery SVG, why can't I addClass?

Here is my rather inelegant but working code that deals with the following issues (without any dependencies):

  • classList not existing on <svg> elements in IE
  • className not representing the class attribute on <svg> elements in IE
  • Old IE's broken getAttribute() and setAttribute() implementations

It uses classList where possible.

Code:

var classNameContainsClass = function(fullClassName, className) {
    return !!fullClassName &&
           new RegExp("(?:^|\\s)" + className + "(?:\\s|$)").test(fullClassName);
};

var hasClass = function(el, className) {
    if (el.nodeType !== 1) {
        return false;
    }
    if (typeof el.classList == "object") {
        return (el.nodeType == 1) && el.classList.contains(className);
    } else {
        var classNameSupported = (typeof el.className == "string");
        var elClass = classNameSupported ? el.className : el.getAttribute("class");
        return classNameContainsClass(elClass, className);
    }
};

var addClass = function(el, className) {
    if (el.nodeType !== 1) {
        return;
    }
    if (typeof el.classList == "object") {
        el.classList.add(className);
    } else {
        var classNameSupported = (typeof el.className == "string");
        var elClass = classNameSupported ?
            el.className : el.getAttribute("class");
        if (elClass) {
            if (!classNameContainsClass(elClass, className)) {
                elClass += " " + className;
            }
        } else {
            elClass = className;
        }
        if (classNameSupported) {
            el.className = elClass;
        } else {
            el.setAttribute("class", elClass);
        }
    }
};

var removeClass = (function() {
    function replacer(matched, whiteSpaceBefore, whiteSpaceAfter) {
        return (whiteSpaceBefore && whiteSpaceAfter) ? " " : "";
    }

    return function(el, className) {
        if (el.nodeType !== 1) {
            return;
        }
        if (typeof el.classList == "object") {
            el.classList.remove(className);
        } else {
            var classNameSupported = (typeof el.className == "string");
            var elClass = classNameSupported ?
                el.className : el.getAttribute("class");
            elClass = elClass.replace(new RegExp("(^|\\s)" + className + "(\\s|$)"), replacer);
            if (classNameSupported) {
                el.className = elClass;
            } else {
                el.setAttribute("class", elClass);
            }
        }
    }; //added semicolon here
})();

Example usage:

var el = document.getElementById("someId");
if (hasClass(el, "someClass")) {
    removeClass(el, "someClass");
}
addClass(el, "someOtherClass");

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

REST API using POST instead of GET

In REST, each HTTP verbs has its place and meaning.

For example,

  • GET is to get the 'resource(s)' that is pointed to in the URL.

  • POST is to instructure the backend to 'create' a resource of the 'type' pointed to in the URL. You can supplement the POST operation with parameters or additional data in the body of the POST call.

In you case, since you are interested in 'getting' the info using query, thus it should be a GET operation instead of a POST operation.

This wiki may help to further clarify things.

Hope this help!

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app. in API constructor add the following:

public class TargetClassController : ControllerBase
{
    private readonly IConfiguration _config;

    public TargetClassController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<DTOResponse>> Get(int id)
    {
        var config = _config["YourKeySection:key"];
    }
}

Java Class.cast() vs. cast operator

Generally the cast operator is preferred to the Class#cast method as it's more concise and can be analyzed by the compiler to spit out blatant issues with the code.

Class#cast takes responsibility for type checking at run-time rather than during compilation.

There are certainly use-cases for Class#cast, particularly when it comes to reflective operations.

Since lambda's came to java I personally like using Class#cast with the collections/stream API if I'm working with abstract types, for example.

Dog findMyDog(String name, Breed breed) {
    return lostAnimals.stream()
                      .filter(Dog.class::isInstance)
                      .map(Dog.class::cast)
                      .filter(dog -> dog.getName().equalsIgnoreCase(name))
                      .filter(dog -> dog.getBreed() == breed)
                      .findFirst()
                      .orElse(null);
}

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

This worked for me allowing me to co-locate javascript and html for partial view in same file. Helps with thought process to see html and related part in same partial view file.


In View which uses Partial View called "_MyPartialView.cshtml"

<div>
    @Html.Partial("_MyPartialView",< model for partial view>,
            new ViewDataDictionary { { "Region", "HTMLSection" } } })
</div>

@section scripts{

    @Html.Partial("_MyPartialView",<model for partial view>, 
                  new ViewDataDictionary { { "Region", "ScriptSection" } })

 }

In Partial View file

@model SomeType

@{
    var region = ViewData["Region"] as string;
}

@if (region == "HTMLSection")
{


}

@if (region == "ScriptSection")
{
        <script type="text/javascript">
    </script">
}

What is AndroidX?

AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.

AndroidX is a major improvement to the original Android Support Library. Like the Support Library, AndroidX ships separately from the Android OS and provides backward-compatibility across Android releases. AndroidX fully replaces the Support Library by providing feature parity and new libraries.

AndroidX includes the following features:

  • All packages in AndroidX live in a consistent namespace starting with the string androidx. The Support Library packages have been mapped into the corresponding androidx.* packages. For a full mapping of all the old classes and build artifacts to the new ones, see the Package Refactoring page.

  • Unlike the Support Library, AndroidX packages are separately maintained and updated. The androidx packages use strict Semantic Versioning starting with version 1.0.0. You can update AndroidX libraries in your project independently.

  • All new Support Library development will occur in the AndroidX library. This includes maintenance of the original Support Library artifacts and introduction of new Jetpack components.

Using AndroidX

See Migrating to AndroidX to learn how to migrate an existing project.

If you want to use AndroidX in a new project, you need to set the compile SDK to Android 9.0 (API level 28) or higher and set both of the following Android Gradle plugin flags to true in your gradle.properties file.

  • android.useAndroidX: When set to true, the Android plugin uses the appropriate AndroidX library instead of a Support Library. The flag is false by default if it is not specified.

  • android.enableJetifier: When set to true, the Android plugin automatically migrates existing third-party libraries to use AndroidX by rewriting their binaries. The flag is false by default if it is not specified.

For Artifact mappings see this

Angular - How to apply [ngStyle] conditions

[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"

show loading icon until the page is load?

HTML page

<div id="overlay">
<img src="<?php echo base_url()?>assest/website/images/loading1.gif" alt="Loading" />
 Loading...
</div>

Script

$(window).load(function(){ 
 //PAGE IS FULLY LOADED 
 //FADE OUT YOUR OVERLAYING DIV
 $('#overlay').fadeOut();
});

python numpy/scipy curve fitting

I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit tries to fit a function f that you must know to a set of points.

This is a simple 3 degree polynomial fit using numpy.polyfit and poly1d, the first performs a least squares polynomial fit and the second calculates the new points:

import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()

enter image description here

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

MySQL Workbench: How to keep the connection alive

OK - so this issue has been driving me crazy - v 6.3.6 on Ubuntu Linux. None of the above solutions worked for me. Connecting to localhost mysql server previously always worked fine. Connecting to remote server always timed out - after about 60 seconds, sometimes after less time, sometimes more.

What finally worked for me was upgrading Workbench to 6.3.9 - no more dropped connections.

How can I truncate a double to only two decimal places in Java?

You can use NumberFormat Class object to accomplish the task.

// Creating number format object to set 2 places after decimal point
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);            
nf.setGroupingUsed(false);

System.out.println(nf.format(precision));// Assuming precision is a double type variable

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

With the help of a temporary item class

public class item
{
    [XmlAttribute]
    public int id;
    [XmlAttribute]
    public string value;
}

Sample Dictionary:

Dictionary<int, string> dict = new Dictionary<int, string>()
{
    {1,"one"}, {2,"two"}
};

.

XmlSerializer serializer = new XmlSerializer(typeof(item[]), 
                                 new XmlRootAttribute() { ElementName = "items" });

Serialization

serializer.Serialize(stream, 
              dict.Select(kv=>new item(){id = kv.Key,value=kv.Value}).ToArray() );

Deserialization

var orgDict = ((item[])serializer.Deserialize(stream))
               .ToDictionary(i => i.id, i => i.value);

------------------------------------------------------------------------------

Here is how it can be done using XElement, if you change your mind.

Serialization

XElement xElem = new XElement(
                    "items",
                    dict.Select(x => new XElement("item",new XAttribute("id", x.Key),new XAttribute("value", x.Value)))
                 );
var xml = xElem.ToString(); //xElem.Save(...);

Deserialization

XElement xElem2 = XElement.Parse(xml); //XElement.Load(...)
var newDict = xElem2.Descendants("item")
                    .ToDictionary(x => (int)x.Attribute("id"), x => (string)x.Attribute("value"));

jQuery animate margin top

check this same effect with less code

$(".item").mouseover(function(){
    $('.info').animate({ marginTop: '-50px' , opacity: 0.5 }, 1000);
}); 

View recent fiddle

smooth scroll to top

You can simply use

_x000D_
_x000D_
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
        document.getElementById("gotoTop").style.display = "block";_x000D_
    } else {_x000D_
        document.getElementById("gotoTop").style.display = "none";_x000D_
    }_x000D_
   _x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
 _x000D_
     $('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  font-size: 20px;_x000D_
}_x000D_
_x000D_
#gotoTop {_x000D_
  display: none;_x000D_
  position: fixed;_x000D_
  bottom: 20px;_x000D_
  right: 30px;_x000D_
  z-index: 99;_x000D_
  font-size: 18px;_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  cursor: pointer;_x000D_
  padding: 15px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
_x000D_
#gotoTop:hover {_x000D_
  background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="gotoTop" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
_x000D_
_x000D_

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

and then run as sqlplus -s username/password @vijay.sql '20100101'

How to check if any flags of a flag combination are set?

You could just check if the value is not zero.

if ((Int32)(letter & Letters.AB) != 0) { }

But I would consider it a better solution to introduce a new enumeration value with value zero and compare agains this enumeration value (if possible because you must be able to modify the enumeration).

[Flags]
enum Letters
{
    None = 0,
    A    = 1,
    B    = 2,
    C    = 4,
    AB   =  A | B,
    All  = AB | C
}

if (letter != Letters.None) { }

UPDATE

Missread the question - fixed the first suggestion and just ignore the second suggestion.

ToList()-- does it create a new list?

ToList will always create a new list, which will not reflect any subsequent changes to the collection.

However, it will reflect changes to the objects themselves (Unless they're mutable structs).

In other words, if you replace an object in the original list with a different object, the ToList will still contain the first object.
However, if you modify one of the objects in the original list, the ToList will still contain the same (modified) object.

How to open google chrome from terminal?

On Linux, just use this command in a terminal:

google-chrome

Amazon S3 direct file upload from client browser - private key disclosure

If you don't have any server side code, you security depends on the security of the access to your JavaScript code on the client side (ie everybody who has the code could upload something).

So I would recommend, to simply create a special S3 bucket which is public writeable (but not readable), so you don't need any signed components on the client side.

The bucket name (a GUID eg) will be your only defense against malicious uploads (but a potential attacker could not use your bucket to transfer data, because it is write only to him)

How to use ConfigurationManager

Go to tools >> nuget >> console and type:

Install-Package System.Configuration.ConfigurationManager 

If you want a specific version:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

Your ConfigurationManager dll will now be imported and the code will begin to work.

What is duck typing?

Looking at the language itself may help; it often helps me (I'm not a native English speaker).

In duck typing:

1) the word typing does not mean typing on a keyboard (as was the persistent image in my mind), it means determining "what type of a thing is that thing?"

2) the word duck expresses how is that determining done; it's kind of a 'loose' determining, as in: "if it walks like a duck ... then it's a duck". It's 'loose' because the thing may be a duck or may not, but whether it actually is a duck doesn't matter; what matters is that I can do with it what I can do with ducks and expect behaviors exhibited by ducks. I can feed it bread crumbs and the thing may go towards me or charge at me or back off ... but it will not devour me like a grizzly would.

How do I concatenate strings and variables in PowerShell?

These answers all seem very complicated. If you are using this in a PowerShell script you can simply do this:

$name = 'Slim Shady'
Write-Host 'My name is'$name

It will output

My name is Slim Shady

Note how a space is put between the words for you

Checking for the correct number of arguments

cat script.sh

    var1=$1
    var2=$2
    if [ "$#" -eq 2 ]
    then
            if [ -d $var1 ]
            then
            echo directory ${var1} exist
            else
            echo Directory ${var1} Does not exists
            fi
            if [ -d $var2 ]
            then
            echo directory ${var2} exist
            else
            echo Directory ${var2} Does not exists
            fi
    else
    echo "Arguments are not equals to 2"
    exit 1
    fi

execute it like below -

./script.sh directory1 directory2

Output will be like -

directory1 exit
directory2 Does not exists

Selecting default item from Combobox C#

private void comboBox_Loaded(object sender, RoutedEventArgs e)
{
 Combobox.selectedIndex= your index;
}

OR if you want to display some value after comparing into combobox

 foreach (var item in comboBox.Items)
            {
                if (item.ToString().ToLower().Equals("your item in lower"))
                {
                    comboBox.SelectedValue = item;
                }
            }

I hope it will help, it works for me.

Set the value of an input field

It's simple; An example is:

<input type="text" id="example"> // Setup text field 
<script type="text/javascript"> 
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Twitter bootstrap modal-backdrop doesn't disappear

.modal('hide')

Manually hides a modal. Returns to the caller before the modal has actually been hidden (i.e. before the hidden.bs.modal event occurs).

So instead of

$('#myModal').modal('hide');
$('#someOtherSelector').trigger('click');

do

$('#myModal').modal('hide');
$('#myModal').on('hidden.bs.modal', function() {
   $('#someOtherSelector').trigger('click');
});

So you are sure to wait till the "hide" event is finished.

How do I toggle an ng-show in AngularJS based on a boolean?

It's worth noting that if you have a button in Controller A and the element you want to show in Controller B, you may need to use dot notation to access the scope variable across controllers.

For example, this will not work:

<div ng-controller="ControllerA">
  <a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

To solve this, create a global variable (ie. in Controller A or your main Controller):

.controller('ControllerA', function ($scope) {
  $scope.global = {};
}

Then add a 'global' prefix to your click and show variables:

<div ng-controller="ControllerA">
  <a ng-click="global.isReplyFormOpen = !global.isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="global.isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

For more detail, check out the Nested States & Nested Views in the Angular-UI documentation, watch a video, or read understanding scopes.

Docker expose all ports or range of ports from 7000 to 8000

Since Docker 1.5 you can now expose a range of ports to other linked containers using:

The Dockerfile EXPOSE command:

EXPOSE 7000-8000

or The Docker run command:

docker run --expose=7000-8000

Or instead you can publish a range of ports to the host machine via Docker run command:

docker run -p 7000-8000:7000-8000

Save array in mysql database

The way things like that are done is with serializing the array, which means "making a string out of it". To better understand this, have a look on this:

$array = array("my", "litte", "array", 2);

$serialized_array = serialize($array); 
$unserialized_array = unserialize($serialized_array); 

var_dump($serialized_array); // gives back a string, perfectly for db saving!
var_dump($unserialized_array); // gives back the array again

Get absolute path of initially run script

echo realpath(dirname(__FILE__));

If you place this in an included file, it prints the path to this include. To get the path of the parent script, replace __FILE__ with $_SERVER['PHP_SELF']. But be aware that PHP_SELF is a security risk!

jQuery UI DatePicker - Change Date Format

you can simply use this format in you function just like

     $(function() {  
        $( "#datepicker" ).datepicker({
            dateFormat: 'dd/mm/yy',
          changeMonth: true,
          changeYear: true
        });
      });

<input type="text" id="datepicker"></p>

How to insert data into elasticsearch

Simple fundamentals, Elastic community has exposed indexing, searching, deleting operation as rest web service. You can interact elastic using curl or sense(chrome plugin) or any rest client like postman.

If you are just testing few commands, I would recommend can use of sense chrome plugin which has simple UI and pretty mature plugin now.

Dynamic function name in javascript?

The most voted answer has got already defined [String] function body. I was looking for the solution to rename already declared function's name and finally after an hour of struggling I've dealt with it. It:

  • takes the alredy declared function
  • parses it to [String] with .toString() method
  • then overwrites the name (of named function) or appends the new one (when anonymous) between function and (
  • then creates the new renamed function with new Function() constructor

_x000D_
_x000D_
function nameAppender(name,fun){_x000D_
  const reg = /^(function)(?:\s*|\s+([A-Za-z0-9_$]+)\s*)(\()/;_x000D_
  return (new Function(`return ${fun.toString().replace(reg,`$1 ${name}$3`)}`))();_x000D_
}_x000D_
_x000D_
//WORK FOR ALREADY NAMED FUNCTIONS:_x000D_
function hello(name){_x000D_
  console.log('hello ' + name);_x000D_
}_x000D_
_x000D_
//rename the 'hello' function_x000D_
var greeting = nameAppender('Greeting', hello); _x000D_
_x000D_
console.log(greeting); //function Greeting(name){...}_x000D_
_x000D_
_x000D_
//WORK FOR ANONYMOUS FUNCTIONS:_x000D_
//give the name for the anonymous function_x000D_
var count = nameAppender('Count',function(x,y){ _x000D_
  this.x = x;_x000D_
  this.y = y;_x000D_
  this.area = x*y;_x000D_
}); _x000D_
_x000D_
console.log(count); //function Count(x,y){...}
_x000D_
_x000D_
_x000D_

Read file data without saving it in Flask

FileStorage contains stream field. This object must extend IO or file object, so it must contain read and other similar methods. FileStorage also extend stream field object attributes, so you can just use file.read() instead file.stream.read(). Also you can use save argument with dst parameter as StringIO or other IO or file object to copy FileStorage.stream to another IO or file object.

See documentation: http://flask.pocoo.org/docs/api/#flask.Request.files and http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.

SQL: Return "true" if list of records exists?

Where is this list of products that you're trying to determine the existence of? If that list exists within another table you could do this

declare @are_equal bit
declare @products int

SELECT @products = 
     count(pl.id)
FROM ProductList pl
JOIN Products p
ON pl.productId = p.productId

select @are_equal = @products == select count(id) from ProductList

Edit:

Then do ALL the work in C#. Cache the actual list of products in your application somewhere, and do a LINQ query.

var compareProducts = new List<Product>(){p1,p2,p3,p4,p5};
var found = From p in GetAllProducts()
            Join cp in compareProducts on cp.Id equals p.Id
            select p;

return compareProducts.Count == found.Count;

This prevents constructing SQL queries by hand, and keeps all your application logic in the application.

What's the easiest way to escape HTML in Python?

In Python 3.2 a new html module was introduced, which is used for escaping reserved characters from HTML markup.

It has one function escape():

>>> import html
>>> html.escape('x > 2 && x < 7 single quote: \' double quote: "')
'x &gt; 2 &amp;&amp; x &lt; 7 single quote: &#x27; double quote: &quot;'

why windows 7 task scheduler task fails with error 2147942667

For me it was the "Start In" - I accidentally left in the '.py' at the end of the name of my program. And I forgot to capitalize the name of the folder it was in ('Apps').

How to add a second css class with a conditional value in razor MVC 4

This:

    <div class="details @(Model.Details.Count > 0 ? "show" : "hide")">

will render this:

    <div class="details hide">

and is the mark-up I want.

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

How to check variable type at runtime in Go language

What's wrong with

func (e *Easy)SetStringOption(option Option, param string)
func (e *Easy)SetLongOption(option Option, param long)

and so on?

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you are using vscode I would recommend you to click the option at the bottom-right of the window and set it to LF from CRLF..this fixed my errors

Python datetime strptime() and strftime(): how to preserve the timezone information

Unfortunately, strptime() can only handle the timezone configured by your OS, and then only as a time offset, really. From the documentation:

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

strftime() doesn't officially support %z.

You are stuck with python-dateutil to support timezone parsing, I am afraid.

How to add header to a dataset in R?

in case you are interested in reading some data from a .txt file and only extract few columns of that file into a new .txt file with a customized header, the following code might be useful:

# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")

# assign the name for the output file:
seqName <- "seq1_data.txt"

#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx        <- civit_cam$q.x.rad.
qy        <- civit_cam$q.y.rad.
qz        <- civit_cam$q.z.rad.
qw        <- civit_cam$q.w

# From GPS:
gpsT      <- civit_gps$X.gpsTime.sec.
latitude  <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude  <- civit_gps$H.Ell.m.
heading   <- civit_gps$Heading.deg.
pitch     <- civit_gps$pitch.deg.
roll      <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]

#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
                     c(frame_idx),
                     c(qx),
                     c(qy),
                     c(qz),
                     c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")

Of course, you should modify this sample script based on your own application.

What is the difference between onBlur and onChange attribute in HTML?

onblur fires when a field loses focus, while onchange fires when that field's value changes. These events will not always occur in the same order, however.

In Firefox, tabbing out of a changed field will fire onchange then onblur, and it will normally do the same in IE. However, if you press the enter key instead of tab, in Firefox it will fire onblur then onchange, while IE will usually fire in the original order. However, I've seen cases where IE will also fire blur first, so be careful. You can't assume that either the onblur or the onchange will happen before the other one.

Javascript : get <img> src and set as variable?

As long as the script is after the img, then:

var youtubeimgsrc = document.getElementById("youtubeimg").src;

See getElementById in the DOM specification.

If the script is before the img, then of course the img doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body element.


Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:

<img id="foo" src="/images/example.png">

...the src reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com, document.getElementById("foo").src would give you "http://www.example.com/images/example.png".

If you wanted the src attribute's content as is, without being resolved, you'd use getAttribute instead: document.getElementById("foo").getAttribute("src"). That would give you "/images/example.png" with my example above.

If you have an absolute URL, like the one in your question, it doesn't matter.

Get the time difference between two datetimes

This should work fine.

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);

console.log(d.days() + ':' + d.hours() + ':' + d.minutes() + ':' + d.seconds());

How do I link a JavaScript file to a HTML file?

Below you have some VALID html5 example document. The type attribute in script tag is not mandatory in HTML5.

You use jquery by $ charater. Put libraries (like jquery) in <head> tag - but your script put allways at the bottom of document (<body> tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src attribute in bottom script tag to include you script file instead of putting direct js code like above.

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <title>Example</title>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
    <div>Im the content</div>_x000D_
_x000D_
    <script>_x000D_
        alert( $('div').text() ); // show message with div content_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

nodejs npm global config missing on windows

How to figure it out

Start with npm root -- it will show you the root folder for NPM packages for the current user. Add -g and you get a global folder. Don't forget to substract node_modules.

Use npm config / npm config -g and check that it'd create you a new .npmrc / npmrc file for you.

Tested on Windows 10 Pro, NPM v.6.4.1:

Global NPM config

C:\Users\%username%\AppData\Roaming\npm\etc\npmrc

Per-user NPM config

C:\Users\%username%\.npmrc

Built-in NPM config

C:\Program Files\nodejs\node_modules\npm\npmrc

References:

How can I debug a .BAT script?

The only way I can think of is spinkle the code with echos and pauses.

Determine if 2 lists have the same elements, regardless of order?

You can simply check whether the multisets with the elements of x and y are equal:

import collections
collections.Counter(x) == collections.Counter(y)

This requires the elements to be hashable; runtime will be in O(n), where n is the size of the lists.

If the elements are also unique, you can also convert to sets (same asymptotic runtime, may be a little bit faster in practice):

set(x) == set(y)

If the elements are not hashable, but sortable, another alternative (runtime in O(n log n)) is

sorted(x) == sorted(y)

If the elements are neither hashable nor sortable you can use the following helper function. Note that it will be quite slow (O(n²)) and should generally not be used outside of the esoteric case of unhashable and unsortable elements.

def equal_ignore_order(a, b):
    """ Use only when elements are neither hashable nor sortable! """
    unmatched = list(b)
    for element in a:
        try:
            unmatched.remove(element)
        except ValueError:
            return False
    return not unmatched

How to delete all files and folders in a directory?

Yes, that's the correct way to do it. If you're looking to give yourself a "Clean" (or, as I'd prefer to call it, "Empty" function), you can create an extension method.

public static void Empty(this System.IO.DirectoryInfo directory)
{
    foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
    foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}

This will then allow you to do something like..

System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\...");

directory.Empty();

how to use html2canvas and jspdf to export to pdf in a proper and simple way

This one shows how to print only selected element on the page with dpi/resolution adjustments

HTML:

<html>

  <body>
    <header>This is the header</header>
    <div id="content">
      This is the element you only want to capture
    </div>
    <button id="print">Download Pdf</button>
    <footer>This is the footer</footer>
  </body>

</html>

CSS:

body {
  background: beige;
}

header {
  background: red;
}

footer {
  background: blue;
}

#content {
  background: yellow;
  width: 70%;
  height: 100px;
  margin: 50px auto;
  border: 1px solid orange;
  padding: 20px;
}

JS:

$('#print').click(function() {

  var w = document.getElementById("content").offsetWidth;
  var h = document.getElementById("content").offsetHeight;
  html2canvas(document.getElementById("content"), {
    dpi: 300, // Set to 300 DPI
    scale: 3, // Adjusts your resolution
    onrendered: function(canvas) {
      var img = canvas.toDataURL("image/jpeg", 1);
      var doc = new jsPDF('L', 'px', [w, h]);
      doc.addImage(img, 'JPEG', 0, 0, w, h);
      doc.save('sample-file.pdf');
    }
  });
});

jsfiddle: https://jsfiddle.net/marksalvania/dum8bfco/

Share application "link" in Android

Share application with title is you app_name, content is your application link

private static void shareApp(Context context) {
    final String appPackageName = BuildConfig.APPLICATION_ID;
    final String appName = context.getString(R.string.app_name);
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    String shareBodyText = "https://play.google.com/store/apps/details?id=" +
            appPackageName;
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, appName);
    shareIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
    context.startActivity(Intent.createChooser(shareIntent, context.getString(R.string
            .share_with)));
}

Xcode 10, Command CodeSign failed with a nonzero exit code

In my experience, the reason that caused this problem was I wrongly reset the Keychain Access to default, so I lost my development certificate.

How did I solve this?

  1. I cleaned my Apple Development Certificate from Keychain Access
  2. I cleaned my Apple Development private key from Keychain Access
  3. Then I got the new error : Revoke certificate Your account already has an Apple Development signing certificate for this machine, but its private key is not installed in your keychain. Xcode can create a new one after revoking your existing certificate.
  4. Go to Xcode Preference -> Accounts Tab -> Fine the team name under the Apple ID -> Double Click it -> Click the + button at the bottom left of box -> Select App Development
  5. In the team drop-down of the target, select "None"
  6. Re-select the correct development team
  7. Clean the project by shift+cmd+k
  8. Rebuild the project cmd+b

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

You have to change delimiter before using triggers, stored procedures and so on.

delimiter //
create procedure ProG() 
begin 
SELECT * FROM hs_hr_employee_leave_quota;
end;//
delimiter ;

Generating Fibonacci Sequence

You're not assigning a value to z, so what do you expect y=z; to do? Likewise you're never actually reading from the array. It looks like you're trying a combination of two different approaches here... try getting rid of the array entirely, and just use:

// Initialization of x and y as before

for (i = 2; i <= 10; i++)
{
    alert(x + y);
    z = x + y;
    x = y;
    y = z;
}

EDIT: The OP changed the code after I'd added this answer. Originally the last line of the loop was y = z; - and that makes sense if you've initialized z as per my code.

If the array is required later, then obviously that needs to be populated still - but otherwise, the code I've given should be fine.

SQL sum with condition

Try this instead:

SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)

Explanation

Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:

The CASE expression has two formats:

  • The simple CASE expression compares an expression to a set of simple expressions to determine the result.
  • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

You want the searched CASE expression syntax:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.

Laravel 5.4 Specific Table Migration

You can only rollback:

php artisan migrate:rollback

https://laravel.com/docs/5.4/migrations#rolling-back-migrations

You can specify how many migrations to roll back to using the 'step' option:

php artisan migrate:rollback --step=1

Some tricks are available here:

Rollback one specific migration in Laravel

How to plot a 2D FFT in Matlab?

Assuming that I is your input image and F is its Fourier Transform (i.e. F = fft2(I))

You can use this code:

F = fftshift(F); % Center FFT

F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1

imshow(F,[]); % Display the result

How to embed a .mov file in HTML?

Well, if you don't want to do the work yourself (object elements aren't really all that hard), you could always use Mike Alsup's Media plugin: http://jquery.malsup.com/media/

What does \0 stand for?

In C, \0 denotes a character with value zero. The following are identical:

char a = 0;
char b = '\0';

The utility of this escape sequence is greater inside string literals, which are arrays of characters:

char arr[] = "abc\0def\0ghi\0";

(Note that this array has two zero characters at the end, since string literals include a hidden, implicit terminal zero.)

Change hash without reload in jQuery

The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)
    event.preventDefault();

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {    
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
        }
    }
});

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

Why not to use separate func?

def func(*args, **kwargs):
    return inst.method(args, kwargs)

print pool.map(func, arr)

Remove Sub String by using Python

import re
re.sub('<.*?>', '', string)
"i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"

The re.sub function takes a regular expresion and replace all the matches in the string with the second parameter. In this case, we are searching for all tags ('<.*?>') and replacing them with nothing ('').

The ? is used in re for non-greedy searches.

More about the re module.

How to build a 'release' APK in Android Studio?

AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle

android {

    signingConfigs {

        release {

            storeFile file('android.keystore')
            storePassword "pwd"
            keyAlias "alias"
            keyPassword "pwd"
        }
    }

    buildTypes {

       release {

           signingConfig signingConfigs.release
       }
    }
}

To actually run your application at emulator or device run gradle installDebug or gradle installRelease.

You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872

Service vs IntentService in the Android platform

Don't reinvent the wheel

IntentService extends Service class which clearly means that IntentService is intentionally made for same purpose.

So what is the purpose ?

`IntentService's purpose is to make our job easier to run background tasks without even worrying about

  • Creation of worker thread

  • Queuing the processing multiple-request one by one (Threading)

  • Destroying the Service

So NO, Service can do any task which an IntentService would do. If your requirements fall under the above-mentioned criteria, then you don't have to write those logics in the Service class. So don't reinvent the wheel because IntentService is the invented wheel.

The "Main" difference

The Service runs on the UI thread while an IntentService runs on a separate thread

When do you use IntentService?

When you want to perform multiple background tasks one by one which exists beyond the scope of an Activity then the IntentService is perfect.

How IntentService is made from Service

A normal service runs on the UI Thread(Any Android Component type runs on UI thread by default eg Activity, BroadcastReceiver, ContentProvider and Service). If you have to do some work that may take a while to complete then you have to create a thread. In the case of multiple requests, you will have to deal with synchronization. IntentService is given some default implementation which does those tasks for you.
According to developer page

  1. IntentService creates a Worker Thread

  2. IntentService creates a Work Queue which sends request to onHandleIntent() method one by one

  3. When there is no work then IntentService calls stopSelf() method
  4. Provides default implementation for onBind() method which is null
  5. Default implementation for onStartCommand() which sends Intent request to WorkQueue and eventually to onHandleIntent()

extract the date part from DateTime in C#

DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date

if you want to compare dates, ignoring the time part, make an use of DateTime.Year and DateTime.DayOfYear properties.

code snippet

DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
    Console.WriteLine("d1 < d2");
else
    if (d1.DayOfYear < d2.DayOfYear)
        Console.WriteLine("d1 < d2");

How to use wget in php?

This method is only one class and doesn't require importing other libraries or reusing code.

Personally I use this script that I made a while ago. Located here but for those who don't want to click on that link you can view it below. It lets the developer use the static method HTTP::GET($url, $options) to use the get method in curl while being able to pass through custom curl options. You can also use HTTP::POST($url, $options) but I hardly use that method.

/**
  *  echo HTTP::POST('http://accounts.kbcomp.co',
  *      array(
  *            'user_name'=>'[email protected]',
  *            'user_password'=>'demo1234'
  *      )
  *  );
  *  OR
  *  echo HTTP::GET('http://api.austinkregel.com/colors/E64B3B/1');
  *                  
  */

class HTTP{
   public static function GET($url,Array $options=array()){
    $ch = curl_init();
    if(count($options>0)){
       curl_setopt_array($ch, $options);
       curl_setopt($ch, CURLOPT_URL, $url);
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
     }
   }
   public static function POST($url, $postfields, $options = null){
       $ch = curl_init();
       $options = array(
          CURLOPT_URL=>$url,
          CURLOPT_RETURNTRANSFER => TRUE,
          CURLOPT_POSTFIELDS => $postfields,
          CURLOPT_HEADER => true
          //CURLOPT_HTTPHEADER, array('Content-Type:application/json')
          ); 
       if(count($options>0)){
           curl_setopt_array($ch, $options);
       }
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
   }
}

How to find the most recent file in a directory using .NET, and without looping?

how about something like this...

var directory = new DirectoryInfo("C:\\MyDirectory");
var myFile = (from f in directory.GetFiles()
             orderby f.LastWriteTime descending
             select f).First();

// or...
var myFile = directory.GetFiles()
             .OrderByDescending(f => f.LastWriteTime)
             .First();

How to export data with Oracle SQL Developer?

In version 3, they changed "export" to "unload". It still functions more or less the same.

python to arduino serial read & write

First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,

C:\Python34\Scripts  

Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd will pop up. Write the below code in that cmd window,

pip install PySerial

and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.


after successfully installed the module open python IDLE and write down the bellow code and run it.

import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using        
ser = serial.Serial("COM11", 9600)
while True:
    cc=str(ser.readline())
    print(cc[2:][:-5])   

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

List to array conversion to use ravel() function

I wanted a way to do this without using an extra module. First turn list to string, then append to an array:

dataset_list = ''.join(input_list)
dataset_array = []
for item in dataset_list.split(';'): # comma, or other
    dataset_array.append(item)

numpy max vs amax vs maximum

For completeness, in Numpy there are four maximum related functions. They fall into two different categories:

  • np.amax/np.max, np.nanmax: for single array order statistics
  • and np.maximum, np.fmax: for element-wise comparison of two arrays

I. For single array order statistics

NaNs propagator np.amax/np.max and its NaN ignorant counterpart np.nanmax.

  • np.max is just an alias of np.amax, so they are considered as one function.

    >>> np.max.__name__
    'amax'
    >>> np.max is np.amax
    True
    
  • np.max propagates NaNs while np.nanmax ignores NaNs.

    >>> np.max([np.nan, 3.14, -1])
    nan
    >>> np.nanmax([np.nan, 3.14, -1])
    3.14
    

II. For element-wise comparison of two arrays

NaNs propagator np.maximum and its NaNs ignorant counterpart np.fmax.

  • Both functions require two arrays as the first two positional args to compare with.

    # x1 and x2 must be the same shape or can be broadcast
    np.maximum(x1, x2, /, ...);
    np.fmax(x1, x2, /, ...)
    
  • np.maximum propagates NaNs while np.fmax ignores NaNs.

    >>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([ nan,  nan, 2.72])
    >>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([-inf, 3.14, 2.72])
    
  • The element-wise functions are np.ufunc(Universal Function), which means they have some special properties that normal Numpy function don't have.

    >>> type(np.maximum)
    <class 'numpy.ufunc'>
    >>> type(np.fmax)
    <class 'numpy.ufunc'>
    >>> #---------------#
    >>> type(np.max)
    <class 'function'>
    >>> type(np.nanmax)
    <class 'function'>
    

And finally, the same rules apply to the four minimum related functions:

  • np.amin/np.min, np.nanmin;
  • and np.minimum, np.fmin.

Proper use of errors

Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.

EvalError --- Creates an instance representing an error that occurs regarding the global function eval().

InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".

RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.

ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.

SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().

TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.

URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

Best way to remove items from a collection

To do this while looping through the collection and not to get the modifying a collection exception, this is the approach I've taken in the past (note the .ToList() at the end of the original collection, this creates another collection in memory, then you can modify the existing collection)

foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments.ToList())
{
    if (spAssignment.Member.Name == shortName)
    {
        workspace.RoleAssignments.Remove(spAssignment);
    }
}

Hexadecimal to Integer in Java

I finally find answers to my question based on all of your comments. Thanks, I tried this :

public Integer calculateHash(String uuid) {

    try {
        //....
        String hex = hexToString(output);
        //Integer i = Integer.valueOf(hex, 16).intValue();
        //Instead of using Integer, I used BigInteger and I returned the int value.
        BigInteger bi = new BigInteger(hex, 16);
        return bi.intValue();`
    } catch (NoSuchAlgorithmException e) {
        System.out.println("SHA1 not implemented in this system");
    }
    //....
}

This solution is not optimal but I can continue with my project. Thanks again for your help

Preferred way of loading resources in Java

Work out the solution according to what you want...

There are two things that getResource/getResourceAsStream() will get from the class it is called on...

  1. The class loader
  2. The starting location

So if you do

this.getClass().getResource("foo.txt");

it will attempt to load foo.txt from the same package as the "this" class and with the class loader of the "this" class. If you put a "/" in front then you are absolutely referencing the resource.

this.getClass().getResource("/x/y/z/foo.txt")

will load the resource from the class loader of "this" and from the x.y.z package (it will need to be in the same directory as classes in that package).

Thread.currentThread().getContextClassLoader().getResource(name)

will load with the context class loader but will not resolve the name according to any package (it must be absolutely referenced)

System.class.getResource(name)

Will load the resource with the system class loader (it would have to be absolutely referenced as well, as you won't be able to put anything into the java.lang package (the package of System).

Just take a look at the source. Also indicates that getResourceAsStream just calls "openStream" on the URL returned from getResource and returns that.

Set a button group's width to 100% and make buttons equal width?

There's no need for extra css the .btn-group-justified class does this.

You have to add this to the parent element and then wrap each btn element in a div with .btn-group like this

    <div class="form-group">

            <div class="btn-group btn-group-justified">
                <div class="btn-group">
                    <button type="submit" id="like" class="btn btn-lg btn-success ">Like</button>
                </div>
                <div class="btn-group">
                    <button type="submit" id="nope" class="btn btn-lg btn-danger ">Nope</button>
                </div>
            </div>

        </div>

#pragma pack effect

You'd likely only want to use this if you were coding to some hardware (e.g. a memory mapped device) which had strict requirements for register ordering and alignment.

However, this looks like a pretty blunt tool to achieve that end. A better approach would be to code a mini-driver in assembler and give it a C calling interface rather than fumbling around with this pragma.

How different is Scrum practice from Agile Practice?

Agile is commonly regarded as an umbrella term. Scrum/Kanban are executions of Agile guiding principles from a project management perspective, whereas eXtreme Programming (XP) focuses on the engineering practices e.g., Unit Testing, Continuous Integration, Pair Programming etc.

Typically: Agile = Scrum + XP

How to catch SQLServer timeout exceptions

When a client sends ABORT, no transactions are rolled back. To avoid this behavior we have to use SET_XACT_ABORT ON https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-ver15

ES6 Class Multiple inheritance

Well Object.assign gives you the possibility to do something close albeit a bit more like composition with ES6 classes.

class Animal {
    constructor(){ 
     Object.assign(this, new Shark()) 
     Object.assign(this, new Clock()) 
  }
}

class Shark {
  // only what's in constructor will be on the object, ence the weird this.bite = this.bite.
  constructor(){ this.color = "black"; this.bite = this.bite }
  bite(){ console.log("bite") }
  eat(){ console.log('eat') }
}

class Clock{
  constructor(){ this.tick = this.tick; }
  tick(){ console.log("tick"); }
}

let animal = new Animal();
animal.bite();
console.log(animal.color);
animal.tick();

I've not seen this used anywhere but it's actually quite useful. You can use function shark(){} instead of class but there are advantages of using class instead.

I believe the only thing different with inheritance with extend keyword is that the function don't live only on the prototype but also the object itself.

Thus now when you do new Shark() the shark created has a bite method, while only its prototype has a eat method

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

This issue arises because of different reasons. It might encountered if you are using Spring boot built war file. As Spring boot web and rest starter projects jars do have embedded Tomcat in it, hence fails with "SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException".

You can fix this by exclusion of the embedded tomcat at the time of packaging by using exclusions in case of maven.

Maven dependency of "spring-boot-starter-web" will look like

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

Best practice for using assert?

The only thing that's really wrong with this approach is that it's hard to make a very descriptive exception using assert statements. If you're looking for the simpler syntax, remember you can also do something like this:

class XLessThanZeroException(Exception):
    pass

def CheckX(x):
    if x < 0:
        raise XLessThanZeroException()

def foo(x):
    CheckX(x)
    #do stuff here

Another problem is that using assert for normal condition-checking is that it makes it difficult to disable the debugging asserts using the -O flag.

How do I use itertools.groupby()?

A neato trick with groupby is to run length encoding in one line:

[(c,len(list(cgen))) for c,cgen in groupby(some_string)]

will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.

Edit: Note that this is what separates itertools.groupby from the SQL GROUP BY semantics: itertools doesn't (and in general can't) sort the iterator in advance, so groups with the same "key" aren't merged.

PHP Pass variable to next page

Passing data in the request

You could either embed it as a hidden field in your form, or add it your forms action URL

 echo '<input type="hidden" name="myVariable" value="'.
     htmlentities($myVariable).'">';

or

echo '<form method="POST" action="Page2.php?myVariable='.
    urlencode($myVariable).'">";

Note this also illustrates the use of htmlentities and urlencode when passing data around.

Passing data in the session

If the data doesn't need to be passed to the client side, then sessions may be more appropriate. Simply call session_start() at the start of each page, and you can get and set data into the $_SESSION array.

Security

Since you state your value is actually a filename, you need to be aware of the security ramifications. If the filename has arrived from the client side, assume the user has tampered with the value. Check it for validity! What happens when the user passes the path to an important system file, or a file under their control? Can your script be used to "probe" the server for files that do or do not exist?

As you are clearly just getting started here, its worth reminding that this goes for any data which arrives in $_GET, $_POST or $_COOKIE - assume your worst enemy crafted the contents of those arrays, and code accordingly!

How To Raise Property Changed events on a Dependency Property?

I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example. In the code below, MyControl has two dependency properties - ActiveTabInt and ActiveTabString. When the user clicks the button on the host (MainWindow), ActiveTabString is modified. The PropertyChanged CALLBACK on the dependency property sets the value of ActiveTabInt. The PropertyChanged EVENT is not manually raised by MyControl.

MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ActiveTabString = "zero";
    }

    private string _ActiveTabString;
    public string ActiveTabString
    {
        get { return _ActiveTabString; }
        set
        {
            if (_ActiveTabString != value)
            {
                _ActiveTabString = value;
                RaisePropertyChanged("ActiveTabString");
            }
        }
    }

    private int _ActiveTabInt;
    public int ActiveTabInt
    {
        get { return _ActiveTabInt; }
        set
        {
            if (_ActiveTabInt != value)
            {
                _ActiveTabInt = value;
                RaisePropertyChanged("ActiveTabInt");
            }
        }
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
    }

}

public class MyControl : Control
{
    public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });


    public string ActiveTabString
    {
        get { return (string)GetValue(ActiveTabStringProperty); }
        set { SetValue(ActiveTabStringProperty, value); }
    }

    public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
        "ActiveTabString",
        typeof(string),
        typeof(MyControl), new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            ActiveTabStringChanged));


    public int ActiveTabInt
    {
        get { return (int)GetValue(ActiveTabIntProperty); }
        set { SetValue(ActiveTabIntProperty, value); }
    }
    public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
        "ActiveTabInt",
        typeof(Int32),
        typeof(MyControl), new FrameworkPropertyMetadata(
            new Int32(),
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));

    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }


    private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MyControl thiscontrol = sender as MyControl;

        if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
            thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());

    }
}

MainWindow.xaml

    <StackPanel Orientation="Vertical">
    <Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
    <local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>

App.xaml

<Style TargetType="local:MyControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MyControl">
                    <TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
                        <TabItem Header="Tab Zero">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                        <TabItem Header="Tab One">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                    </TabControl>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>