Programs & Examples On #Treemodel

How to make inline functions in C#

The answer to your question is yes and no, depending on what you mean by "inline function". If you're using the term like it's used in C++ development then the answer is no, you can't do that - even a lambda expression is a function call. While it's true that you can define inline lambda expressions to replace function declarations in C#, the compiler still ends up creating an anonymous function.

Here's some really simple code I used to test this (VS2015):

    static void Main(string[] args)
    {
        Func<int, int> incr = a => a + 1;
        Console.WriteLine($"P1 = {incr(5)}");
    }

What does the compiler generate? I used a nifty tool called ILSpy that shows the actual IL assembly generated. Have a look (I've omitted a lot of class setup stuff)

This is the Main function:

        IL_001f: stloc.0
        IL_0020: ldstr "P1 = {0}"
        IL_0025: ldloc.0
        IL_0026: ldc.i4.5
        IL_0027: callvirt instance !1 class [mscorlib]System.Func`2<int32, int32>::Invoke(!0)
        IL_002c: box [mscorlib]System.Int32
        IL_0031: call string [mscorlib]System.String::Format(string, object)
        IL_0036: call void [mscorlib]System.Console::WriteLine(string)
        IL_003b: ret

See those lines IL_0026 and IL_0027? Those two instructions load the number 5 and call a function. Then IL_0031 and IL_0036 format and print the result.

And here's the function called:

        .method assembly hidebysig 
            instance int32 '<Main>b__0_0' (
                int32 a
            ) cil managed 
        {
            // Method begins at RVA 0x20ac
            // Code size 4 (0x4)
            .maxstack 8

            IL_0000: ldarg.1
            IL_0001: ldc.i4.1
            IL_0002: add
            IL_0003: ret
        } // end of method '<>c'::'<Main>b__0_0'

It's a really short function, but it is a function.

Is this worth any effort to optimize? Nah. Maybe if you're calling it thousands of times a second, but if performance is that important then you should consider calling native code written in C/C++ to do the work.

In my experience readability and maintainability are almost always more important than optimizing for a few microseconds gain in speed. Use functions to make your code readable and to control variable scoping and don't worry about performance.

"Premature optimization is the root of all evil (or at least most of it) in programming." -- Donald Knuth

"A program that doesn't run correctly doesn't need to run fast" -- Me

How to change the URI (URL) for a remote Git repository?

You can

git remote set-url origin new.git.url/here

(see git help remote) or you can edit .git/config and change the URLs there. You're not in any danger of losing history unless you do something very silly (and if you're worried, just make a copy of your repo, since your repo is your history.)

Edit a commit message in SourceTree Windows (already pushed to remote)

If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)

So I have to use the following method.

CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.

Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.

Step2:

[Situation A]: target commit is the latest one.

1) In the git command console, input

git commit --amend -m "new comment message"

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force

[Situation B]: target commit is not the latest one.

1) In the git command console, input

git rebase -i HEAD~n

It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2. This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq to save&quit.

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force


Finally: In the sourcetree main window, Press F5 to refresh.

How to avoid "Permission denied" when using pip with virtualenv

You did not activate the virtual environment before using pip.

Try it with:

$(your venv path) . bin/activate

And then use pip -r requirements.txt on your main folder

Nullable DateTime conversion

You might want to do it like this:

DateTime? lastPostDate =  (DateTime?)(reader.IsDbNull(3) ? null : reader[3]); 

The problem you are having is that the ternary operator wants a viable cast between the left and right sides. And null can't be cast to DateTime.

Note the above works because both sides of the ternary are object's. The object is explicitly cast to DateTime? which works: as long as reader[3] is in fact a date.

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

open /Users/you/eclipse/java-oxygen right click on eclipse, click on show package content

Then go to Contents/Eclipse and select file eclipse.ini, open in text file or in any editor.

search deleted java path and add newer java path till bin /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

findByInventoryIdIn(List<Long> inventoryIdList) should do the trick.

The HTTP request parameter format would be like so:

Yes ?id=1,2,3
No  ?id=1&id=2&id=3

The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn and IsNotIn.

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

Float to String format specifier

You can pass a format string to the ToString method, like so:

ToString("N4"); // 4 decimal points Number

If you want to see more modifiers, take a look at MSDN - Standard Numeric Format Strings

How / can I display a console window in Intellij IDEA?

IntelliJ IDEA 14 & 15 & 2017:

View > Tool Windows > Terminal

or

Alt + F12

enter image description here enter image description here

How to remove focus without setting focus to another control?

You do not need to clear focus, just add this code where you want to focus

 time_statusTV.setFocusable(true);
 time_statusTV.requestFocus();
 InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
 imm.showSoftInput( time_statusTV, 0);

What is a blob URL and why it is used?

I have modified working solution to handle both the case.. when video is uploaded and when image is uploaded .. hope it will help some.

HTML

<input type="file" id="fileInput">
<div> duration: <span id='sp'></span><div>

Javascript

var fileEl = document.querySelector("input");

fileEl.onchange = function(e) {


    var file = e.target.files[0]; // selected file

    if (!file) {
        console.log("nothing here");
        return;
    }

    console.log(file);
    console.log('file.size-' + file.size);
    console.log('file.type-' + file.type);
    console.log('file.acutalName-' + file.name);

    let start = performance.now();

    var mime = file.type, // store mime for later
        rd = new FileReader(); // create a FileReader

    if (/video/.test(mime)) {

        rd.onload = function(e) { // when file has read:


            var blob = new Blob([e.target.result], {
                    type: mime
                }), // create a blob of buffer
                url = (URL || webkitURL).createObjectURL(blob), // create o-URL of blob
                video = document.createElement("video"); // create video element
            //console.log(blob);
            video.preload = "metadata"; // preload setting

            video.addEventListener("loadedmetadata", function() { // when enough data loads
                console.log('video.duration-' + video.duration);
                console.log('video.videoHeight-' + video.videoHeight);
                console.log('video.videoWidth-' + video.videoWidth);
                //document.querySelector("div")
                //  .innerHTML = "Duration: " + video.duration + "s" + " <br>Height: " + video.videoHeight; // show duration
                (URL || webkitURL).revokeObjectURL(url); // clean up

                console.log(start - performance.now());
                // ... continue from here ...

            });
            video.src = url; // start video load
        };
    } else if (/image/.test(mime)) {
        rd.onload = function(e) {

            var blob = new Blob([e.target.result], {
                    type: mime
                }),
                url = URL.createObjectURL(blob),
                img = new Image();

            img.onload = function() {
                console.log('iamge');
                console.dir('this.height-' + this.height);
                console.dir('this.width-' + this.width);
                URL.revokeObjectURL(this.src); // clean-up memory
                console.log(start - performance.now()); // add image to DOM
            }

            img.src = url;

        };
    }

    var chunk = file.slice(0, 1024 * 1024 * 10); // .5MB
    rd.readAsArrayBuffer(chunk); // read file object

};

jsFiddle Url

https://jsfiddle.net/PratapDessai/0sp3b159/

Overriding css style?

Instead of override you can add another class to the element and then you have an extra abilities. for example:

HTML

<div class="style1 style2"></div>

CSS

//only style for the first stylesheet
.style1 {
   width: 100%;      
}
//only style for second stylesheet
.style2 {
   width: 50%;     
}
//override all
.style1.style2 { 
   width: 70%;
}

Is there any way to show a countdown on the lockscreen of iphone?

Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)

Limit results in jQuery UI Autocomplete

I've tried all the solutions above, but mine only worked on this way:

success: function (data) {
    response($.map(data.slice (0,10), function(item) {
    return {
    value: item.nome
    };
    }));
},

How to get Enum Value from index in Java?

I just tried the same and came up with following solution:

public enum Countries {
    TEXAS,
    FLORIDA,
    OKLAHOMA,
    KENTUCKY;

    private static Countries[] list = Countries.values();

    public static Countries getCountry(int i) {
        return list[i];
    }

    public static int listGetLastIndex() {
        return list.length - 1;
    }
}

The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:

public static String getCountry(int i) {
    return list[(i - 1)];
}

public static int listGetLastIndex() {
    return list.length;
}

Inside my Main I get the needed countries-object with

public static void main(String[] args) {
   int i = Countries.listGetLastIndex();
   Countries currCountry = Countries.getCountry(i);
}

which sets currCountry to the last country, in this case Countries.KENTUCKY.

Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.

How to list all tags along with the full message in git?

I prefer doing this on the command line, but if you don't mind a web interface and you use GitHub, you can visit https://github.com/user/repo/tags and click on the "..." next to each tag to display its annotation.

How to create an HTML button that acts like a link?

Use:

<a href="http://www.stackoverflow.com/">
    <button>Click me</button>
</a>

Unfortunately, this markup is no longer valid in HTML5 and will neither validate nor always work as potentially expected. Use another approach.

SQL Row_Number() function in Where Clause

Using CTE (SQL Server 2005+):

WITH employee_rows AS (
  SELECT t.employee_id,
         ROW_NUMBER() OVER ( ORDER BY t.employee_id ) 'rownum'
    FROM V_EMPLOYEE t)
SELECT er.employee_id
  FROM employee_rows er
 WHERE er.rownum > 1

Using Inline view/Non-CTE Equivalent Alternative:

SELECT er.employee_id
  FROM (SELECT t.employee_id,
               ROW_NUMBER() OVER ( ORDER BY t.employee_id ) 'rownum'
          FROM V_EMPLOYEE t) er
 WHERE er.rownum > 1

Converting String To Float in C#

First, it is just a presentation of the float number you see in the debugger. The real value is approximately exact (as much as it's possible).

Note: Use always CultureInfo information when dealing with floating point numbers versus strings.

float.Parse("41.00027357629127",
      System.Globalization.CultureInfo.InvariantCulture);

This is just an example; choose an appropriate culture for your case.

Android button background color

In addition to Mark Proctor's answer:

If you want to keep the default styling, but have a conditional coloring on the button, just set the backgroundTint property like so:

android:backgroundTint="@drawable/styles_mybutton"

Create the associated file /res/drawable/styles_mybutton.xml, then use the following template and change the colors as per your tastes:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Disabled state-->
    <item android:state_enabled="false"
        android:color="@android:color/white">
    </item>
    <!-- Default state-->
    <item
        android:color="#cfc">
    </item>
</selector>

How to allow download of .json file with ASP.NET

Add the JSON MIME type to IIS 6. Follow the directions at MSDN's Configure MIME Types (IIS 6.0).

  • Extension: .json
  • MIME type: application/json

Don't forget to restart IIS after the change.

UPDATE: There are easy ways to do this on IIS7 and newer. The op specifically asked for IIS6 help so I'm leaving this answer as-is. But this answer is still getting a lot of traffic even though IIS6 is very old now. Hopefully you're using something newer, so I wanted to mention that if you have a newer IIS7 or newer version see @ProVega's answer below for a simpler solution for those newer versions.

Getting one value from a tuple

For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.

# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)

# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)

# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]

# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]

# or this
v1, v2 = my_tuple_fun()

Hope this clears things up further for those that need it.

Android TextView Text not getting wrapped

I added a \n in the middle of my string and it looked okay.

How to set transparent background for Image Button in code?

This should work - imageButton.setBackgroundColor(android.R.color.transparent);

How do I use .toLocaleTimeString() without displaying seconds?

I've also been looking for solution to this problem, here's what I eventually came up with:

function getTimeStr() {
    var dt = new Date();
    var d = dt.toLocaleDateString();
    var t = dt.toLocaleTimeString();
    t = t.replace(/\u200E/g, '');
    t = t.replace(/^([^\d]*\d{1,2}:\d{1,2}):\d{1,2}([^\d]*)$/, '$1$2');
    var result = d + ' ' + t;
    return result;
}

You can try it here: http://jsfiddle.net/B5Zrx/

\u200E is some formatting character that I've seen on some IE version (it's unicode left-to-right mark).

I assume that if the formatted time contains something like "XX:XX:XX" then it must be time with seconds and I remove the last part, if I don't find this pattern, nothing is changed. Pretty safe, but there is a risk of leaving seconds in some weird circumstances.

I just hope that there is no locale that would change the order of formatted time parts (e.g. make it ss:mm:hh). This left-to-right mark is making me a bit nervous about that though, that is why I don't remove the right-to-left mark (\u202E) - I prefer to not find a match in this case and leave the time formatted with seconds in such case.

Getting the last argument passed to a shell script

If you are using Bash >= 3.0

echo ${BASH_ARGV[0]}

Scala vs. Groovy vs. Clojure

I never had time to play with clojure. But for scala vs groovy, this is words from James Strachan - Groovy creator

"Though my tip though for the long term replacement of javac is Scala. I'm very impressed with it! I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy."

You can read the whole story here

Visual Studio Code cannot detect installed git

  1. Make sure git is enabled (File --> Preferences --> Git Enabled) as other have mentioned.
  2. Make sure Gits installed and in the PATH (with the correct location, by default: C:\Program Files\Git\cmd) - PATH on system variables btw
  3. Change default terminal, Powershell can be a bit funny, I recommend Git BASH but cmd is fine, this can be done by selecting the terminal dropdown and selecting 'set default shell' then creating a new terminal with the + button.
  4. Restarting VS Code, sometimes Reboot if that fails.

Hope that helped, and last but not least, it's 'git' not 'Git'/'gat'. :)

Query to list number of records in each table in a database

This approaches uses string concatenation to produce a statement with all tables and their counts dynamically, like the example(s) given in the original question:

          SELECT COUNT(*) AS Count,'[dbo].[tbl1]' AS TableName FROM [dbo].[tbl1]
UNION ALL SELECT COUNT(*) AS Count,'[dbo].[tbl2]' AS TableName FROM [dbo].[tbl2]
UNION ALL SELECT...

Finally this is executed with EXEC:

DECLARE @cmd VARCHAR(MAX)=STUFF(
                    (
                        SELECT 'UNION ALL SELECT COUNT(*) AS Count,''' 
                              + QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME) 
                              + ''' AS TableName FROM ' + QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)
                        FROM INFORMATION_SCHEMA.TABLES AS t
                        WHERE TABLE_TYPE='BASE TABLE'
                        FOR XML PATH('')
                    ),1,10,'');
EXEC(@cmd);

Two HTML tables side by side, centered on the page

Off the top of my head, you might try using the "margin: 0 auto" for #outer rather than #inner.

I often add background-color to my DIVs to see how they're laying out on the view. That might be a good way to diagnose what's going onn here.

Converting BitmapImage to Bitmap and vice versa

Here the async version.

public static Task<BitmapSource> ToBitmapSourceAsync(this Bitmap bitmap)
{
    return Task.Run(() =>
    {
        using (System.IO.MemoryStream memory = new System.IO.MemoryStream())
        {
            bitmap.Save(memory, ImageFormat.Png);
            memory.Position = 0;
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
            bitmapImage.Freeze();
            return bitmapImage as BitmapSource;
        }
    });

}

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Try this (edited):

ctx.Database.ExecuteSqlCommand(sql, new SqlParameter("FirstName", firstName), 
                                    new SqlParameter("Id", id));

Previous idea was wrong.

Remove title in Toolbar in appcompat-v7

Just add this attribute to your toolbar

app:title=" "

Simple mediaplayer play mp3 from file path?

Here is the code to set up a MediaPlayer to play off of the SD card:

String PATH_TO_FILE = "/sdcard/music.mp3";    
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();   
mediaPlayer.start()

You can see the full example here. Let me know if you have any problems.

ReadFile in Base64 Nodejs

Latest and greatest way to do this:

Node supports file and buffer operations with the base64 encoding:

const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});

Or using the new promises API:

const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});

Unstaged changes left after git reset --hard

None of these methods worked for me, the only solution was to nuke the whole repo and re-clone it. This includes stashing, resetting, adding then resetting, clrf settings, case sensitivity etc. Sigh..

How do I get indices of N maximum values in a NumPy array?

Newer NumPy versions (1.8 and up) have a function called argpartition for this. To get the indices of the four largest elements, do

>>> a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> a
array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> ind = np.argpartition(a, -4)[-4:]
>>> ind
array([1, 5, 8, 0])
>>> a[ind]
array([4, 9, 6, 9])

Unlike argsort, this function runs in linear time in the worst case, but the returned indices are not sorted, as can be seen from the result of evaluating a[ind]. If you need that too, sort them afterwards:

>>> ind[np.argsort(a[ind])]
array([1, 8, 5, 0])

To get the top-k elements in sorted order in this way takes O(n + k log k) time.

Objective-C ARC: strong vs retain and weak vs assign

To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.

 -(void)displayLocalVariable
  {
     NSString myName = @"ABC";
     NSLog(@"My name is = %@", myName);
  }

In above method scope of myName variable is limited to displayLocalVariable method, once the method gets finished myName variable which is holding the string "ABC" will get deallocated from the memory.

Now what if we want to hold the myName variable value throughout our view controller life cycle. For this we can create the property named as username which will have Strong reference to the variable myName(see self.username = myName; in below code), as below,

@interface LoginViewController ()

@property(nonatomic,strong) NSString* username;
@property(nonatomic,weak) NSString* dummyName;

- (void)displayLocalVariable;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated
{
     [self displayLocalVariable];
}

- (void)displayLocalVariable
{
   NSString myName = @"ABC";
   NSLog(@"My name is = %@", myName);
   self.username = myName;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end

Now in above code you can see myName has been assigned to self.username and self.username is having a strong reference(as we declared in interface using @property) to myName(indirectly it's having Strong reference to "ABC" string). Hence String myName will not get deallocated from memory till self.username is alive.

  • Weak reference

Now consider assigning myName to dummyName which is a Weak reference, self.dummyName = myName; Unlike Strong reference Weak will hold the myName only till there is Strong reference to myName. See below code to understand Weak reference,

-(void)displayLocalVariable
  {
     NSString myName = @"ABC";
     NSLog(@"My name is = %@", myName);
     self.dummyName = myName;
  }

In above code there is Weak reference to myName(i.e. self.dummyName is having Weak reference to myName) but there is no Strong reference to myName, hence self.dummyName will not be able to hold the myName value.

Now again consider the below code,

-(void)displayLocalVariable
      {
         NSString myName = @"ABC";
         NSLog(@"My name is = %@", myName);
         self.username = myName;
         self.dummyName = myName;
      } 

In above code self.username has a Strong reference to myName, hence self.dummyName will now have a value of myName even after method ends since myName has a Strong reference associated with it.

Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated retain count reaches to 0.

Hope this helps.

How to play CSS3 transitions in a loop?

CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

You need to define the animation keyframes and apply it to the element:

@keyframes changewidth {
  from {
    width: 100px;
  }

  to {
    width: 300px;
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.

Can I force a UITableView to hide the separator between empty cells?

I use the following:

UIView *view = [[UIView alloc] init];
myTableView.tableFooterView = view;
[view release];

Doing it in viewDidLoad. But you can set it anywhere.

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

Tomcat Servlet: Error 404 - The requested resource is not available

this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.

Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output

phpinfo() - is there an easy way for seeing it?

From the CLI the best way is to use grep like:

php -i | grep libxml

PHP read and write JSON from file

The sample for reading and writing JSON in PHP:

$json = json_decode(file_get_contents($file),TRUE);

$json[$user] = array("first" => $first, "last" => $last);

file_put_contents($file, json_encode($json));

How to append elements into a dictionary in Swift?

In Swift, if you are using NSDictionary, you can use setValue:

dict.setValue("value", forKey: "key")

How to update /etc/hosts file in Docker image during "docker build"

Following worked for me by mounting the file during docker run instead of docker build

docker service create --name <name>  --mount type=bind,source=/etc/hosts,dst=/etc/hosts   <image>

PSQLException: current transaction is aborted, commands ignored until end of transaction block

Check the output before the statement that caused current transaction is aborted. This typically means that database threw an exception that your code had ignored and now expecting next queries to return some data.

So you now have a state mismatch between your application, which considers things are fine, and database, that requires you to rollback and re-start your transaction from the beginning.

You should catch all exceptions and rollback transactions in such cases.

Here's a similar issue.

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

On my execution of openssl pkcs12 -export -out cacert.pkcs12 -in testca/cacert.pem, I received the following message:

unable to load private key 140707250050712:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: ANY PRIVATE KEY`

Got this solved by providing the key file along with the command. The switch is -inkey inkeyfile.pem

Convert java.util.Date to String

Why don't you use Joda (org.joda.time.DateTime)? It's basically a one-liner.

Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");

// output: 2014-11-14 14:05:09

Cannot open Windows.h in Microsoft Visual Studio

If you already haven't done it, try adding "SDK Path\Include" to:

Project ? Preferences ? C/C++ ? General ? Additional Include Directories

And add "SDK Path\Lib" to:

Project ? Preferences ? Linker ? General ? Additional Library Directories

Also, try to change "Windows.h" to <windows.h>

If won't help, check the physical existence of the file, it should be in "\VC\PlatformSDK\Include" folder in your Visual Studio install directory.

CSS / HTML Navigation and Logo on same line

You need to apply the logo class to the image...then float the ul

Codepen Demo

HTML

<img class="logo" src="http://i.imgur.com/hCrQkJi.png">

CSS

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  float: left;
  background: white;
}

Get the latest record from mongodb collection

This is how to get the last record from all MongoDB documents from the "foo" collection.(change foo,x,y.. etc.)

db.foo.aggregate([{$sort:{ x : 1, date : 1 } },{$group: { _id: "$x" ,y: {$last:"$y"},yz: {$last:"$yz"},date: { $last : "$date" }}} ],{   allowDiskUse:true  })

you can add or remove from the group

help articles: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group

https://docs.mongodb.com/manual/reference/operator/aggregation/last/

Iterating each character in a string using Python

If you ever run in a situation where you need to get the next char of the word using __next__(), remember to create a string_iterator and iterate over it and not the original string (it does not have the __next__() method)

In this example, when I find a char = [ I keep looking into the next word while I don't find ], so I need to use __next__

here a for loop over the string wouldn't help

myString = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myString.__iter__()
for idx, char in enumerate(word_iterator):
    if char == "'":
        continue

    processedInput+=char

    if char == '[':
        next_char=word_iterator.__next__()
        while(next_char != "]"):
          processedInput+=next_char
          next_char=word_iterator.__next__()
        else:
          processedInput+=next_char

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

sudo /usr/local/mysql/support-files/mysql.server start 

This worked for me. However, if this doesnt work then make sure that mysqld is running and try connecting.

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

if you want to redirect it to some other url lets google.com then make your like as happy to help other says rikin <a href="//google.com">happy to help other says rikin</a> this will remove self site url form the href.

Reload an iframe with jQuery

Just reciprocating Alex's answer but with jQuery

var currSrc = $("#currentElement").attr("src");
$("#currentElement").attr("src", currSrc);

How to build PDF file from binary string returned from a web-service using javascript

I saw another question on just this topic recently (streaming pdf into iframe using dataurl only works in chrome).

I've constructed pdfs in the ast and streamed them to the browser. I was creating them first with fdf, then with a pdf class I wrote myself - in each case the pdf was created from data retrieved from a COM object based on a couple of of GET params passed in via the url.

From looking at your data sent recieved in the ajax call, it looks like you're nearly there. I haven't played with the code for a couple of years now and didn't document it as well as I'd have cared to, but - I think all you need to do is set the target of an iframe to be the url you get the pdf from. Though this may not work - the file that oututs the pdf may also have to outut a html response header first.

In a nutshell, this is the output code I used:

//We send to a browser
header('Content-Type: application/pdf');
if(headers_sent())
    $this->Error('Some data has already been output, can\'t send PDF file');
header('Content-Length: '.strlen($this->buffer));
header('Content-Disposition: inline; filename="'.$name.'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
echo $this->buffer;

So, without seeing the full response text fro the ajax call I can't really be certain what it is, though I'm inclined to think that the code that outputs the pdf you're requesting may only be doig the equivalent of the last line in the above code. If it's code you have control over, I'd try setting the headers - then this way the browser can just deal with the response text - you don't have to bother doing a thing to it.

I simply constructed a url for the pdf I wanted (a timetable) then created a string that represented the html for an iframe of the desired sie, id etc that used the constructed url as it's src. As soon as I set the inner html of a div to the constructed html string, the browser asked for the pdf and then displayed it when it was received.

function  showPdfTt(studentId)
{
    var url, tgt;
    title = byId("popupTitle");
    title.innerHTML = "Timetable for " + studentId;
    tgt = byId("popupContent");
    url = "pdftimetable.php?";
    url += "id="+studentId;
    url += "&type=Student";
    tgt.innerHTML = "<iframe onload=\"centerElem(byId('box'))\" src='"+url+"' width=\"700px\" height=\"500px\"></iframe>";
}

EDIT: forgot to mention - you can send binary pdf's in this manner. The streams they contain don't need to be ascii85 or hex encoded. I used flate on all the streams in the pdf and it worked fine.

Handling Enter Key in Vue.js

This event works to me:

@keyup.enter.native="onEnter".

Best way to convert text files between character sets?

to write properties file (Java) normally I use this in linux (mint and ubuntu distributions):

$ native2ascii filename.properties

For example:

$ cat test.properties 
first=Execução número um
second=Execução número dois

$ native2ascii test.properties 
first=Execu\u00e7\u00e3o n\u00famero um
second=Execu\u00e7\u00e3o n\u00famero dois

PS: I writed Execution number one/two in portugues to force special characters.

In my case, in first execution I received this message:

$ native2ascii teste.txt 
The program 'native2ascii' can be found in the following packages:
 * gcj-5-jdk
 * openjdk-8-jdk-headless
 * gcj-4.8-jdk
 * gcj-4.9-jdk
Try: sudo apt install <selected package>

When I installed the first option (gcj-5-jdk) the problem was finished.

I hope this help someone.

Wampserver icon not going green fully, mysql services not starting up?

I had the same issue, to resolve it I added the following line to my.ini

innodb_force_recovery = 1

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

Overflow Scroll css is not working in the div

If you add height in .wrapper class then your scroll is working, without height scroll is not working.

Try this http://jsfiddle.net/ZcrFr/3/

CSS:

.wrapper {
  position: relative;
  overflow: scroll;
  width: 1000px;
  height: 800px;
}

Generate UML Class Diagram from Java Project

How about the Omondo Plugin for Eclipse. I have used it and I find it to be quite useful. Although if you are generating diagrams for large sources, you might have to start Eclipse with more memory.

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.

Verifying a specific parameter with Moq

I believe that the problem in the fact that Moq will check for equality. And, since XmlElement does not override Equals, it's implementation will check for reference equality.

Can't you use a custom object, so you can override equals?

Get top most UIViewController

Where did you put the code in?

I try your code in my demo, I found out, if you put the code in

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

will fail, because key window have been setting yet.

But I put your code in some view controller's

override func viewDidLoad() {

It just works.

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

With that level of accuracy, it would be better to reason in CPU tick rather than in system call like clock(). And do not forget that if it takes more than one nanosecond to execute an instruction... having a nanosecond accuracy is pretty much impossible.

Still, something like that is a start:

Here's the actual code to retrieve number of 80x86 CPU clock ticks passed since the CPU was last started. It will work on Pentium and above (386/486 not supported). This code is actually MS Visual C++ specific, but can be probably very easy ported to whatever else, as long as it supports inline assembly.

inline __int64 GetCpuClocks()
{

    // Counter
    struct { int32 low, high; } counter;

    // Use RDTSC instruction to get clocks count
    __asm push EAX
    __asm push EDX
    __asm __emit 0fh __asm __emit 031h // RDTSC
    __asm mov counter.low, EAX
    __asm mov counter.high, EDX
    __asm pop EDX
    __asm pop EAX

    // Return result
    return *(__int64 *)(&counter);

}

This function has also the advantage of being extremely fast - it usually takes no more than 50 cpu cycles to execute.

Using the Timing Figures:
If you need to translate the clock counts into true elapsed time, divide the results by your chip's clock speed. Remember that the "rated" GHz is likely to be slightly different from the actual speed of your chip. To check your chip's true speed, you can use several very good utilities or the Win32 call, QueryPerformanceFrequency().

How to write a simple Html.DropDownListFor()?

<%: 
     Html.DropDownListFor(
           model => model.Color, 
           new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Red"  },
                       new { value = 1 , text = "Blue" },
                       new { value = 2 , text = "Green"}
                    },
                  "value",
                  "text",
                   Model.Color
           )
        )
%>

or you can write no classes, put something like this directly to the view.

Disabling buttons on react native

TouchableOpacity extents TouchableWithoutFeedback, so you can just use the disabled property :

<TouchableOpacity disabled={true}>
  <Text>I'm disabled</Text>
</TouchableOpacity>

React Native TouchableWithoutFeedback #disabled documentation

The new Pressable API has a disabled option too :

<Pressable disable={true}>
  {({ pressed }) => (
    <Text>I'm disabled</Text>
  )}
</Pressable>

What are access specifiers? Should I inherit with private, protected or public?

The explanation from Scott Meyers in Effective C++ might help understand when to use them:

Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.

Running AngularJS initialization code when view is loaded

Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:

function MyCtrl($scope) {
    $scope.isSaving = false;

    (function() {  // init
        if (true) { // $routeParams.Id) {
            //get an existing object
        } else {
            //create a new object
        }
    })()

    $scope.isClean = function () {
       return $scope.hasChanges() && !$scope.isSaving;
    }

    $scope.hasChanges = function() { return false }
}

How to list all `env` properties within jenkins pipeline job?

Here's a quick script you can add as a pipeline job to list all environment variables:

node {
    echo(env.getEnvironment().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
    echo(System.getenv().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
}

This will list both system and Jenkins variables.

Why would you use String.Equals over ==?

There's a writeup on this article which you might find to be interesting, with some quotes from Jon Skeet. It seems like the use is pretty much the same.

Jon Skeet states that the performance of instance Equals "is slightly better when the strings are short—as the strings increase in length, that difference becomes completely insignificant."

How to show all of columns name on pandas dataframe?

Not a conventional answer, but I guess you could transpose the dataframe to look at the rows instead of the columns. I use this because I find looking at rows more 'intuitional' than looking at columns:

data_all2.T

This should let you view all the rows. This action is not permanent, it just lets you view the transposed version of the dataframe.

If the rows are still truncated, just use print(data_all2.T) to view everything.

Mercurial undo last commit

I believe the more modern and simpler way to do this now is hg uncommit. Note this leaves behind an empty commit which can be useful if you want to reuse the commit message later. If you don't, use hg uncommit --no-keep to not leave the empty commit.

hg uncommit [OPTION]... [FILE]...

uncommit part or all of a local changeset

This command undoes the effect of a local commit, returning the affected
files to their uncommitted state. This means that files modified or
deleted in the changeset will be left unchanged, and so will remain
modified in the working directory.

If no files are specified, the commit will be left empty, unless --no-keep

Sorry, I am not sure what the equivalent is TortoiseHg.

In Javascript, how to conditionally add a member to an object?

If you wish to do this server side (without jquery), you can use lodash 4.3.0:

a = _.pickBy({ b: (someCondition? 5 : undefined) }, _.negate(_.isUndefined));

And this works using lodash 3.10.1

a = _.pick({ b: (someCondition? 5 : undefined) }, _.negate(_.isUndefined));

Get Number of Rows returned by ResultSet in Java

You could load the ResultSet into a TableModel, then create a JTable that uses that TableModel, and then use the table.getRowCount() method. If you are going to display the result of the query, you have to do it anyway.

ResultSet resultSet;
resultSet = doQuery(something, somethingelse);
KiransTableModel myTableModel = new KiransTableModel(resultSet);
JTable table = new JTable(KiransTableModel);
int rowCount;
rowCount = table.getRowCount;

Removing a list of characters in string

If you are using python3 and looking for the translate solution - the function was changed and now takes 1 parameter instead of 2.

That parameter is a table (can be dictionary) where each key is the Unicode ordinal (int) of the character to find and the value is the replacement (can be either a Unicode ordinal or a string to map the key to).

Here is a usage example:

>>> list = [',', '!', '.', ';']
>>> s = "This is, my! str,ing."
>>> s.translate({ord(x): '' for x in list})
'This is my string'

How to connect to local instance of SQL Server 2008 Express

For me it was a windows firewall issue. Allow incoming connections. Opening port didn't work but allow programs did.

Link

Link2

iPhone UITextField - Change placeholder text color

I needed to keep the placeholder alignment so adam's answer was not enough for me.

To solve this I used a small variation that I hope will help some of you too:

- (void) drawPlaceholderInRect:(CGRect)rect {
    //search field placeholder color
    UIColor* color = [UIColor whiteColor];

    [color setFill];
    [self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}

Replace transparency in PNG images with white background

I saw this question and answers which really help me but then I was needed to do it for a lot of files, So in case you have multiple images (PNG images) in one folder and you want to do it for all:

find ./ -name "*.png" -exec convert {} -flatten {} \;

How to draw border on just one side of a linear layout?

To get a border on just one side of a drawable, apply a negative inset to the other 3 sides (causing those borders to be drawn off-screen).

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetTop="-2dp" 
    android:insetBottom="-2dp"
    android:insetLeft="-2dp">

    <shape android:shape="rectangle">
        <stroke android:width="2dp" android:color="#FF0000" />
        <solid android:color="#000000" />
    </shape>

</inset>

enter image description here

This approach is similar to naykah's answer, but without the use of a layer-list.

How to run function of parent window when child window closes?

Check following link. This would be helpful too..

In Parent Window:

function OpenChildAsPopup() {
        var childWindow = window.open("ChildWindow.aspx", "_blank",
        "width=200px,height=350px,left=200,top=100");
        childWindow.focus();
 }

function ChangeBackgroudColor() {
        var para = document.getElementById('samplePara');
        if (para !="undefied") {
            para.style.backgroundColor = '#6CDBF5';
        }
 }

Parent Window HTML Markup:

<div>
  <p id="samplePara" style="width: 350px;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  </p><br />
 <asp:Button ID="Button1" Text="Open Child Window" 
         runat="server" OnClientClick="OpenChildAsPopup();"/>
</div>

In Child Window:

// This will be called when the child window is closed.     
  window.onunload = function (e) {
        opener.ChangeBackgroudColor();
        //or you can do
        //var para = opener.document.getElementById('samplePara');
        //if (para != "undefied") {
        //    para.style.backgroundColor = '#6CDBF5';
        //}
    };

Div width 100% minus fixed amount of pixels

New way I've just stumbled upon: css calc():

.calculated-width {
    width: -webkit-calc(100% - 100px);
    width:    -moz-calc(100% - 100px);
    width:         calc(100% - 100px);
}?

Source: css width 100% minus 100px

Spring Boot @Value Properties

I had the similar issue and the above examples doesn't help me to read properties. I have posted the complete class which will help you to read properties values from application.properties file in SpringBoot application in the below link.

Spring Boot - Environment @Autowired throws NullPointerException

What's the difference between @Component, @Repository & @Service annotations in Spring?

Good enough answers are here to explain the whats-the-difference-between-component-repository-service-annotations. I would like to share the difference between @Controller & @RestController

@Controller vs RestController

@RestController:

enter image description here

  • This annotation is a specialized version of @Controller which adds @Controller and @ResponseBody annotation automatically. so we do not have to add @ResponseBody to our mapping methods. That means @ResponseBody is default active.
  • If you use @RestController you cannot return a view (By using Viewresolver in Spring/Spring-Boot)
  • @RestController also converts the response to JSON/XML automatically as @ResponseBody makes the returned objects to something that could be in the body, e.g. JSON or XML

@Controller

enter image description here

  • @Controller is used to mark classes as Spring MVC Controller. This annotation is just a specialized version of @Component and it allows the controller classes to be auto-detected based on classpath scanning.
  • @Controller you can return a view in Spring web MVC.

More Detailed View

How can I see if a Perl hash already has a certain key?

I believe to check if a key exists in a hash you just do

if (exists $strings{$string}) {
    ...
} else {
    ...
}

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

You can remove "JavaAppletPlugin.plugin" found in Spotlight or Finder, then re-install downloaded Java 8.

This will simply solve your problem.

Do you need to dispose of objects and set them to null?

I agree with the common answer here that yes you should dispose and no you generally shouldn't set the variable to null... but I wanted to point out that dispose is NOT primarily about memory management. Yes, it can help (and sometimes does) with memory management, but it's primary purpose is to give you deterministic releasing of scarce resources.

For example, if you open a hardware port (serial for example), a TCP/IP socket, a file (in exclusive access mode) or even a database connection you have now prevented any other code from using those items until they are released. Dispose generally releases these items (along with GDI and other "os" handles etc. which there are 1000's of available, but are still limited overall). If you don't call dipose on the owner object and explicitly release these resources, then try to open the same resource again in the future (or another program does) that open attempt will fail because your undisposed, uncollected object still has the item open. Of course, when the GC collects the item (if the Dispose pattern has been implemented correctly) the resource will get released... but you don't know when that will be, so you don't know when it's safe to re-open that resource. This is the primary issue Dispose works around. Of course, releasing these handles often releases memory too, and never releasing them may never release that memory... hence all the talk about memory leaks, or delays in memory clean up.

I have seen real world examples of this causing problems. For instance, I have seen ASP.Net web applications that eventually fail to connect to the database (albeit for short periods of time, or until the web server process is restarted) because the sql server 'connection pool is full'... i.e, so many connections have been created and not explicitly released in so short a period of time that no new connections can be created and many of the connections in the pool, although not active, are still referenced by undiposed and uncollected objects and so can't be reused. Correctly disposing the database connections where necessary ensures this problem doesn't happen (at least not unless you have very high concurrent access).

Can we define min-margin and max-margin, max-padding and min-padding in css?

I ran across this looking for a way to do a max-margin for responsive design. I need a 5% margin for mobile/tablet devices up to 48 pixels wide. Berd gave me the answer by using media queries.

My answer: 48 * 2 = 96 total max margin 96 is 10% of total width. 10 * 96 = (960) 100% of vw where 48px is the first time I want it to overwrite the % .

So my media queries to control my margins become:

@media (max-width: 959px) {
    .content {
        margin: 30px 5% 48px;
    }
}
@media (min-width: 960px) {
    .content {
        display:block;
        margin: 30px 48px 48px;
    }
}

Logging levels - Logback - rule-of-thumb to assign log levels

My approach, i think coming more from an development than an operations point of view, is:

  • Error means that the execution of some task could not be completed; an email couldn't be sent, a page couldn't be rendered, some data couldn't be stored to a database, something like that. Something has definitively gone wrong.
  • Warning means that something unexpected happened, but that execution can continue, perhaps in a degraded mode; a configuration file was missing but defaults were used, a price was calculated as negative, so it was clamped to zero, etc. Something is not right, but it hasn't gone properly wrong yet - warnings are often a sign that there will be an error very soon.
  • Info means that something normal but significant happened; the system started, the system stopped, the daily inventory update job ran, etc. There shouldn't be a continual torrent of these, otherwise there's just too much to read.
  • Debug means that something normal and insignificant happened; a new user came to the site, a page was rendered, an order was taken, a price was updated. This is the stuff excluded from info because there would be too much of it.
  • Trace is something i have never actually used.

Trigger standard HTML5 validation (form) without using submit button?

As stated in the other answers use event.preventDefault() to prevent form submitting.

To check the form before I wrote a little jQuery function you may use (note that the element needs an ID!)

(function( $ ){
    $.fn.isValid = function() {
        return document.getElementById(this[0].id).checkValidity();
    };
})( jQuery );

example usage

 $('#submitBtn').click( function(e){

        if ($('#registerForm').isValid()){
            // do the request
        } else {
            e.preventDefault();
        }
    });

Putting a password to a user in PhpMyAdmin in Wamp

There is a file called config.inc.php in the phpmyadmin folder.

The file path is C:\wamp\apps\phpmyadmin4.0.4

Edit The auth_type 'cookie' to 'config' or 'http'

$cfg['Servers'][$i]['auth_type'] = 'cookie';

$cfg['Servers'][$i]['auth_type'] = 'config';

or

$cfg['Servers'][$i]['auth_type'] = 'http';

When you go to the phpmyadmin site then you will be asked for the username and password. This also secure external people from accessing your phpmyadmin application if you happen to have your web server exposed to outside connections.

Powershell: Get FQDN Hostname

"$env:computername.$env:userdnsdomain" 

will work if separated out like this

"$env:computername"+"$env:userdnsdomain"

What does "use strict" do in JavaScript, and what is the reasoning behind it?

Quoting from w3schools:

The "use strict" Directive

The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5).

It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.

The purpose of "use strict" is to indicate that the code should be executed in "strict mode".

With strict mode, you can not, for example, use undeclared variables.

Why Strict Mode?

Strict mode makes it easier to write "secure" JavaScript.

Strict mode changes previously accepted "bad syntax" into real errors.

As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.

In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.

In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.

Please refer to http://www.w3schools.com/js/js_strict.asp to know more

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

What is the correct wget command syntax for HTTPS with username and password?

It's not that your file is partially downloaded. It fails authentication and hence downloads e.g "index.html" but it names it myfile.zip (since this is what you want to download).

I followed the link suggested by @thomasbabuj and figured it out eventually.

You should try adding --auth-no-challenge and as @thomasbabuj suggested replace your password entry

I.e

wget --auth-no-challenge --user=myusername --ask-password https://test.mydomain.com/files/myfile.zip

Proxy Error 502 : The proxy server received an invalid response from an upstream server

I had this issue once. It turned out to be database query issue. After re-create tables and index it has been fixed.

Although it says proxy error, when you look at server log, it shows execute query timeout. This is what I had before and how I solved it.

How to hide/show more text within a certain length (like youtube)

Show More, Show Less (Only when needed) No JQuery

I needed this functionality for an RSS feed on our company's website. This is what I came up with:

_x000D_
_x000D_
// Create Variables_x000D_
var allOSB = [];_x000D_
var mxh = '';_x000D_
_x000D_
window.onload = function() {_x000D_
  // Set Variables_x000D_
  allOSB = document.getElementsByClassName("only-so-big");_x000D_
  _x000D_
  if (allOSB.length > 0) {_x000D_
    mxh = window.getComputedStyle(allOSB[0]).getPropertyValue('max-height');_x000D_
    mxh = parseInt(mxh.replace('px', ''));_x000D_
    _x000D_
    // Add read-more button to each OSB section_x000D_
    for (var i = 0; i < allOSB.length; i++) {_x000D_
      var el = document.createElement("button");_x000D_
      el.innerHTML = "Read More";_x000D_
      el.setAttribute("type", "button");_x000D_
      el.setAttribute("class", "read-more hid");_x000D_
      _x000D_
      insertAfter(allOSB[i], el);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Add click function to buttons_x000D_
  var readMoreButtons = document.getElementsByClassName("read-more");_x000D_
  for (var i = 0; i < readMoreButtons.length; i++) {_x000D_
    readMoreButtons[i].addEventListener("click", function() { _x000D_
      revealThis(this);_x000D_
    }, false);_x000D_
  }_x000D_
  _x000D_
  // Update buttons so only the needed ones show_x000D_
  updateReadMore();_x000D_
}_x000D_
// Update on resize_x000D_
window.onresize = function() {_x000D_
  updateReadMore();_x000D_
}_x000D_
_x000D_
// show only the necessary read-more buttons_x000D_
function updateReadMore() {_x000D_
  if (allOSB.length > 0) {_x000D_
    for (var i = 0; i < allOSB.length; i++) {_x000D_
      if (allOSB[i].scrollHeight > mxh) {_x000D_
        if (allOSB[i].hasAttribute("style")) {_x000D_
          updateHeight(allOSB[i]);_x000D_
        }_x000D_
        allOSB[i].nextElementSibling.className = "read-more";_x000D_
      } else {_x000D_
        allOSB[i].nextElementSibling.className = "read-more hid";_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
function revealThis(current) {_x000D_
  var el = current.previousElementSibling;_x000D_
  if (el.hasAttribute("style")) {_x000D_
    current.innerHTML = "Read More";_x000D_
    el.removeAttribute("style");_x000D_
  } else {_x000D_
    updateHeight(el);_x000D_
    current.innerHTML = "Show Less";_x000D_
  }_x000D_
}_x000D_
_x000D_
function updateHeight(el) {_x000D_
  el.style.maxHeight = el.scrollHeight + "px";_x000D_
}_x000D_
_x000D_
// thanks to karim79 for this function_x000D_
// http://stackoverflow.com/a/4793630/5667951_x000D_
function insertAfter(referenceNode, newNode) {_x000D_
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);_x000D_
}
_x000D_
@import url('https://fonts.googleapis.com/css?family=Open+Sans:600');_x000D_
_x000D_
*,_x000D_
*:before,_x000D_
*:after {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
body {_x000D_
  font-family: 'Open Sans', sans-serif;_x000D_
}_x000D_
h1 {_x000D_
  text-align: center;_x000D_
}_x000D_
.main-container {_x000D_
  margin: 30px auto;_x000D_
  max-width: 1000px;_x000D_
  padding: 20px;_x000D_
}_x000D_
.only-so-big p {_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
p {_x000D_
  font-size: 15px;_x000D_
  line-height: 20px;_x000D_
}_x000D_
hr {_x000D_
  background: #ccc;_x000D_
  display: block;_x000D_
  height: 1px;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
  NECESSARY SECTION_x000D_
*/_x000D_
.only-so-big {_x000D_
  background: rgba(178, 252, 255, .3);_x000D_
  height: 100%;_x000D_
  max-height: 100px;_x000D_
  overflow: hidden;_x000D_
  -webkit-transition: max-height .75s;_x000D_
  transition: max-height .75s;_x000D_
}_x000D_
_x000D_
.read-more {_x000D_
  background: none;_x000D_
  border: none;_x000D_
  color: #1199f9;_x000D_
  cursor: pointer;_x000D_
  font-size: 1em;_x000D_
  outline: none; _x000D_
}_x000D_
.read-more:hover {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
.read-more:focus {_x000D_
  outline: none;_x000D_
}_x000D_
.read-more::-moz-focus-inner {_x000D_
  border: 0;_x000D_
}_x000D_
.hid {_x000D_
  display: none;_x000D_
}
_x000D_
<div class="main-container">_x000D_
      <h1>Controlling Different Content Size</h1>_x000D_
      <p>We're working with an RSS feed and have had issues with some being much larger than others (content wise). I only want to show the "Read More" button if it's needed.</p>_x000D_
      <div class="only-so-big">_x000D_
        <p>This is just a short guy. No need for the read more button.</p>_x000D_
      </div>_x000D_
      <hr>_x000D_
      <div class="only-so-big">_x000D_
        <p>This one has way too much content to show. Best be saving it for those who want to read everything in here.</p>_x000D_
        <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia_x000D_
          voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi THE END!</p>_x000D_
      </div>_x000D_
      <hr>_x000D_
      <div class="only-so-big">_x000D_
        <p>Another small section with not a lot of content</p>_x000D_
      </div>_x000D_
      <hr>_x000D_
      <div class="only-so-big">_x000D_
        <p>Make Window smaller to show "Read More" button.<br> totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed?</p>_x000D_
      </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How to remove old Docker containers

You can use the following command to remove the exited containers:

docker rm $(sudo docker ps -a | grep Exit | cut -d ' ' -f 1)

Here is the full gist to also remove the old images on docker: Gist to remove old Docker containers and images.

How to read a text file in project's root directory?

You can use the following to get the root directory of a website project:

String FilePath;
FilePath = Server.MapPath("/MyWebSite");

Or you can get the base directory like so:

AppDomain.CurrentDomain.BaseDirectory

SameSite warning Chrome 77

When it comes to Google Analytics I found raik's answer at Secure Google tracking cookies very useful. It set secure and samesite to a value.

ga('create', 'UA-XXXXX-Y', {
    cookieFlags: 'max-age=7200;secure;samesite=none'
});

Also more info in this blog post

How to use glyphicons in bootstrap 3.0

The icons (glyphicons) are now contained in a separate css file...

The markup has changed to:

<i class="glyphicon glyphicon-search"></i>

or

<span class="glyphicon glyphicon-search"></span>

Here is a helpful list of changes for Bootstrap 3: http://bootply.com/bootstrap-3-migration-guide

Make XAMPP / Apache serve file outside of htdocs folder

If you're trying to get XAMPP to use a network drive as your document root you have to use UNC paths in httpd.conf. XAMPP will not recognize your mapped network drives.

For example the following won't work, DocumentRoot "X:/webroot"

But this will, DocumentRoot "//192.168.10.100/webroot" (note the forward slashes, not back slashes)

How do you set a default value for a MySQL Datetime column?

For all who use the TIMESTAMP column as a solution i want to second the following limitation from the manual:

http://dev.mysql.com/doc/refman/5.0/en/datetime.html

"The TIMESTAMP data type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in. These properties are described later in this section. "

So this will obviously break your software in about 28 years.

I believe the only solution on the database side is to use triggers like mentioned in other answers.

Using $window or $location to Redirect in AngularJS

Not sure from what version, but I use 1.3.14 and you can just use:

window.location.href = '/employee/1';

No need to inject $location or $window in the controller and no need to get the current host address.

How can I convert a string to an int in Python?

def addition(a, b): return a + b

def subtraction(a, b): return a - b

def multiplication(a, b): return a * b

def division(a, b): return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
 print "Please choose what you'd like to do:"

Eclipse error: "The import XXX cannot be resolved"

Obviously there are cases where there is a valid issue however Eclipse throws this error for no good reason sometimes. This is still (in v 2020-09) an old (2010) Eclipse bug that can be resolved by making a negligible change to the project settings.

touch .classpath

solves the issue, or go to Project > Properties > Java Build Path > Order and Export > make a meaningless order change > Apply. Changing the order back does not regress to the problem.

Replace substring with another substring C++

using std::string;

string string_replace( string src, string const& target, string const& repl)
{
    // handle error situations/trivial cases

    if (target.length() == 0) {
        // searching for a match to the empty string will result in 
        //  an infinite loop
        //  it might make sense to throw an exception for this case
        return src;
    }

    if (src.length() == 0) {
        return src;  // nothing to match against
    }

    size_t idx = 0;

    for (;;) {
        idx = src.find( target, idx);
        if (idx == string::npos)  break;

        src.replace( idx, target.length(), repl);
        idx += repl.length();
    }

    return src;
}

Since it's not a member of the string class, it doesn't allow quite as nice a syntax as in your example, but the following will do the equivalent:

test = string_replace( string_replace( test, "abc", "hij"), "def", "klm")

Reading integers from binary file in Python

When you read from a binary file, a data type called bytes is used. This is a bit like list or tuple, except it can only store integers from 0 to 255.

Try:

file_size = fin.read(4)
file_size0 = file_size[0]
file_size1 = file_size[1]
file_size2 = file_size[2]
file_size3 = file_size[3]

Or:

file_size = list(fin.read(4))

Instead of:

file_size = int(fin.read(4))

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

Center content vertically on Vuetify

Still surprised that no one proposed the shortest solution with align-center justify-center to center content vertically and horizontally. Check this CodeSandbox and code below:

<v-container fluid fill-height>
  <v-layout align-center justify-center>
    <v-flex>
      <!-- Some HTML elements... -->
    </v-flex>
  </v-layout>
</v-container>

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

TSQL CASE with if comparison in SELECT statement

Should be:

SELECT registrationDate, 
       (SELECT CASE
        WHEN COUNT(*)< 2 THEN 'Ama'
        WHEN COUNT(*)< 5 THEN 'SemiAma' 
        WHEN COUNT(*)< 7 THEN 'Good'  
        WHEN COUNT(*)< 9 THEN 'Better' 
        WHEN COUNT(*)< 12 THEN 'Best'
        ELSE 'Outstanding'
        END as a FROM Articles 
        WHERE Articles.userId = Users.userId) as ranking,
        (SELECT COUNT(*) 
        FROM Articles 
        WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS

removeEventListener on anonymous functions in JavaScript

Possibly not the best solution in terms of what you are asking. I have still not determined an efficient method for removing anonymous function declared inline with the event listener invocation.

I personally use a variable to store the <target> and declare the function outside of the event listener invocation eg:

const target = document.querySelector('<identifier>');

function myFunc(event) { function code; }

target.addEventListener('click', myFunc);

Then to remove the listener:

target.removeEventListener('click', myFunc);

Not the top recommendation you will receive but to remove anonymous functions the only solution I have found useful is to remove then replace the HTML element. I am sure there must be a better vanilla JS method but I haven't seen it yet.

Eclipse HotKey: how to switch between tabs?

Custom KeyBinding sequence example : CTRL + TAB to switch between visilble Modules or Editors Forward direction using Eclipse RCP.

you press CTRL + TAB second time to open another editor and close previous editor using RCP Eclipse.

package rcp_demo.Toolbar;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import rcp_demo.Editor.EmployeeEditor;
import rcp_demo.Editor.EmployeeEditorInput;
import rcp_demo.Editor.ProductEditor;
import rcp_demo.Editor.ProductEditorInput;
import rcp_demo.Editor.UserEditor;
import rcp_demo.Editor.UserEditorInput;

public class Forward_Editor extends AbstractHandler{

    static String Editor_name;  //  Active Editor name store in Temporary 
    static int cnt;             //  close editor count this variable
    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {

        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
        IWorkbenchPage page = window.getActivePage();

        UserEditorInput std_input = new UserEditorInput();
        EmployeeEditorInput emp_input=new EmployeeEditorInput();
        ProductEditorInput product_input=new ProductEditorInput();

        IEditorReference[] editors = page.getEditorReferences();

        //Blank Editor Window to execute..
        if(editors.length==0)
        {
            //First time close editor can open Student_Editor
            if(cnt==1 && Editor_name.equals("Student_Editor"))
            {
                try {
                    page.openEditor(emp_input, EmployeeEditor.Id);
                    cnt=1;
                    Editor_name=page.getActiveEditor().getTitle();
                    System.out.println("EMP>>Len:: "+editors.length+"..EDi::"+Editor_name);
                } catch (PartInitException e) {
                    e.printStackTrace();
                }       
            }
            //First time close editor can open Employee_Editor
            else if(cnt==1 && Editor_name.equals("Employee_Editor"))
            {
                try {
                    page.openEditor(product_input,ProductEditor.ID);
                    cnt=1;
                    Editor_name=page.getActiveEditor().getTitle();
                    System.out.println("PRO>>Len:: "+editors.length+"..EDi::"+Editor_name); 
                } catch (PartInitException e) {e.printStackTrace();
                }
            }
            //First time close editor can open Product_Editor
            else if(cnt==1 && Editor_name.equals("Product_Editor"))
            {
                try {
                    page.openEditor(std_input, UserEditor.ID);
                    System.out.println("student Editor open");
                    cnt=1;
                    Editor_name=page.getActiveEditor().getTitle();
                    System.out.println("Close::"+Editor_name);
                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
            //First Time call // empty editors 
            else{
                try {
                    page.openEditor(std_input, UserEditor.ID);
                    System.out.println("student Editor open");
                    Editor_name=page.getActiveEditor().getTitle();
                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
        }//End if condition

        //AvtiveEditor(Student_Editor) close to open Employee Editor
        else if(page.getActiveEditor().getTitle().equals("Student_Editor"))
        {
            try {
                //page.closeAllEditors(true);
                page.closeEditor(page.getActiveEditor(), true);
                page.openEditor(emp_input, EmployeeEditor.Id);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("EMP>>Len:: "+editors.length+"..EDi::"+Editor_name);
            } catch (PartInitException e) {
                e.printStackTrace();
            }
        }
        //AvtiveEditor(Employee_Editor) close to open Product Editor
        else if(page.getActiveEditor().getTitle().equals("Employee_Editor"))
        {
            try {
                page.closeAllEditors(true);
                page.openEditor(product_input,ProductEditor.ID);

                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("PRO>>Len:: "+editors.length+"..EDi::"+Editor_name);

            } catch (PartInitException e) {
                e.printStackTrace();
            }
        }
        //AvtiveEditor(Product_Editor) close to open Student Editor
        else if(page.getActiveEditor().getTitle().equals("Product_Editor"))
        {
            try {
                page.closeAllEditors(true);
                page.openEditor(std_input, UserEditor.ID);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("stud>>Len:: "+editors.length+"..EDi::"+Editor_name);
            } catch (PartInitException e) {
                e.printStackTrace();
            }
        }
        //by default open Student Editor
        else 
        {
            try {
                page.closeAllEditors(true);
                page.openEditor(std_input, UserEditor.ID);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("stud_else>>Len:: "+editors.length+"..EDi::"+Editor_name);
            } catch (PartInitException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

>Custom KeyBinding sequence example : <kbd> SHIFT + TAB </kbd> to switch between visilble Modules or Editors **Backword** direction using Eclipse RCP.


package rcp_demo.Toolbar;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import rcp_demo.Editor.EmployeeEditor;
import rcp_demo.Editor.EmployeeEditorInput;
import rcp_demo.Editor.ProductEditor;
import rcp_demo.Editor.ProductEditorInput;
import rcp_demo.Editor.UserEditor;
import rcp_demo.Editor.UserEditorInput;

public class Backword_Editor extends AbstractHandler{

    static String Editor_name;   // Active Editor name store in Temporary 
    static int cnt;

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {

        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
        IWorkbenchPage page = window.getActivePage();
        //Three object create in EditorInput 
        UserEditorInput std_input = new UserEditorInput();
        EmployeeEditorInput emp_input=new EmployeeEditorInput();
        ProductEditorInput product_input=new ProductEditorInput();

        IEditorReference[] editors = page.getEditorReferences();
        System.out.println("Length : "+editors.length);

        if(editors.length==0)
        {
            //First time close editor can open Student_Editor
            if(cnt==1 && Editor_name.equals("Product_Editor"))
            {
                try {
                    page.openEditor(emp_input, EmployeeEditor.Id);
                    cnt=1;
                    Editor_name=page.getActiveEditor().getTitle();
                    System.out.println("EMP>>Len:: "+editors.length+"..EDi::"+Editor_name);
                } catch (PartInitException e) {
                    e.printStackTrace();
                }               
            }
            //First time close editor can open Employee_Editor
            else if(cnt==1 && Editor_name.equals("Employee_Editor"))
            {
                try {
                    page.openEditor(std_input, UserEditor.ID);
                    cnt=1;
                    Editor_name=page.getActiveEditor().getTitle();
                    System.out.println("Student>>Len:: "+editors.length+"..student::"+Editor_name);

                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
            //First time close editor can open Product_Editor
            else if(cnt==1 && Editor_name.equals("Student_Editor"))
            {
                        try {
                            page.openEditor(product_input,ProductEditor.ID);
                            cnt=1;
                            Editor_name=page.getActiveEditor().getTitle();
                            System.out.println("PRO>>Len:: "+editors.length+"..EDi::"+Editor_name);

                        } catch (PartInitException e) {
                            e.printStackTrace();
                        }
            } 
            //First Time or empty editors to check this condition
            else{
                try {
                    page.openEditor(product_input,ProductEditor.ID);
                    System.out.println("product Editor open");
                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
        }
        //AvtiveEditor(Product_Editor) close to open Employee Editor
        else if(page.getActiveEditor().getTitle().equals("Product_Editor"))
        {
            System.out.println("Product:: "+page.getActiveEditor().getTitle());
            try {
                page.closeAllEditors(true);
                page.openEditor(emp_input, EmployeeEditor.Id);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("Employee Editor open");
            } catch (PartInitException e) {
                e.printStackTrace();
            }
        }
        //AvtiveEditor(Employee_Editor) close to open Student Editor
        else if(page.getActiveEditor().getTitle().equals("Employee_Editor"))
        {
            System.out.println("Emp:: "+page.getActiveEditor().getTitle());
            try {
                page.closeAllEditors(true);
                page.openEditor(std_input, UserEditor.ID);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("student Editor open");
            } catch (PartInitException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //AvtiveEditor(Student_Editor) close to open Product Editor
        else if(page.getActiveEditor().getTitle().equals("Student_Editor"))
        {
            System.out.println("Product:: "+page.getActiveEditor().getTitle());
            try {
                page.closeAllEditors(true);
                page.openEditor(product_input,ProductEditor.ID);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("product Editor open");
            } catch (PartInitException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //by default open Student Editor
        else 
        {
            try {
                page.closeAllEditors(true);
                page.openEditor(product_input,ProductEditor.ID);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("product Editor open");
            } catch (PartInitException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}

Custom KeyBinding sequence example : SHIFT + TAB to switch between visilble Modules or Editors Backword direction using Eclipse RCP.

package rcp_demo.Toolbar;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import rcp_demo.Editor.EmployeeEditor;
import rcp_demo.Editor.EmployeeEditorInput;
import rcp_demo.Editor.ProductEditor;
import rcp_demo.Editor.ProductEditorInput;
import rcp_demo.Editor.UserEditor;
import rcp_demo.Editor.UserEditorInput;

public class Backword_Editor extends AbstractHandler{

    static String Editor_name;   // Active Editor name store in Temporary 
    static int cnt;

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {

        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
        IWorkbenchPage page = window.getActivePage();
        //Three object create in EditorInput 
        UserEditorInput std_input = new UserEditorInput();
        EmployeeEditorInput emp_input=new EmployeeEditorInput();
        ProductEditorInput product_input=new ProductEditorInput();

        IEditorReference[] editors = page.getEditorReferences();
        System.out.println("Length : "+editors.length);

        if(editors.length==0)
        {
            //First time close editor can open Student_Editor
            if(cnt==1 && Editor_name.equals("Product_Editor"))
            {
                try {
                    page.openEditor(emp_input, EmployeeEditor.Id);
                    cnt=1;
                    Editor_name=page.getActiveEditor().getTitle();
                    System.out.println("EMP>>Len:: "+editors.length+"..EDi::"+Editor_name);
                } catch (PartInitException e) {
                    e.printStackTrace();
                }               
            }
            //First time close editor can open Employee_Editor
            else if(cnt==1 && Editor_name.equals("Employee_Editor"))
            {
                try {
                    page.openEditor(std_input, UserEditor.ID);
                    cnt=1;
                    Editor_name=page.getActiveEditor().getTitle();
                    System.out.println("Student>>Len:: "+editors.length+"..student::"+Editor_name);

                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
            //First time close editor can open Product_Editor
            else if(cnt==1 && Editor_name.equals("Student_Editor"))
            {
                        try {
                            page.openEditor(product_input,ProductEditor.ID);
                            cnt=1;
                            Editor_name=page.getActiveEditor().getTitle();
                            System.out.println("PRO>>Len:: "+editors.length+"..EDi::"+Editor_name);

                        } catch (PartInitException e) {
                            e.printStackTrace();
                        }
            } 
            //First Time or empty editors to check this condition
            else{
                try {
                    page.openEditor(product_input,ProductEditor.ID);
                    System.out.println("product Editor open");
                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
        }
        //AvtiveEditor(Product_Editor) close to open Employee Editor
        else if(page.getActiveEditor().getTitle().equals("Product_Editor"))
        {
            System.out.println("Product:: "+page.getActiveEditor().getTitle());
            try {
                page.closeAllEditors(true);
                page.openEditor(emp_input, EmployeeEditor.Id);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("Employee Editor open");
            } catch (PartInitException e) {
                e.printStackTrace();
            }
        }
        //AvtiveEditor(Employee_Editor) close to open Student Editor
        else if(page.getActiveEditor().getTitle().equals("Employee_Editor"))
        {
            System.out.println("Emp:: "+page.getActiveEditor().getTitle());
            try {
                page.closeAllEditors(true);
                page.openEditor(std_input, UserEditor.ID);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("student Editor open");
            } catch (PartInitException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //AvtiveEditor(Student_Editor) close to open Product Editor
        else if(page.getActiveEditor().getTitle().equals("Student_Editor"))
        {
            System.out.println("Product:: "+page.getActiveEditor().getTitle());
            try {
                page.closeAllEditors(true);
                page.openEditor(product_input,ProductEditor.ID);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("product Editor open");
            } catch (PartInitException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //by default open Student Editor
        else 
        {
            try {
                page.closeAllEditors(true);
                page.openEditor(product_input,ProductEditor.ID);
                cnt=1;
                Editor_name=page.getActiveEditor().getTitle();
                System.out.println("product Editor open");
            } catch (PartInitException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}

Key Sequence

M1 means CTRL

M2 means SHIFT

plugin.xml


<extension point="org.eclipse.ui.commands">
        <command
                defaultHandler="rcp_demo.Toolbar.Forward_Editor"
                id="RCP_Demo.Toolbar.Forward_editor_open_cmd"
                name="Forward_Editor">
        </command>
        <command
                defaultHandler="rcp_demo.Toolbar.Backword_Editor"
                id="RCP_Demo.Toolbar.backwards_editor_open_cmd"
                name="Backword_Editor">
        </command>
    </extension>
<extension point="org.eclipse.ui.bindings">
        <key
                commandId="RCP_Demo.Toolbar.Forward_editor_open_cmd"
                schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
                sequence="M1+TAB">
        </key>  
        <key
                commandId="RCP_Demo.Toolbar.backwards_editor_open_cmd"
                schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
                sequence="M2+TAB">
        </key>              
</extension>

How do I convert between ISO-8859-1 and UTF-8 in Java?

In general, you can't do this. UTF-8 is capable of encoding any Unicode code point. ISO-8859-1 can handle only a tiny fraction of them. So, transcoding from ISO-8859-1 to UTF-8 is no problem. Going backwards from UTF-8 to ISO-8859-1 will cause "replacement characters" (�) to appear in your text when unsupported characters are found.

To transcode text:

byte[] latin1 = ...
byte[] utf8 = new String(latin1, "ISO-8859-1").getBytes("UTF-8");

or

byte[] utf8 = ...
byte[] latin1 = new String(utf8, "UTF-8").getBytes("ISO-8859-1");

You can exercise more control by using the lower-level Charset APIs. For example, you can raise an exception when an un-encodable character is found, or use a different character for replacement text.

how to change php version in htaccess in server

This worked for me

PHP 7.2

AddHandler application/x-httpd-ea-php72 .php .php7 .phtml

PHP 7.3

AddHandler application/x-httpd-ea-php73 .php

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

How to create a bash script to check the SSH connection?

If you would like to check a remote folder exists, or any other file-test really:

if [ -n "$(ssh "${user}@${server}" [ -d "$folder" ] && echo 1; exit)" ]; then
    # exists
else
    # doesn't exist
fi

Do not forget the quotes in "$(ssh ...)".

How to make CREATE OR REPLACE VIEW work in SQL Server?

Here is another method, where you don't have to duplicate the contents of the view:

IF (NOT EXISTS (SELECT 1 FROM sys.views WHERE name = 'data_VVV'))
BEGIN
    EXECUTE('CREATE VIEW data_VVVV as SELECT 1 as t');
END;

GO

ALTER VIEW data_VVVV AS 
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A ;

The first checks for the existence of the view (there are other ways to do this). If it doesn't exist, then create it with something simple and dumb. If it does, then just move on to the alter view statement.

how to install tensorflow on anaconda python 3.6

Uninstall Python 3.7 for Windows, and only install Python 3.6.0 then you will have no problem or receive the error message:

import tensorflow as tf ModuleNotFoundError: No module named 'tensorflow'

Single-threaded apartment - cannot instantiate ActiveX control

If you used [STAThread] to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!

Private void YourFunc(..)
{
    if (this.InvokeRequired)
    {
        Invoke(new MethodInvoker(delegate()
        {
           // Call your method YourFunc(..);
        }));
    }
    else
    {
        ///
    }

How do I add the Java API documentation to Eclipse?

Ensure "Preferences" -> "Java" -> "Editor" -> "Hovers" -> "Combined Hover" is checked.

Working copy locked error in tortoise svn while committing

If this (https://stackoverflow.com/a/11764922/3045875) does not help: Check if another SVN tool is interfering and close the tool. We just struggled a couple of hours at merging using TortoiseSVN and had dozens of such lock errors. Eventually we figured that Matlabs SVN integration is interfering and after closing it all worked out.

Can constructors be async?

Your problem is comparable to the creation of a file object and opening the file. In fact there are a lot of classes where you have to perform two steps before you can actually use the object: create + Initialize (often called something similar to Open).

The advantage of this is that the constructor can be lightweight. If desired, you can change some properties before actually initializing the object. When all properties are set, the Initialize/Open function is called to prepare the object to be used. This Initialize function can be async.

The disadvantage is that you have to trust the user of your class that he will call Initialize() before he uses any other function of your class. In fact if you want to make your class full proof (fool proof?) you have to check in every function that the Initialize() has been called.

The pattern to make this easier is to declare the constructor private and make a public static function that will construct the object and call Initialize() before returning the constructed object. This way you'll know that everyone who has access to the object has used the Initialize function.

The example shows a class that mimics your desired async constructor

public MyClass
{
    public static async Task<MyClass> CreateAsync(...)
    {
        MyClass x = new MyClass();
        await x.InitializeAsync(...)
        return x;
    }

    // make sure no one but the Create function can call the constructor:
    private MyClass(){}

    private async Task InitializeAsync(...)
    {
        // do the async things you wanted to do in your async constructor
    }

    public async Task<int> OtherFunctionAsync(int a, int b)
    {
        return await ... // return something useful
    }

Usage will be as follows:

public async Task<int> SomethingAsync()
{
    // Create and initialize a MyClass object
    MyClass myObject = await MyClass.CreateAsync(...);

    // use the created object:
    return await myObject.OtherFunctionAsync(4, 7);
}

What data type to use for hashed password field and what length?

You can actually use CHAR(length of hash) to define your datatype for MySQL because each hashing algorithm will always evaluate out to the same number of characters. For example, SHA1 always returns a 40-character hexadecimal number.

How can one create an overlay in css?

         div{
         background-image:url('');
         background-size:cover;
         background-position:top center;
         position:relative;
         }

         div:before{
         content:'';
         position:absolute;
         left:0;
         top:0;
         height:100%;
         width:100%;
         background-color:rgba(0,0,0,0.7);
         }

Increase heap size in Java

You can increase the Heap Size by passing JVM parameters -Xms and -Xmx like below:

For Jar Files:

java -jar -Xms4096M -Xmx6144M jarFilePath.jar

For Java Files:

 java -Xms4096M -Xmx6144M ClassName

The above parameters increase the InitialHeapSize (-Xms) to 4GB (4096 MB) and MaxHeapSize(-Xmx) to 6GB (6144 MB).

But, the Young Generation Heap Size will remain same and the additional HeapSize will be added to the Old Generation Heap Size. To equalize the size of Young Gen Heap and Old Gen Heap, use -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy params.

java -jar -Xms4096M -Xmx6144M -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy pathToJarFile.jar

-XX:NewRatio = Old Gen Heap Size : Young Gen HeapSize (You can play with this ratio to get your desired ratio).

Box shadow for bottom side only

Specify negative value to spread value. This works for me:

box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Be sure to remember to invoke json.loads() on the contents of the file, as opposed to the file path of that JSON:

json_file_path = "/path/to/example.json"

with open(json_file_path, 'r') as j:
     contents = json.loads(j.read())

I think a lot of people are guilty of doing this every once in a while (myself included):

contents = json.loads(json_file_path)

How to deploy a Java Web Application (.war) on tomcat?

Note that you can deploy remotely using HTTP.

http://localhost:8080/manager/deploy

Upload the web application archive (WAR) file that is specified as the request data in this HTTP PUT request, install it into the appBase directory of our corresponding virtual host, and start it using the war file name without the .war extension as the path. The application can later be undeployed (and the corresponding application directory removed) by use of the /undeploy. To deploy the ROOT web application (the application with a context path of "/"), name the war ROOT.war.

and if you're using Ant you can do this using Tomcat Ant tasks (perhaps following a successful build).

To determine which path you then hit on your browser, you need to know the port Tomcat is running on, the context and your servlet path. See here for more details.

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

How to export SQL Server database to MySQL?

I used the below connection string on the Advanced tab of MySQL Migration Tool Kit to connect to SQL Server 2008 instance:

jdbc:jtds:sqlserver://"sql_server_ip_address":1433/<db_name>;Instance=<sqlserver_instanceName>;user=sa;password=PASSWORD;namedPipe=true;charset=utf-8;domain= 

Usually the parameter has "systemName\instanceName". But in the above, do not add "systemName\" (use only InstanceName).

To check what the instanceName should be, go to services.msc and check the DisplayName of the MSSQL instance. It shows similar to MSSQL$instanceName.

Hope this help in MSSQL connectivity from mysql migration toolKit.

TypeError: 'function' object is not subscriptable - Python

You can use this:

bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bankHoliday[month])

bank_holiday(int(input("Which month would you like to check out: ")))

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a hard time making this work too, the solution for me was to use both hyui and konstantin answers,

class ExampleTask extends AsyncTask<String, String, String> {

// Your onPreExecute method.

@Override
protected String doInBackground(String... params) {
    // Your code.
    if (condition_is_true) {
        this.publishProgress("Show the dialog");
    }
    return "Result";
}

@Override
protected void onProgressUpdate(String... values) {

    super.onProgressUpdate(values);
    YourActivity.this.runOnUiThread(new Runnable() {
       public void run() {
           alertDialog.show();
       }
     });
 }

}

How can I introduce multiple conditions in LIKE operator?

Even u can try this

Function

CREATE  FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(   
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)  
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
  BEGIN 
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
      BEGIN  
        INSERT INTO @Strings VALUES (@text)
          BREAK 
      END 
    IF (@index > 1) 
      BEGIN  
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      END 
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END

Query

select * from my_table inner join (select value from fn_split('ABC,MOP',','))
as split_table on my_table.column_name like '%'+split_table.value+'%';

What is meant by immutable?

Immutable simply mean unchangeable or unmodifiable. Once string object is created its data or state can't be changed

Consider bellow example,

class Testimmutablestring{  
  public static void main(String args[]){  
    String s="Future";  
    s.concat(" World");//concat() method appends the string at the end  
    System.out.println(s);//will print Future because strings are immutable objects  
  }  
 }  

Let's get idea considering bellow diagram,

enter image description here

In this diagram, you can see new object created as "Future World". But not change "Future".Because String is immutable. s, still refer to "Future". If you need to call "Future World",

String s="Future";  
s=s.concat(" World");  
System.out.println(s);//print Future World

Why are string objects immutable in java?

Because Java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "Future".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Horizontal ListView in Android?

As per Android Documentation RecyclerView is the new way to organize the items in listview and to be displayed horizontally

Advantages:

  1. Since by using Recyclerview Adapter, ViewHolder pattern is automatically implemented
  2. Animation is easy to perform
  3. Many more features

More Information about RecyclerView:

  1. grokkingandroid.com
  2. antonioleiva.com

Sample:

survivingwithandroid.com

Just add the below block to make the ListView to horizontal from vertical

Code-snippet

LinearLayoutManager layoutManager= new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(layoutManager);

rawQuery(query, selectionArgs)

rawQuery("SELECT id, name FROM people WHERE name = ? AND id = ?", new String[] {"David", "2"});

You pass a string array with an equal number of elements as you have "?"

How do I check if a string contains another string in Objective-C?

For iOS 8.0+ and macOS 10.10+, you can use NSString's native containsString:.

For older versions of iOS and macOS, you can create your own (obsolete) category for NSString:

@interface NSString ( SubstringSearch )
    - (BOOL)containsString:(NSString *)substring;
@end

// - - - - 

@implementation NSString ( SubstringSearch )

- (BOOL)containsString:(NSString *)substring
{    
    NSRange range = [self rangeOfString : substring];
    BOOL found = ( range.location != NSNotFound );
    return found;
}

@end

Note: Observe Daniel Galasko's comment below regarding naming

check if array is empty (vba excel)

I would do this as

if isnumeric(ubound(a)) = False then msgbox "a is empty!"

How to execute two mysql queries as one in PHP/MYSQL?

Yes it is possible without using MySQLi extension.

Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.

Refer to the comments below Husni's post for more information.

Get Bitmap attached to ImageView

try this code:

Bitmap bitmap;
bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

What's the difference between primitive and reference types?

these are primitive data types

  • boolean
  • character
  • byte
  • short
  • integer
  • long
  • float
  • double

saved in stack in the memory which is managed memory on the other hand object data type or reference data type stored in head in the memory managed by GC

this is the most important difference

How do I reset a jquery-chosen select option with jQuery?

jQuery("#autoship_option option:first").attr('selected', true);

Use underscore inside Angular controllers

you can use this module -> https://github.com/jiahut/ng.lodash

this is for lodash so does underscore

Sum across multiple columns with dplyr

I would use regular expression matching to sum over variables with certain pattern names. For example:

df <- df %>% mutate(sum1 = rowSums(.[grep("x[3-5]", names(.))], na.rm = TRUE),
                    sum_all = rowSums(.[grep("x", names(.))], na.rm = TRUE))

This way you can create more than one variable as a sum of certain group of variables of your data frame.

How do I get a file's directory using the File object?

If you do something like this:

File file = new File("test.txt");
String parent = file.getParent();

parent will be null.

So to get directory of this file you can do next:

parent = file.getAbsoluteFile().getParent();

WordPress path url in js script file

    wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);
    wp_enqueue_script('custom-js');

    $wnm_custom = array( 'template_url' => get_bloginfo('template_url') );
    wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );

and in custom.js

alert(wnm_custom.template_url);

Iterating Through a Dictionary in Swift

This is a user-defined function to iterate through a dictionary:

func findDic(dict: [String: String]){
    for (key, value) in dict{
    print("\(key) : \(value)")
  }
}

findDic(dict: ["Animal":"Lion", "Bird":"Sparrow"])
//prints Animal : Lion 
         Bird : Sparrow

Converting between java.time.LocalDateTime and java.util.Date

I'm not sure if this is the simplest or best way, or if there are any pitfalls, but it works:

static public LocalDateTime toLdt(Date date) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    ZonedDateTime zdt = cal.toZonedDateTime();
    return zdt.toLocalDateTime();
}

static public Date fromLdt(LocalDateTime ldt) {
    ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
    GregorianCalendar cal = GregorianCalendar.from(zdt);
    return cal.getTime();
}

Altering a column to be nullable

ALTER TABLE Merchant_Pending_Functions MODIFY COLUMN `NumberOfLocations` INT null;

This will work for you.

If you want to change a not null column to allow null, no need to include not null clause. Because default columns get not null.

ALTER TABLE Merchant_Pending_Functions MODIFY COLUMN `NumberOfLocations` INT;

C# declare empty string array

Your syntax is wrong:

string[] arr = new string[]{};

or

string[] arr = new string[0];

List of all unique characters in a string?

For completeness sake, here's another recipe that sorts the letters as a byproduct of the way it works:

>>> from itertools import groupby
>>> ''.join(k for k, g in groupby(sorted("aaabcabccd")))
'abcd'

How to change default Anaconda python environment

For Jupyter and Windows users, you can change the Target path in your Jupyter Notebook (anaconda3) shortcut from C:\Users\<YourUserName>\anaconda3 to C:\Users\<YourUserName>\anaconda3\envs\<YourEnvironmentName>

you could do the same thing for the Anaconda Prompt..etc.

After changing the path you can check your active environment by opening a terminal in Jupyter and run conda info --envs.

enter image description here

tsc is not recognized as internal or external command

For windows

After installing typescript globally

npm install typescript -g 

just search for "node.js command prompt"

type in command promt

tsc -v 

Here we can see tsc command works, now navigate to your folder and type

tsc filename.ts 

its complies ts to js file.

Can I use return value of INSERT...RETURNING in another INSERT?

DO $$
DECLARE tableId integer;
BEGIN
  INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id INTO tableId;
  INSERT INTO Table2 (val) VALUES (tableId);
END $$;

Tested with psql (10.3, server 9.6.8)

Getting the document object of an iframe

For even more robustness:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...

php convert datetime to UTC

As strtotime requires specific input format, DateTime::createFromFormat could be used (php 5.3+ is required)

// set timezone to user timezone
date_default_timezone_set($str_user_timezone);

// create date object using any given format
$date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime);

// convert given datetime to safe format for strtotime
$str_user_datetime = $date->format('Y-m-d H:i:s');

// convert to UTC
$str_UTC_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));

// return timezone to server default
date_default_timezone_set($str_server_timezone);

How to install numpy on windows using pip install?

py -m pip install numpy

Worked for me!

Get time of specific timezone

The best way to do this is to use getLocaleString, like this:

Create a date object:

date = new Date(0)

If you are in Berlin, this should convert to this string:

Thu Jan 01 1970 01:00:00 GMT+0100 (CET)

Get the hours in Athens:

date.toLocaleString('de-DE', {hour: '2-digit',   hour12: false, timeZone: 'Europe/Athens' })

'02'

Get the hours in Shanghai:

date.toLocaleString('de-DE', {hour: '2-digit',   hour12: false, timeZone: 'Asia/Shanghai' })

'08'

How can I adjust DIV width to contents

Try width: max-content to adjust the width of the div by it's content.

<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
  width:500px;
  margin: auto;
  border: 3px solid #73AD21;
}

div.ex2 {
  width: max-content;
  margin: auto;
  border: 3px solid #73AD21;
}
</style>
</head>
<body>

<div class="ex1">This div element has width 500px;</div>
<br>
<div class="ex2">Width by content size</div>

</body>
</html>

Convert named list to vector with values only

This can be done by using unlist before as.vector. The result is the same as using the parameter use.names=FALSE.

as.vector(unlist(myList))

Simplest JQuery validation rules example

$("#commentForm").validate({
    rules: {
     cname : { required : true, minlength: 2 }
    }
});

Should be something like that, I've just typed this up in the editor here so might be a syntax error or two, but you should be able to follow the pattern and the documentation

Cannot push to Git repository on Bitbucket

I got this error

Connection to bitbucket.org closed by remote host. fatal: Could not read from remote repository. Please make sure you have the correct access rights.

Then i tried

git config --global user.email "[email protected]"

worked without quotes.

JFrame background image

I used a very similar method to @bott, but I modified it a little bit to make there be no need to resize the image:

BufferedImage img = null;
try {
    img = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}
Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));

Works every time. You can also get the width and height of the jFrame and use that in place of the 800 and 508 respectively.

Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi
EOF

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    #!/bin/bash
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
    else
      exit 1
    fi
EOF

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

How to increase timeout for a single test case in mocha

From command line:

mocha -t 100000 test.js

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

Shared folder was earlier working for me but all f sudden it stopped working (Virualbox - host was Windows 7, Guest was OpenSuSe)

modprobe -a vboxguest vboxsf vboxvideo

then mount -t vboxsf testsf /opt/tsf (testsf was the folder in Windows C drive which was added in Virtualbox shared folder --- and /opt/tsf is the folder in OpenSuse

SQL Inner join 2 tables with multiple column conditions and update

You need to do

Update table_xpto
set column_xpto = x.xpto_New
    ,column2 = x.column2New
from table_xpto xpto
   inner join table_xptoNew xptoNew ON xpto.bla = xptoNew.Bla
where <clause where>

If you need a better answer, you can give us more information :)

Mockito: InvalidUseOfMatchersException

For my case, the exception was raised because I tried to mock a package-access method. When I changed the method access level from package to protected the exception went away. E.g. inside below Java class,

public class Foo {
    String getName(String id) {
        return mMap.get(id);
    }
}

the method String getName(String id) has to be AT LEAST protected level so that the mocking mechanism (sub-classing) can work.

Targeting only Firefox with CSS

Here is some browser hacks for targeting only the Firefox browser,

Using selector hacks.

_:-moz-tree-row(hover), .selector {}

JavaScript Hacks

var isFF = !!window.sidebar;

var isFF = 'MozAppearance' in document.documentElement.style;

var isFF = !!navigator.userAgent.match(/firefox/i);

Media Query Hacks

This is gonna work on, Firefox 3.6 and Later

@media screen and (-moz-images-in-menus:0) {}

If you need more information,Please visit browserhacks

Where to place JavaScript in an HTML file?

I would say that it depends of fact what do you planed to achieve with Javascript code:

  • if you planned to insert external your JS script(s), then the best place is in head of the page
  • if you planed to use pages on smartphones, then bottom of page, just before tag.
  • but, if you planned to make combination HTML and JS (dynamically created and populated HTML table, for example) then you must put it where you need it there.

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

File Upload in WebView

2019: This code worked for me (Tested on Androids 5 - 9).

package com.example.filechooser;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends Activity {

    // variables para manejar la subida de archivos
    private final static int FILECHOOSER_RESULTCODE = 1;
    private ValueCallback<Uri[]> mUploadMessage;

    // variable para manejar el navegador empotrado
    WebView mainWebView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // instanciamos el webview
        mainWebView = findViewById(R.id.main_web_view);

        // establecemos el cliente interno para que la navegacion no se salga de la aplicacion
        mainWebView.setWebViewClient(new MyWebViewClient());

        // establecemos el cliente chrome para seleccionar archivos
        mainWebView.setWebChromeClient(new MyWebChromeClient());

        // configuracion del webview
        mainWebView.getSettings().setJavaScriptEnabled(true);

        // cargamos la pagina
        mainWebView.loadUrl("https://example.com");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        // manejo de seleccion de archivo
        if (requestCode == FILECHOOSER_RESULTCODE) {

            if (null == mUploadMessage || intent == null || resultCode != RESULT_OK) {
                return;
            }

            Uri[] result = null;
            String dataString = intent.getDataString();

            if (dataString != null) {
                result = new Uri[]{ Uri.parse(dataString) };
            }

            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }


    // ====================
    // Web clients classes
    // ====================

    /**
     * Clase para configurar el webview
     */
    private class MyWebViewClient extends WebViewClient {

        // permite la navegacion dentro del webview
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }


    /**
     * Clase para configurar el chrome client para que nos permita seleccionar archivos
     */
    private class MyWebChromeClient extends WebChromeClient {

        // maneja la accion de seleccionar archivos
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

            // asegurar que no existan callbacks
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
            }

            mUploadMessage = filePathCallback;

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*"); // set MIME type to filter

            MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FILECHOOSER_RESULTCODE );

            return true;
        }
    }

}

Hope can help you.

Center the nav in Twitter Bootstrap

I prefer this :

<nav class="navbar">
  <div class="hidden-xs hidden-sm" style="position: absolute;left: 50%;margin-left:-56px;width:112px" id="centered-div">
    <!-- this element is on the center of the nav, visible only on -md and -lg -->
    <a></a>
  </div>

  <div class="container-fluid">
    <!-- ...things with your navbar... -->
      <div class="visible-xs visible-sm">
        <!-- this element will be hidden on -md and -lg -->
      </div>
    <!-- ...things with your navbar... -->
  </div>
</nav>

The element is perfectly centered, and will be hidden on some screen sizes (there was no place left on -xs and -sm for me for example). I get the idea from Twitter's actual navbar

Blade if(isset) is not working Laravel

I solved this using the optional() helper. Using the example here it would be:

{{ optional($usersType) }}

A more complicated example would be if, like me, say you are trying to access a property of a null object (ie. $users->type) in a view that is using old() helper.

value="{{ old('type', optional($users)->type }}"

Important to note that the brackets go around the object variable and not the whole thing if trying to access a property of the object.

https://laravel.com/docs/5.8/helpers#method-optional

How do I convert a file path to a URL in ASP.NET

For get the left part of the URL:

?HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)
"http://localhost:1714"

For get the application (web) name:

?HttpRuntime.AppDomainAppVirtualPath
"/"

With this, you are available to add your relative path after that obtaining the complete URL.

Converting string to title case

Use ToLower() first, than CultureInfo.CurrentCulture.TextInfo.ToTitleCase on the result to get the correct output.

    //---------------------------------------------------------------
    // Get title case of a string (every word with leading upper case,
    //                             the rest is lower case)
    //    i.e: ABCD EFG -> Abcd Efg,
    //         john doe -> John Doe,
    //         miXEd CaSING - > Mixed Casing
    //---------------------------------------------------------------
    public static string ToTitleCase(string str)
    {
        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
    }

Hide Show content-list with only CSS, no javascript used

This is what I've used recently.

CSS

div#tabs p{display:none;}

div#tabs p.tab1:target {display:block;}
div#tabs p.tab2:target {display:block;}
div#tabs p.tab3:target {display:block;}

HTML

<div id='tabs'>
  <h2 class="nav-tab-wrapper">
    <a href="#tab1" class="nav-tab tab1">Pages</a>
    <a href="#tab2" class="nav-tab nav-tab-active tab2">Email</a>
    <a href="#tab3" class="nav-tab tab3">Support</a>
  </h2>

  <p id='tab1' class='tab1'>Awesome tab1 stuff</p>
  <p id='tab2' class='tab2'>Tab2 stuff</p>
  <p id='tab3' class='tab3'>Tab3 stuff</p>

</div>

https://jsfiddle.net/hoq0djwc/1/

Hope it helps somewhere.

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

They both convert a String to a double value but wherease the parseDouble() method returns the primitive double value, the valueOf() method further converts the primitive double to a Double wrapper class object which contains the primitive double value.

The conversion from String to primitive double may throw NFE(NumberFormatException) if the value in String is not convertible into a primitive double.

How do I get the resource id of an image if I know its name?

You can also try this:

try {
    Class res = R.drawable.class;
    Field field = res.getField("drawableName");
    int drawableId = field.getInt(null);
}
catch (Exception e) {
    Log.e("MyTag", "Failure to get drawable id.", e);
}

I have copied this source codes from below URL. Based on tests done in this page, it is 5 times faster than getIdentifier(). I also found it more handy and easy to use. Hope it helps you as well.

Link: Dynamically Retrieving Resources in Android

How to get row number in dataframe in Pandas?

To get all indices that matches 'Smith'

>>> df[df['LastName'] == 'Smith'].index
Int64Index([1], dtype='int64')

or as a numpy array

>>> df[df['LastName'] == 'Smith'].index.to_numpy()  # .values on older versions
array([1])

or if there is only one and you want the integer, you can subset

>>> df[df['LastName'] == 'Smith'].index[0]
1

You could use the same boolean expressions with .loc, but it is not needed unless you also want to select a certain column, which is redundant when you only want the row number/index.

What does "restore purchases" in In-App purchases mean?

Is it as optional functionality.

If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.

If you will provide restore mechanism then your purchase manager will see restored transaction.

If app should distinguish this options then you should provide functionality for restoring previously purchased products.

Compare two Timestamp in java

Just convert the timestamp in millisec representation. Use getTime() method.

Linq Syntax - Selecting multiple columns

As the other answers have indicated, you need to use an anonymous type.

As far as syntax is concerned, I personally far prefer method chaining. The method chaining equivalent would be:-

var employee = _db.EMPLOYEEs
    .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)
    .Select(x => new { x.EMAIL, x.ID });

AFAIK, the declarative LINQ syntax is converted to a method call chain similar to this when it is compiled.

UPDATE

If you want the entire object, then you just have to omit the call to Select(), i.e.

var employee = _db.EMPLOYEEs
    .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo);

Export Postgresql table data using pgAdmin

In the pgAdmin4, Right click on table select backup like this

enter image description here

After that into the backup dialog there is Dump options tab into that there is section queries you can select Use Insert Commands which include all insert queries as well in the backup.

enter image description here

Google Chrome Full Black Screen

You didn't mention anything about the environment you're running. This problem occurs on VirtualBox when running on Windows 10. One thing you can try is disabling 3D Acceleration on your VM, this is a known issue.

https://www.virtualbox.org/ticket/14985

use std::fill to populate vector with increasing numbers

Speaking of boost:

auto ivec = boost::copy_range<std::vector<int>>(boost::irange(5, 10));

Easiest way to toggle 2 classes in jQuery

Your onClick request:

<span class="A" onclick="var state = this.className.indexOf('A') > -1; $(this).toggleClass('A', !state).toggleClass('B', state);">Click Me</span>

Try it: https://jsfiddle.net/v15q6b5y/


Just the JS à la jQuery:

$('.selector').toggleClass('A', !state).toggleClass('B', state);

How to set cursor position in EditText?

Let editText2 is your second EditText view .then put following piece of code in onResume()

editText2.setFocusableInTouchMode(true);
editText2.requestFocus();

or put

<requestFocus />

in your xml layout of the second EditText view.

Are there benefits of passing by pointer over passing by reference in C++?

I like the reasoning by an article from "cplusplus.com:"

  1. Pass by value when the function does not want to modify the parameter and the value is easy to copy (ints, doubles, char, bool, etc... simple types. std::string, std::vector, and all other STL containers are NOT simple types.)

  2. Pass by const pointer when the value is expensive to copy AND the function does not want to modify the value pointed to AND NULL is a valid, expected value that the function handles.

  3. Pass by non-const pointer when the value is expensive to copy AND the function wants to modify the value pointed to AND NULL is a valid, expected value that the function handles.

  4. Pass by const reference when the value is expensive to copy AND the function does not want to modify the value referred to AND NULL would not be a valid value if a pointer was used instead.

  5. Pass by non-cont reference when the value is expensive to copy AND the function wants to modify the value referred to AND NULL would not be a valid value if a pointer was used instead.

  6. When writing template functions, there isn't a clear-cut answer because there are a few tradeoffs to consider that are beyond the scope of this discussion, but suffice it to say that most template functions take their parameters by value or (const) reference, however because iterator syntax is similar to that of pointers (asterisk to "dereference"), any template function that expects iterators as arguments will also by default accept pointers as well (and not check for NULL since the NULL iterator concept has a different syntax).

http://www.cplusplus.com/articles/z6vU7k9E/

What I take from this is that the major difference between choosing to use a pointer or reference parameter is if NULL is an acceptable value. That's it.

Whether the value is input, output, modifiable etc. should be in the documentation / comments about the function, after all.