Programs & Examples On #Imagelist

Go: panic: runtime error: invalid memory address or nil pointer dereference

According to the docs for func (*Client) Do:

"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.

When err is nil, resp always contains a non-nil resp.Body."

Then looking at this code:

res, err := client.Do(req)
defer res.Body.Close()

if err != nil {
    return nil, err
}

I'm guessing that err is not nil. You're accessing the .Close() method on res.Body before you check for the err.

The defer only defers the function call. The field and method are accessed immediately.


So instead, try checking the error immediately.

res, err := client.Do(req)

if err != nil {
    return nil, err
}
defer res.Body.Close()

How to find the array index with a value?

You can use indexOf:

var imageList = [100,200,300,400,500];
var index = imageList.indexOf(200); // 1

You will get -1 if it cannot find a value in the array.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Just encase someone else ran into the issues I did I was using Response.End() an async trigger button

<asp:AsyncPostBackTrigger ControlID="btn_login" />

in an update panel. I switched to regular post back not the best but it worked.

<asp:PostBackTrigger ControlID="btn_login" />. 

Since I was only redirecting on the page this was a viable solution.

AngularJS. How to call controller function from outside of controller component

I am an Ionic framework user and the one I found that would consistently provide the current controller's $scope is:

angular.element(document.querySelector('ion-view[nav-view="active"]')).scope()

I suspect this can be modified to fit most scenarios regardless of framework (or not) by finding the query that will target the specific DOM element(s) that are available only during a given controller instance.

Can anonymous class implement interface?

Anonymous types can implement interfaces via a dynamic proxy.

I wrote an extension method on GitHub and a blog post http://wblo.gs/feE to support this scenario.

The method can be used like this:

class Program
{
    static void Main(string[] args)
    {
        var developer = new { Name = "Jason Bowers" };

        PrintDeveloperName(developer.DuckCast<IDeveloper>());

        Console.ReadKey();
    }

    private static void PrintDeveloperName(IDeveloper developer)
    {
        Console.WriteLine(developer.Name);
    }
}

public interface IDeveloper
{
    string Name { get; }
}

Why is my Button text forced to ALL CAPS on Lollipop?

Add android:textAllCaps="false" in <Button> tag that's it.

Does Typescript support the ?. operator? (And, what's it called?)

The Elvis (?.) Optional Chaining Operator is supported in TypeScript 3.7.

You can use it to check for null values: cats?.miows returns null if cats is null or undefined.

You can also use it for optional method calling: cats.doMiow?.(5) will call doMiow if it exists.

Property access is also possible: cats?.['miows'].

Reference: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/

The server principal is not able to access the database under the current security context in SQL Server MS 2012

SQL Logins are defined at the server level, and must be mapped to Users in specific databases.

In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.

Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.

enter image description here

These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:

USE {database};
ALTER USER {user} WITH login = {login}

You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.

Python recursive folder read

I've found the following to be the easiest

from glob import glob
import os

files = [f for f in glob('rootdir/**', recursive=True) if os.path.isfile(f)]

Using glob('some/path/**', recursive=True) gets all files, but also includes directory names. Adding the if os.path.isfile(f) condition filters this list to existing files only

JavaFX 2.1 TableView refresh items

JavaFX8

I'm adding new Item by a DialogBox. Here is my code.

ObservableList<Area> area = FXCollections.observableArrayList();

At initialize() or setApp()

this.areaTable.setItems(getAreaData());

getAreaData()

private ObservableList<Area> getAreaData() {
    try {
        area = AreaDAO.searchEmployees(); // To inform ObservableList
        return area;
    } catch (ClassNotFoundException | SQLException e) {
        System.out.println("Error: " + e);
        return null;
    }
}

Add by dialog box.

@FXML
private void handleNewArea() {
    Area tempArea = new Area();
    boolean okClicked = showAreaDialog(tempArea);
    if (okClicked) {
        addNewArea(tempArea);
        this.area.add(tempArea); // To inform ObservableList
    }

}

Area is an ordinary JavaFX POJO. Hope this helps someone.

How to compare two files in Notepad++ v6.6.8

I give the answer because I need to compare 2 files in notepad++ and there is no option available.

So first enable the plugin manager as asked by question here, Then follow this step to compare 2 files which is free in this software.

1.open notepad++, go to

Plugin -> Plugin Manager -> Show Plugin Manager

2.Show the available plugin list, choose Compare and Install

3.Restart Notepad++.

http://www.technicaloverload.com/compare-two-files-using-notepad/

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

Sticky Header after scrolling down

I used jQuery .scroll() function to track the event of the toolbar scroll value using scrollTop. I then used a conditional to determine if it was greater than the value on what I wanted to replace. In the below example it was "Results". If the value was true then the results-label added a class 'fixedSimilarLabel' and the new styles were then taken into account.

    $('.toolbar').scroll(function (e) {
//console.info(e.currentTarget.scrollTop);
    if (e.currentTarget.scrollTop >= 130) {
        $('.results-label').addClass('fixedSimilarLabel');
    }
    else {      
        $('.results-label').removeClass('fixedSimilarLabel');
    }
});

http://codepen.io/franklynroth/pen/pjEzeK

Get error message if ModelState.IsValid fails?

If Modal State is not Valid & the error cannot be seen on screen because your control is in collapsed accordion, then you can return the HttpStatusCode so that the actual error message is shown if you do F12. Also you can log this error to ELMAH error log. Below is the code

if (!ModelState.IsValid)
{
              var message = string.Join(" | ", ModelState.Values
                                            .SelectMany(v => v.Errors)
                                            .Select(e => e.ErrorMessage));

                //Log This exception to ELMAH:
                Exception exception = new Exception(message.ToString());
                Elmah.ErrorSignal.FromCurrentContext().Raise(exception);

                //Return Status Code:
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}

But please note that this code will log all validation errors. So this should be used only when such situation arises where you cannot see the errors on screen.

Notepad++ add to every line

  1. Move your cursor to the start of the first line
  2. Hold down Alt + Shift and use the cursor down key to extend the selection to the end of the block

This allows you to type on every line simultaneously.

I found the solution above here.

I think this is much easier than using regex.

When a 'blur' event occurs, how can I find out which element focus went *to*?

I solved it eventually with a timeout on the onblur event (thanks to the advice of a friend who is not StackOverflow):

<input id="myInput" onblur="setTimeout(function() {alert(clickSrc);},200);"></input>
<span onclick="clickSrc='mySpan';" id="mySpan">Hello World</span>

Works both in FF and IE.

How do you extract IP addresses from files using a regex in a linux shell?

This works fine for me in access logs.

cat access_log | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'

Let's break it part by part.

  • [0-9]{1,3} means one to three occurrences of the range mentioned in []. In this case it is 0-9. so it matches patterns like 10 or 183.

  • Followed by a '.'. We will need to escape this as '.' is a meta character and has special meaning for the shell.

So now we are at patterns like '123.' '12.' etc.

  • This pattern repeats itself three times(with the '.'). So we enclose it in brackets. ([0-9]{1,3}\.){3}

  • And lastly the pattern repeats itself but this time without the '.'. That is why we kept it separately in the 3rd step. [0-9]{1,3}

If the ips are at the beginning of each line as in my case use:

egrep -o '^([0-9]{1,3}\.){3}[0-9]{1,3}'

where '^' is an anchor that tells to search at the start of a line.

Bootstrap $('#myModal').modal('show') is not working

Try This without paramater

$('#myModal').modal();

it should be worked

Solving "adb server version doesn't match this client" error

One possible reason for the occurrence of this error is due to the difference in adb versions in the development machine and the connected connected device/emulator being used for debugging.

So resolution is:

  1. Firstly disconnect device/emulator.
  2. Run on terminal/command prompt following commands:

    adb kill-server
    adb start-server
    

This will start the adb successfully. Now you can connect device. Hope it helps.

Automatically enter SSH password with script

Use public key authentication: https://help.ubuntu.com/community/SSH/OpenSSH/Keys

In the source host run this only once:

ssh-keygen -t rsa # ENTER to every field
ssh-copy-id myname@somehost

That's all, after that you'll be able to do ssh without password.

Android: converting String to int

Change

try {
    myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {

to

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {

Get names of all files from a folder with Ruby

One simple way could be:

dir = './' # desired directory
files = Dir.glob(File.join(dir, '**', '*')).select{|file| File.file?(file)}

files.each do |f|
    puts f
end

Laravel 5 not finding css files

Use this to add assets like css, javascript, images.. into blade file.

FOR CSS,

<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" >

OR

<link href="{{ URL::asset('css/app.css') }}" rel="stylesheet" type="text/css" >

FOR JS,

<script type="text/javascript" src="{{ asset('js/custom.js') }}"></script>

OR

 <script type="text/javascript" src="{{ URL::asset('js/custom.js') }}"></script>

FOR IMAGES,

{{ asset('img/photo.jpg'); }}

Here is the DOC

Alternatively, if you pulled the composer package illuminate/html which was come as default in laravel 4.2 then you can use like below, In laravel 5. you have to manually pull the package.

{{ HTML::style('css/style.css') }}

Here is an Example.

Negative matching using grep (match lines that do not contain foo)

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.

find /home/baumerf/public_html/ -mmin -60 -not -name error_log

If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

find /home/baumerf/public_html/ -mmin -60 -not -name \*.log

Date vs DateTime

Unfortunately, not in the .Net BCL. Dates are usually represented as a DateTime object with the time set to midnight.

As you can guess, this means that you have all the attendant timezone issues around it, even though for a Date object you'd want absolutely no timezone handling.

How do you get the footer to stay at the bottom of a Web page?

You could use position: absolute following to put the footer at the bottom of the page, but then make sure your 2 columns have the appropriate margin-bottom so that they never get occluded by the footer.

#footer {
    position: absolute;
    bottom: 0px;
    width: 100%;
}
#content, #sidebar { 
    margin-bottom: 5em; 
}

Append data to a POST NSURLRequest

If you don't wish to use 3rd party classes then the following is how you set the post body...

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                             delegate:self];

Simply append your key/value pair to the post string

How do you read a file into a list in Python?

hdl = open("C:/name/MyDocuments/numbers", 'r')
milist = hdl.readlines()
hdl.close()

How do I pass along variables with XMLHTTPRequest

How about?

function callHttpService(url, params){
  // Assume params contains key/value request params
  let queryStrings = '';

  for(let key in params){
      queryStrings += `${key}=${params[key]}&`
    } 
 const fullUrl = `${url}?queryStrings`

  //make http request with fullUrl
}

Proper way to assert type of variable in Python

The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

def my_print(text, begin, end):
    "Print 'text' in UPPER between 'begin' and 'end' in lower"
    try:
      print begin.lower() + text.upper() + end.lower()
    except (AttributeError, TypeError):
      raise AssertionError('Input variables should be strings')

This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)

Command line to remove an environment variable from the OS level configuration

From PowerShell you can use the .NET [System.Environment]::SetEnvironmentVariable() method:

  • To remove a user environment variable named FOO:

    [Environment]::SetEnvironmentVariable('FOO', $null, 'User')
    

Note that $null is used to better signal the intent to remove the variable, though technically it is effectively the same as passing '' in this case.

  • To remove a system (machine-level) environment variable named FOO - requires elevation (must be run as administrator):

    [Environment]::SetEnvironmentVariable('FOO', $null, 'Machine')
    

Aside from faster execution, the advantage over the reg.exe-based method is that other applications are notified of the change, via a WM_SETTINGCHANGE message (though not all applications listen to that message).

force browsers to get latest js and css files in asp.net application

Easy and smart way to implement css versioning in .net application by below concept.. no need to write back-end code.

<link href="<%="../../App_Themes/Base/css/main.css?v="+ DateTime.Now.ToString("yyyyMMddhhmmss") +""%>" rel="stylesheet" />

JavaScript - Get minutes between two dates

Subtracting 2 Date objects gives you the difference in milliseconds, e.g.:

var diff = Math.abs(new Date('2011/10/09 12:00') - new Date('2011/10/09 00:00'));

Math.abs is used to be able to use the absolute difference (so new Date('2011/10/09 00:00') - new Date('2011/10/09 12:00') gives the same result).

Dividing the result by 1000 gives you the number of seconds. Dividing that by 60 gives you the number of minutes. To round to whole minutes, use Math.floor or Math.ceil:

var minutes = Math.floor((diff/1000)/60);

In this example the result will be 720

How can I add new array elements at the beginning of an array in Javascript?

Quick Cheatsheet:

The terms shift/unshift and push/pop can be a bit confusing, at least to folks who may not be familiar with programming in C.

If you are not familiar with the lingo, here is a quick translation of alternate terms, which may be easier to remember:

* array_unshift()  -  (aka Prepend ;; InsertBefore ;; InsertAtBegin )     
* array_shift()    -  (aka UnPrepend ;; RemoveBefore  ;; RemoveFromBegin )

* array_push()     -  (aka Append ;; InsertAfter   ;; InsertAtEnd )     
* array_pop()      -  (aka UnAppend ;; RemoveAfter   ;; RemoveFromEnd ) 

How to hide iOS status bar

Add following line in viewdidload

  [[UIApplication sharedApplication] setStatusBarHidden:YES
                                        withAnimation:UIStatusBarAnimationFade];

and add new method

  - (BOOL)prefersStatusBarHidden {
          return YES;
  }

also change info.plist file View controller-based status bar appearance" = NO

its works for me

How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

How can you test if an object has a specific property?

You could check with:

($Member.PropertyNames -contains "Name") this will check for the Named property

django import error - No module named core.management

This error usually occurs when django is not installed. If you have already installed django but still getting the same error, then you must be working in separate virtual environment. You need to install django in your virtual environmnent as well. When you are in shell of virtual machine simply do this:

pip install django

It is because virtual machine has separate file system, it doesn't recognize django even if it is installed on your system.

How to read the RGB value of a given pixel in Python?

There's a really good article on wiki.wxpython.org entitled Working With Images. The article mentions the possiblity of using wxWidgets (wxImage), PIL or PythonMagick. Personally, I've used PIL and wxWidgets and both make image manipulation fairly easy.

How to get the jQuery $.ajax error response text?

Try:

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

Counting Chars in EditText Changed Listener

TextWatcher maritalStatusTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        try {
            if (charSequence.length()==0){
                topMaritalStatus.setVisibility(View.GONE);
            }else{
                topMaritalStatus.setVisibility(View.VISIBLE);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
};

How to run a class from Jar which is not the Main-Class in its Manifest file

Apart from calling java -jar myjar.jar com.mycompany.Myclass, you can also make the main class in your Manifest a Dispatcher class.

Example:

public class Dispatcher{

    private static final Map<String, Class<?>> ENTRY_POINTS =
        new HashMap<String, Class<?>>();
    static{
        ENTRY_POINTS.put("foo", Foo.class);
        ENTRY_POINTS.put("bar", Bar.class);
        ENTRY_POINTS.put("baz", Baz.class);
    }

    public static void main(final String[] args) throws Exception{

        if(args.length < 1){
            // throw exception, not enough args
        }
        final Class<?> entryPoint = ENTRY_POINTS.get(args[0]);
        if(entryPoint==null){
            // throw exception, entry point doesn't exist
        }
        final String[] argsCopy =
            args.length > 1
                ? Arrays.copyOfRange(args, 1, args.length)
                : new String[0];
        entryPoint.getMethod("main", String[].class).invoke(null,
            (Object) argsCopy);

    }
}

How to use Selenium with Python?

You just need to get selenium package imported, that you can do from command prompt using the command

pip install selenium

When you have to use it in any IDE just import this package, no other documentation required to be imported

For Eg :

import selenium 
print(selenium.__filepath__)

This is just a general command you may use in starting to check the filepath of selenium

Bootstrap: Position of dropdown menu relative to navbar item

This is the effect that we're trying to achieve:

A right-aligned menu

The classes that need to be applied changed with the release of Bootstrap 3.1.0 and again with the release of Bootstrap 4. If one of the below solutions doesn't seem to be working double check the version number of Bootstrap that you're importing and try a different one.

Bootstrap 3

Before v3.1.0

You can use the pull-right class to line the right hand side of the menu up with the caret:

<li class="dropdown">
  <a class="dropdown-toggle" href="#">Link</a>
  <ul class="dropdown-menu pull-right">
     <li>...</li>
  </ul>
</li>

Fiddle: http://jsfiddle.net/joeczucha/ewzafdju/

After v3.1.0

As of v3.1.0, we've deprecated .pull-right on dropdown menus. To right-align a menu, use .dropdown-menu-right. Right-aligned nav components in the navbar use a mixin version of this class to automatically align the menu. To override it, use .dropdown-menu-left.

You can use the dropdown-right class to line the right hand side of the menu up with the caret:

<li class="dropdown">
  <a class="dropdown-toggle" href="#">Link</a>
  <ul class="dropdown-menu dropdown-menu-right">
     <li>...</li>
  </ul>
</li>

Fiddle: http://jsfiddle.net/joeczucha/1nrLafxc/

Bootstrap 4

The class for Bootstrap 4 are the same as Bootstrap > 3.1.0, just watch out as the rest of the surrounding markup has changed a little:

<li class="nav-item dropdown">
  <a class="nav-link dropdown-toggle" href="#">
    Link
  </a>
  <div class="dropdown-menu dropdown-menu-right">
    <a class="dropdown-item" href="#">...</a>
  </div>
</li>

Fiddle: https://jsfiddle.net/joeczucha/f8h2tLoc/

BLOB to String, SQL Server

Can you try this:

select convert(nvarchar(max),convert(varbinary(max),blob_column)) from table_name

Javascript reduce() on Object

Try this one. It will sort numbers from other variables.

const obj = {
   a: 1,
   b: 2,
   c: 3
};
const result = Object.keys(obj)
.reduce((acc, rec) => typeof obj[rec] === "number" ? acc.concat([obj[rec]]) : acc, [])
.reduce((acc, rec) => acc + rec)

PHP upload image

Change function file_get_content() in your code to file_get_contents() . You are missing 's' at the end of function name. That is why it is giving undefined function error.

file_get_contents()

Remove last unnecessary comma after $image filed in line

"INSERT INTO content VALUES         ('','','','','','','','','','$image_name','$image',)

There is an error in XML document (1, 41)

Agreed with the answer from sll, but experienced another hurdle which was having specified a namespace in the attributes, when receiving the return xml that namespace wasn't included and thus failed finding the class.

i had to find a workaround to specifying the namespace in the attribute and it worked.

ie.

[Serializable()]
    [XmlRoot("Patient", Namespace = "http://www.xxxx.org/TargetNamespace")]
    public class Patient

generated

<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xxxx.org/TargetNamespace">

but I had to change it to

[Serializable()]
[XmlRoot("Patient")]
public class Patient

which generated to

<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

This solved my problem, hope it helps someone else.

How to check if bootstrap modal is open, so I can use jquery validate?

Bootstrap 2 , 3 Check is any modal open in page :

if($('.modal.in').length)

compatible version Bootstrap 2 , 3 , 4+

if($('.modal.in, .modal.show').length)

Only Bootstrap 4+

if($('.modal.show').length)

How to iterate over associative arrays in Bash

The keys are accessed using an exclamation point: ${!array[@]}, the values are accessed using ${array[@]}.

You can iterate over the key/value pairs like this:

for i in "${!array[@]}"
do
  echo "key  : $i"
  echo "value: ${array[$i]}"
done

Note the use of quotes around the variable in the for statement (plus the use of @ instead of *). This is necessary in case any keys include spaces.

The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.

creating json object with variables

You're referencing a DOM element when doing something like $('#lastName'). That's an element with id attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject is in the same scope as the variable declarations) -

var formObject = {
    formObject: [
        {
            firstName:firstName,  // no need to quote variable names
            lastName:lastName
        },
        {
            phoneNumber:phoneNumber,
            address:address
        }
    ]
};

This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

System.Collections.Generic.List does not contain a definition for 'Select'

I had this issue , When calling Generic.List like:

mylist.Select( selectFunc )

Where selectFunc is defined as Expression<Func<T, List<string>>>. Simply changed "mylist" to be a IQuerable instead of List then it allowed me to use .Select.

iOS 7.0 No code signing identities found

you need not to delete all your profiles.I had same issue and fixed it by installing the missing certificates. You might forgot to install the required certificate for the provisioning profile you are using for code signing.

  • make sure that you installed desired certificates(development/distribution) into keychain for the code-signing provision profile(development/distribution).

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

I implemented a nested grid view and i faced the same problem .I have used LinkButton instead of image button like this:

before i had a column like this:

<asp:TemplateField ItemStyle-Width="9">
  <ItemTemplate>
 <asp:ImageButton ID="ImgBtn" ImageUrl="Include/images/gridplus.gif" CommandName="Expand"
                        runat="server" />
  </ItemTemplate>
</asp:TemplateField>

I have replaced like this.

<asp:TemplateField>
<ItemTemplate>
     <asp:LinkButton  CommandName="Expand" ID="lnkBtn"  runat="server" ><asp:Image  ID="Img"  runat="server" ImageUrl="~/Images/app/plus.gif" /></asp:LinkButton>
      </ItemTemplate>
</asp:TemplateField> 

How to understand nil vs. empty vs. blank in Ruby

Quick tip: !obj.blank? == obj.present?

Can be handy/easier on the eyes in some expressions

Setting active profile and config location from command line in spring boot

you can use the following command line:

java -jar -Dspring.profiles.active=[yourProfileName] target/[yourJar].jar

Converting a year from 4 digit to 2 digit and back again in C#

Why not have the original drop down on the page be a 2 digit value only? Credit cards only cover a small span when looking at the year especially if the CC vendor only takes in 2 digits already.

How to compute the sum and average of elements in an array?

You can also use lodash, _.sum(array) and _.mean(array) in Math part (also have other convenient stuff).

_.sum([4, 2, 8, 6]);
// => 20
_.mean([4, 2, 8, 6]);
// => 5

Iterator over HashMap in Java

  1. Using EntrySet() and for each loop

       for(Map.Entry<String, String> entry: hashMap.entrySet()) {
         System.out.println("Key Of map = "+ entry.getKey() + 
                          " , value of map = " + entry.getValue() );
     }
    
  2. Using keyset() and for each loop

             for(String key : hashMap.keySet()) {
                System.out.println("Key Of map = "+ key + " , 
                          value of map = " + hashMap.get(key) );
               }
    
  3. Using EntrySet() and java Iterator

          for(String key : hashMap.keySet()) {
            System.out.println("Key Of map = "+ key + " , 
                          value of map = " + hashMap.get(key) );
            }
    
  4. Using keyset() and java Iterator

         Iterator<String> keysIterator = keySet.iterator();
        while (keysIterator.hasNext()) {
            String key = keysIterator.next();
            System.out.println("Key Of map = "+ key + " , value of map = " + hashMap.get(key) );
       }
    

Reference : How to iterate over Map or HashMap in java

SVN Repository on Google Drive or DropBox

I made my own subversion repository on my Ubuntu One folder. Then, I imported the files to the repository using svn+ssh and my user account password.

When I want to do a checkout, I just checkout from my Ubuntu One folder. The commit process its analogue.

You must setup Ubutnu One on the devices that you want to grant access, then checkout the project from this folder to a temporary folder to edit it.

In my case, I use a folder in the Ubuntu One file-system, so I have the repository and my develop-folder in Ubuntu One.

Where is svn.exe in my machine?

TortoiseSVN doesn't use svn.exe it has SVN library compiled in. If you need to run your own tasks you would have to install stand alone subversion client. You either from Cygwin [http://cygwin.com ] or get a native version from http://subversion.apache.org/packages.html#windows

PHPMyAdmin Default login password

If it was installed with plesk (not sure if it's just that, or on the phpmyadmin side: It changes the root user to admin.

Commit history on remote repository

I don't believe this is possible. I believe you have to clone that remote repo locally and perform git fetch on it before you can issue a git log against it.

Sequel Pro Alternative for Windows

You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.

But if you want alternative suggestions, here are a few that I know of and have used:

MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.

Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.

(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)

Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

Scenario

I was getting SSLHandshake exceptions on devices running versions of Android earlier than Android 5.0. In my use case I also wanted to create a TrustManager to trust my client certificate.

I implemented NoSSLv3SocketFactory and NoSSLv3Factory to remove SSLv3 from my client's list of supported protocols but I could get neither of these solutions to work.

Some things I learned:

  • On devices older than Android 5.0 TLSv1.1 and TLSv1.2 protocols are not enabled by default.
  • SSLv3 protocol is not disabled by default on devices older than Android 5.0.
  • SSLv3 is not a secure protocol and it is therefore desirable to remove it from our client's list of supported protocols before a connection is made.

What worked for me

Allow Android's security Provider to update when starting your app.

The default Provider before 5.0+ does not disable SSLv3. Provided you have access to Google Play services it is relatively straightforward to patch Android's security Provider from your app.

private void updateAndroidSecurityProvider(Activity callingActivity) {
    try {
        ProviderInstaller.installIfNeeded(this);
    } catch (GooglePlayServicesRepairableException e) {
        // Thrown when Google Play Services is not installed, up-to-date, or enabled
        // Show dialog to allow users to install, update, or otherwise enable Google Play services.
        GooglePlayServicesUtil.getErrorDialog(e.getConnectionStatusCode(), callingActivity, 0);
    } catch (GooglePlayServicesNotAvailableException e) {
        Log.e("SecurityException", "Google Play Services not available.");
    }
}

If you now create your OkHttpClient or HttpURLConnection TLSv1.1 and TLSv1.2 should be available as protocols and SSLv3 should be removed. If the client/connection (or more specifically it's SSLContext) was initialised before calling ProviderInstaller.installIfNeeded(...) then it will need to be recreated.

Don't forget to add the following dependency (latest version found here):

compile 'com.google.android.gms:play-services-auth:16.0.1'

Sources:

Aside

I didn't need to explicitly set which cipher algorithms my client should use but I found a SO post recommending those considered most secure at the time of writing: Which Cipher Suites to enable for SSL Socket?

3D Plotting from X, Y, Z Data, Excel or other Tools

I ended up using matplotlib :)

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
x = [1000,1000,1000,1000,1000,5000,5000,5000,5000,5000,10000,10000,10000,10000,10000]
y = [13,21,29,37,45,13,21,29,37,45,13,21,29,37,45]
z = [75.2,79.21,80.02,81.2,81.62,84.79,87.38,87.9,88.54,88.56,88.34,89.66,90.11,90.79,90.87]
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)
plt.show()

Chrome ignores autocomplete="off"

Some end 2020 Update. I tried all the old solutions from different sites. None of them worked! :-(
Then I found this:
Use

<input type="search"/> 

and the autocomplete is gone!

Success with Chrome 86, FireFox, Edge 87.

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

Force browser to refresh css, javascript, etc

General solution

Pressing Ctrl + F5 (or Ctrl + Shift + R) to force a cache reload. I believe Macs use Cmd + Shift + R.

PHP

In PHP, you can disable the cache by setting the expiration date to a time in the past with headers:

header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

Chrome

Chrome's cache can be disabled by opening the developer tools with F12, clicking on the gear icon in the lower right corner and selecting Disable cache in the settings dialog, like this:

enter image description here
Image taken from this answer.

Firefox

Type about:config into the URL bar then find the entry titled network.http.use-cache. Set this to false.

Check if a class is derived from a generic class

(Reposted due to a massive rewrite)

JaredPar's code answer is fantastic, but I have a tip that would make it unnecessary if your generic types are not based on value type parameters. I was hung up on why the "is" operator would not work, so I have also documented the results of my experimentation for future reference. Please enhance this answer to further enhance its clarity.

TIP:

If you make certain that your GenericClass implementation inherits from an abstract non-generic base class such as GenericClassBase, you could ask the same question without any trouble at all like this:

typeof(Test).IsSubclassOf(typeof(GenericClassBase))

IsSubclassOf()

My testing indicates that IsSubclassOf() does not work on parameterless generic types such as

typeof(GenericClass<>)

whereas it will work with

typeof(GenericClass<SomeType>)

Therefore the following code will work for any derivation of GenericClass<>, assuming you are willing to test based on SomeType:

typeof(Test).IsSubclassOf(typeof(GenericClass<SomeType>))

The only time I can imagine that you would want to test by GenericClass<> is in a plug-in framework scenario.


Thoughts on the "is" operator

At design-time C# does not allow the use of parameterless generics because they are essentially not a complete CLR type at that point. Therefore, you must declare generic variables with parameters, and that is why the "is" operator is so powerful for working with objects. Incidentally, the "is" operator also can not evaluate parameterless generic types.

The "is" operator will test the entire inheritance chain, including interfaces.

So, given an instance of any object, the following method will do the trick:

bool IsTypeof<T>(object t)
{
    return (t is T);
}

This is sort of redundant, but I figured I would go ahead and visualize it for everybody.

Given

var t = new Test();

The following lines of code would return true:

bool test1 = IsTypeof<GenericInterface<SomeType>>(t);

bool test2 = IsTypeof<GenericClass<SomeType>>(t);

bool test3 = IsTypeof<Test>(t);

On the other hand, if you want something specific to GenericClass, you could make it more specific, I suppose, like this:

bool IsTypeofGenericClass<SomeType>(object t)
{
    return (t is GenericClass<SomeType>);
}

Then you would test like this:

bool test1 = IsTypeofGenericClass<SomeType>(t);

iOS: how to perform a HTTP POST request?

NOTE: Pure Swift 3 (Xcode 8) example: Please try out the following sample code. It is the simple example of dataTask function of URLSession.

func simpleDataRequest() {

        //Get the url from url string
        let url:URL = URL(string: "YOUR URL STRING")!

        //Get the session instance
        let session = URLSession.shared

        //Create Mutable url request
        var request = URLRequest(url: url as URL)

        //Set the http method type
        request.httpMethod = "POST"

        //Set the cache policy
        request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData

        //Post parameter
        let paramString = "key=value"

        //Set the post param as the request body
        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest) {
            (data, response, error) in

            guard let _:Data = data as Data?, let _:URLResponse = response  , error == nil else {

                //Oops! Error occured.
                print("error")
                return
            }

            //Get the raw response string
            let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))

            //Print the response
            print(dataString!)

        }

        //resume the task
        task.resume()

    }

COPY with docker but with exclusion

For those who can't use a .dockerignore file (e.g. if you need the file in one COPY but not another):

Yes, but you need multiple COPY instructions. Specifically, you need a COPY for each letter in the filename you wish to exclude.

COPY [^n]*    # All files that don't start with 'n'
COPY n[^o]*   # All files that start with 'n', but not 'no'
COPY no[^d]*  # All files that start with 'no', but not 'nod'

Continuing until you have the full file name, or just the prefix you're reasonably sure won't have any other files.

How can I open Java .class files in a human-readable way?

If the class file you want to look into is open source, you should not decompile it, but instead attach the source files directly into your IDE. that way, you can just view the code of some library class as if it were your own

Can we instantiate an abstract class?

Technical Answer

Abstract classes cannot be instantiated - this is by definition and design.

From the JLS, Chapter 8. Classes:

A named class may be declared abstract (§8.1.1.1) and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses.

From JSE 6 java doc for Classes.newInstance():

InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.

You can, of course, instantiate a concrete subclass of an abstract class (including an anonymous subclass) and also carry out a typecast of an object reference to an abstract type.

A Different Angle On This - Teamplay & Social Intelligence:

This sort of technical misunderstanding happens frequently in the real world when we deal with complex technologies and legalistic specifications.

"People Skills" can be more important here than "Technical Skills". If competitively and aggressively trying to prove your side of the argument, then you could be theoretically right, but you could also do more damage in having a fight / damaging "face" / creating an enemy than it is worth. Be reconciliatory and understanding in resolving your differences. Who knows - maybe you're "both right" but working off slightly different meanings for terms??

Who knows - though not likely, it is possible the interviewer deliberately introduced a small conflict/misunderstanding to put you into a challenging situation and see how you behave emotionally and socially. Be gracious and constructive with colleagues, follow advice from seniors, and follow through after the interview to resolve any challenge/misunderstanding - via email or phone call. Shows you're motivated and detail-oriented.

How can I count text lines inside an DOM element? Can I?

No, not reliably. There are simply too many unknown variables

  1. What OS (different DPIs, font variations, etc...)?
  2. Do they have their font-size scaled up because they are practically blind?
  3. Heck, in webkit browsers, you can actually resize textboxes to your heart's desire.

The list goes on. Someday I hope there will be such a method of reliably accomplishing this with JavaScript, but until that day comes, your out of luck.

I hate these kinds of answers and I hope someone can prove me wrong.

How to update nested state properties in React

const newState = Object.assign({}, this.state);
newState.property.nestedProperty = "new value";
this.setState(newState);

How to create a JPA query with LEFT OUTER JOIN

If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:

select a, (select b from B b where b.joinProperty = a.joinProperty) from A a

This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.

Uninstall Node.JS using Linux command line?

If you have yum you could do:

yum remove nodesource-release* nodejs

yum clean all

And after that check if its deleted:

rpm -qa 'node|npm'

Convert datetime value into string

Try this:

concat(left(datefield,10),left(timefield,8))
  • 10 char on date field based on full date yyyy-MM-dd.

  • 8 char on time field based on full time hh:mm:ss.

It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.

Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.

Copying text outside of Vim with set mouse=a enabled

You can use :set mouse& in the vim command line to enable copy/paste of text selected using the mouse. You can then simply use the middle mouse button or shiftinsert to paste it.

Boolean checking in the 'if' condition

This is more readable and good practice too.

if(!status){
//do sth
}else{
//do sth
}

What is the best way to tell if a character is a letter or number in Java without using regexes?

Compare its value. It should be between the value of 'a' and 'z', 'A' and 'Z', '0' and '9'

Shuffling a list of objects

""" to shuffle random, set random= True """

def shuffle(x,random=False):
     shuffled = []
     ma = x
     if random == True:
         rando = [ma[i] for i in np.random.randint(0,len(ma),len(ma))]
         return rando
     if random == False:
          for i in range(len(ma)):
          ave = len(ma)//3
          if i < ave:
             shuffled.append(ma[i+ave])
          else:
             shuffled.append(ma[i-ave])    
     return shuffled

Compare two files line by line and generate the difference in another file

Try

sdiff file1 file2

It ususally works much better in most cases for me. You may want to sort files prior, if order of lines is not important (e.g. some text config files).

For example,

sdiff -w 185 file1.cfg file2.cfg

Improve subplot size/spacing with many subplots in matplotlib

Try using plt.tight_layout

As a quick example:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

plt.show()

Without Tight Layout

enter image description here


With Tight Layout enter image description here

How to count the number of lines of a string in javascript

Hmm yeah... what you're doing is absolutely wrong. When you say str.split("\r\n|\r|\n") it will try to find the exact string "\r\n|\r|\n". That's where you're wrong. There's no such occurance in the whole string. What you really want is what David Hedlund suggested:

lines = str.split(/\r\n|\r|\n/);
return lines.length;

The reason is that the split method doesn't convert strings into regular expressions in JavaScript. If you want to use a regexp, use a regexp.

How to get div height to auto-adjust to background size?

There is a pure CSS solution that the other answers have missed.

The "content:" property is mostly used to insert text content into an element, but can also be used to insert image content.

.my-div:before {
    content: url("image.png");
}

This will cause the div to resize its height to the actual pixel size of the image. To resize the width too, add:

.my-div {
    display: inline-block;
}

inline conditionals in angular.js

So with Angular 1.5.1 ( had existing app dependency on some other MEAN stack dependencies is why I'm not currently using 1.6.4 )

This works for me like the OP saying {{myVar === "two" ? "it's true" : "it's false"}}

{{vm.StateName === "AA" ? "ALL" : vm.StateName}}

Proper usage of Optional.ifPresent()

Use flatMap. If a value is present, flatMap returns a sequential Stream containing only that value, otherwise returns an empty Stream. So there is no need to use ifPresent() . Example:

list.stream().map(data -> data.getSomeValue).map(this::getOptinalValue).flatMap(Optional::stream).collect(Collectors.toList());

Android Button Onclick

There are two solutions for this are :-

(1) do not put onClick in xml

(2) remove

button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
            // TODO Auto-generated method stub
    }
});

and put

public void setLogin(View v) {
    // Your code here
}

Difference between \w and \b regular expression meta characters

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Simply put: \b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".

In all flavors, the characters [a-zA-Z0-9_] are word characters. These are also matched by the short-hand character class \w. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.

\w stands for "word character", usually [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

\W is short for [^\w], the negated version of \w.

How to count how many values per level in a given factor?

One more approach would be to apply n() function which is counting the number of observations

library(dplyr)
library(magrittr)
data %>% 
  group_by(columnName) %>%
  summarise(Count = n())

How to add an object to an ArrayList in Java

Contacts.add(objt.Data(name, address, contact));

This is not a perfect way to call a constructor. The constructor is called at the time of object creation automatically. If there is no constructor java class creates its own constructor.

The correct way is:

// object creation. 
Data object1 = new Data(name, address, contact);      

// adding Data object to ArrayList object Contacts.
Contacts.add(object1);                              

Forbidden :You don't have permission to access /phpmyadmin on this server

On a fresh install on CENTOS7 I have tried the above methods (edit phpMyAdmin.conf and add Require all granted), it still does'nt work. Here is the solution : install the mod_php module :

$ sudo yum install php

then restart httpd :

$ sudo systemctl restart httpd

and voila !

How to store a datetime in MySQL with timezone info

MySQL stores DATETIME without timezone information. Let's say you store '2019-01-01 20:00:00' into a DATETIME field, when you retrieve that value you're expected to know what timezone it belongs to.

So in your case, when you store a value into a DATETIME field, make sure it is Tanzania time. Then when you get it out, it will be Tanzania time. Yay!

Now, the hairy question is: When I do an INSERT/UPDATE, how do I make sure the value is Tanzania time? Two cases:

  1. You do INSERT INTO table (dateCreated) VALUES (CURRENT_TIMESTAMP or NOW()).

  2. You do INSERT INTO table (dateCreated) VALUES (?), and specify the current time from your application code.

CASE #1

MySQL will take the current time, let's say that is '2019-01-01 20:00:00' Tanzania time. Then MySQL will convert it to UTC, which comes out to '2019-01-01 17:00:00', and store that value into the field.

So how do you get the Tanzania time, which is '20:00:00', to store into the field? It's not possible. Your code will need to expect UTC time when reading from this field.

CASE #2

It depends on what type of value you pass as ?. If you pass the string '2019-01-01 20:00:00', then good for you, that's exactly what will be stored to the DB. If you pass a Date object of some kind, then it'll depend on how the db driver interprets that Date object, and ultimate what 'YYYY-MM-DD HH:mm:ss' string it provides to MySQL for storage. The db driver's documentation should tell you.

How can I set the request header for curl?

Just use the -H parameter several times:

curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com

From io.Reader to string in Go

EDIT:

Since 1.10, strings.Builder exists. Example:

buf := new(strings.Builder)
n, err := io.Copy(buf, r)
// check errors
fmt.Println(buf.String())

OUTDATED INFORMATION BELOW

The short answer is that it it will not be efficient because converting to a string requires doing a complete copy of the byte array. Here is the proper (non-efficient) way to do what you want:

buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
s := buf.String() // Does a complete copy of the bytes in the buffer.

This copy is done as a protection mechanism. Strings are immutable. If you could convert a []byte to a string, you could change the contents of the string. However, go allows you to disable the type safety mechanisms using the unsafe package. Use the unsafe package at your own risk. Hopefully the name alone is a good enough warning. Here is how I would do it using unsafe:

buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
b := buf.Bytes()
s := *(*string)(unsafe.Pointer(&b))

There we go, you have now efficiently converted your byte array to a string. Really, all this does is trick the type system into calling it a string. There are a couple caveats to this method:

  1. There are no guarantees this will work in all go compilers. While this works with the plan-9 gc compiler, it relies on "implementation details" not mentioned in the official spec. You can not even guarantee that this will work on all architectures or not be changed in gc. In other words, this is a bad idea.
  2. That string is mutable! If you make any calls on that buffer it will change the string. Be very careful.

My advice is to stick to the official method. Doing a copy is not that expensive and it is not worth the evils of unsafe. If the string is too large to do a copy, you should not be making it into a string.

How to load a resource bundle from a file resource in Java?

I would prefer to use the resourceboundle class to load the properties - just to get it done in one line instead of 5 lines code through stream, Properties class and load().

FYI ....

    public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    try {

            /*** Type1 */
        Properties props = new Properties();

        String fileName = getServletContext().getRealPath("WEB-INF/classes/com/test/my.properties");
    //          stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    //          stream = ClassLoader.getSystemResourceAsStream("WEB-INF/class/com/test/my.properties");  

        InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/classes/com/test/my.properties");

  //        props.load(new FileInputStream(fileName));
        props.load(stream);

        stream.close();
        Iterator keyIterator = props.keySet().iterator();
        while(keyIterator.hasNext()) {
                String key = (String) keyIterator.next();
                String value = (String) props.getProperty(key);
                System.out.println("key:" + key + " value: " + value);
        }

  /*** Type2:  */
  // Just get it done in one line by rb instead of 5 lines to load the properties
  // WEB-INF/classes/com/test/my.properties file            
  //            ResourceBundle rb = ResourceBundle.getBundle("com.test.my", Locale.ENGLISH, getClass().getClassLoader());
        ResourceBundle rb = ResourceBundle.getBundle("com.ibm.multitool.customerlogs.ui.nl.redirect");
        Enumeration<String> keys = rb.getKeys();
        while(keys.hasMoreElements()) {
            String key = keys.nextElement();
            System.out.println(key + " - " + rb.getObject(key));
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new ServletException("Error loading config.", e);
    } catch (Exception e) {
        e.printStackTrace();
        throw new ServletException("Error loading config.", e);
    }       

}

Write-back vs Write-Through caching?

Write-Back is a more complex one and requires a complicated Cache Coherence Protocol(MOESI) but it is worth it as it makes the system fast and efficient.

The only benefit of Write-Through is that it makes the implementation extremely simple and no complicated cache coherency protocol is required.

Convert textbox text to integer

Example:

int x = Convert.ToInt32(this.txtboxname.Text) + 1 //You dont need the "this"
txtboxname.Text = x.ToString();

The x.ToString() makes the integer into string to show that in the text box.

Result:

  1. You put number in the text box.
  2. You click on the button or something running the function.
  3. You see your number just bigger than your number by one in your text box.

:)

jQuery - How to dynamically add a validation rule

You need to call .validate() before you can add rules this way, like this:

$("#myForm").validate(); //sets up the validator
$("input[id*=Hours]").rules("add", "required");

The .validate() documentation is a good guide, here's the blurb about .rules("add", option):

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.

Simple way to copy or clone a DataRow?

You can use ImportRow method to copy Row from DataTable to DataTable with the same schema:

var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);

Update:

With your new Edit, I believe:

var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];

will work

Java: Retrieving an element from a HashSet

If you could use List as a data structure to store your data, instead of using Map to store the result in the value of the Map, you can use following snippet and store the result in the same object.

Here is a Node class:

private class Node {
    public int row, col, distance;

    public Node(int row, int col, int distance) {
        this.row = row;
        this.col = col;
        this.distance = distance;
    }

    public boolean equals(Object o) {
        return (o instanceof Node &&
                row == ((Node) o).row &&
                col == ((Node) o).col);
    }
}

If you store your result in distance variable and the items in the list are checked based on their coordinates, you can use the following to change the distance to a new one with the help of lastIndexOf method as long as you only need to store one element for each data:

    List<Node> nodeList;
    nodeList = new ArrayList<>(Arrays.asList(new Node(1, 2, 1), new Node(3, 4, 5)));
    Node tempNode = new Node(1, 2, 10);
    if(nodeList.contains(tempNode))
        nodeList.get(nodeList.lastIndexOf(tempNode)).distance += tempNode.distance;

It is basically reimplementing Set whose items can be accessed and changed.

Are arrays passed by value or passed by reference in Java?

Your question is based on a false premise.

Arrays are not a primitive type in Java, but they are not objects either ... "

In fact, all arrays in Java are objects1. Every Java array type has java.lang.Object as its supertype, and inherits the implementation of all methods in the Object API.

... so are they passed by value or by reference? Does it depend on what the array contains, for example references or a primitive type?

Short answers: 1) pass by value, and 2) it makes no difference.

Longer answer:

Like all Java objects, arrays are passed by value ... but the value is the reference to the array. So, when you assign something to a cell of the array in the called method, you will be assigning to the same array object that the caller sees.

This is NOT pass-by-reference. Real pass-by-reference involves passing the address of a variable. With real pass-by-reference, the called method can assign to its local variable, and this causes the variable in the caller to be updated.

But not in Java. In Java, the called method can update the contents of the array, and it can update its copy of the array reference, but it can't update the variable in the caller that holds the caller's array reference. Hence ... what Java is providing is NOT pass-by-reference.

Here are some links that explain the difference between pass-by-reference and pass-by-value. If you don't understand my explanations above, or if you feel inclined to disagree with the terminology, you should read them.

Related SO question:

Historical background:

The phrase "pass-by-reference" was originally "call-by-reference", and it was used to distinguish the argument passing semantics of FORTRAN (call-by-reference) from those of ALGOL-60 (call-by-value and call-by-name).

  • In call-by-value, the argument expression is evaluated to a value, and that value is copied to the called method.

  • In call-by-reference, the argument expression is partially evaluated to an "lvalue" (i.e. the address of a variable or array element) that is passed to the calling method. The calling method can then directly read and update the variable / element.

  • In call-by-name, the actual argument expression is passed to the calling method (!!) which can evaluate it multiple times (!!!). This was complicated to implement, and could be used (abused) to write code that was very difficult to understand. Call-by-name was only ever used in Algol-60 (thankfully!).

UPDATE

Actually, Algol-60's call-by-name is similar to passing lambda expressions as parameters. The wrinkle is that these not-exactly-lambda-expressions (they were referred to as "thunks" at the implementation level) can indirectly modify the state of variables that are in scope in the calling procedure / function. That is part of what made them so hard to understand. (See the Wikipedia page on Jensen's Device for example.)


1. Nothing in the linked Q&A (Arrays in Java and how they are stored in memory) either states or implies that arrays are not objects.

"import datetime" v.s. "from datetime import datetime"

from datetime import datetime,timedelta
today=datetime.today()
print("Todays Date:",today)
yesterday=today-datetime,timedelta(days=1)
print("Yesterday date:",yesterday)
tommorrow=today+datetime.timedelta(days=1)
print("Tommorrow Date:",tommorrow)

Python Function to test ping

Adding on to the other answers, you can check the OS and decide whether to use "-c" or "-n":

import os, platform
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + host)

This will work on Windows, OS X, and Linux

You can also use sys:

import os, sys
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  sys.platform().lower()=="win32" else "-c 1 ") + host)

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

GridLayout (not GridView) how to stretch all children evenly

You can set width of every child dynamically:

GridLayout.LayoutParams params = (GridLayout.LayoutParams) child.getLayoutParams();
    params.width = (parent.getWidth()/parent.getColumnCount()) -params.rightMargin - params.leftMargin;
    child.setLayoutParams(params);

C++ Object Instantiation

I've seen this anti-pattern from people who don't quite get the & address-of operator. If they need to call a function with a pointer, they'll always allocate on the heap so they get a pointer.

void FeedTheDog(Dog* hungryDog);

Dog* badDog = new Dog;
FeedTheDog(badDog);
delete badDog;

Dog goodDog;
FeedTheDog(&goodDog);

Android Device not recognized by adb

  1. Download and install Moborobo software on your computer.
  2. Connect your device with USB debugging through USB cable.
  3. Now open moborobo and it will connect to your android.
  4. Stay connected, now your device should recognize as adb devices and get listed.

How to convert milliseconds to seconds with precision

Surely you just need:

double seconds = milliseconds / 1000.0;

There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0 (as a double literal) forces. (I'm assuming your milliseconds value is an integer of some form.)

Note that as usual with double, you may not be able to represent the result exactly. Consider using BigDecimal if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double is probably appropriate, but...)

grant remote access of MySQL database from any IP address

Run the following:

$ mysql -u root -p      
mysql> GRANT ALL ON *.* to root@'ipaddress' IDENTIFIED BY 'mysql root password';     
mysql> FLUSH PRIVILEGES;     
mysql> exit

Then attempt a connection from the IP address you specified:

mysql -h address-of-remove-server -u root -p   

You should be able to connect.

How can I access the MySQL command line with XAMPP for Windows?

Your MySQL binaries should be somewhere under your XAMPP folder. Look for a /bin folder, and you'll find the mysql.exe client around. Let's assume it is in c:\xampp\mysql\bin, then you should fireup a command prompt in this folder.

That means, fire up "cmd", and type:

cd c:\xampp\mysql\bin
mysql.exe -u root --password

If you want to use mysqldump.exe, you should also find it there.

Log into your mysql server, and start typing your commands.

Hope it helps...

What is the difference between `throw new Error` and `throw someObject`?

The Error constructor is used to create an error object. Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.

User-defined Errors are thrown via the throw statement. program control will be passed to the first catch block in the call stack.

The difference between throwing an error with and without Error object:


throw {'hehe':'haha'};

In chrome devtools looks like this:

enter image description here

Chrome tells us that we have an uncaught error which just is a JS object. The object itself could have information regarding the error but we still don't know immediately where it came from. Not very useful when we are working on our code and debugging it.


throw new Error({'hehe':'haha'}); 

In chrome devtools looks like this:

enter image description here

An error thrown with the Error object gives us a stack trace when we expand it. This gives us valuable information where the error precisely came from which is often valuable information when debugging your code. Further note that the error says [object Object], this is because the Error constructor expects a message string as a first argument. When it receives a object it will coerce it into a string.

How can I dynamically set the position of view in Android?

One thing to keep in mind with positioning is that each view has an index relative to its parent view. So if you have a linear layout with three subviews, the subviews will each have an index: 0, 1, 2 in the above case.

This allows you to add a view to the last position (or the end) in a parent view by doing something like this:

int childCount = parent.getChildCount();
parentView.addView(newView, childCount);

Alternatively you could replace a view using something like the following:

int childIndex = parentView.indexOfChild(childView);
childView.setVisibility(View.GONE);

parentView.addView(newView, childIndex);

How to verify if nginx is running or not?

Can also use the following code to check the nginx status:

   sudo /etc/init.d/nginx status

Current date and time - Default in MVC razor

If you want to display date time on view without model, just write this:

Date : @DateTime.Now

The output will be:

Date : 16-Aug-17 2:32:10 PM

Truncate (not round off) decimal numbers in javascript

You can fix the rounding by subtracting 0.5 for toFixed, e.g.

(f - 0.005).toFixed(2)

Converting String to Double in Android

try this:

double d= Double.parseDouble(yourString);

Regex matching beginning AND end strings

\bdbo\..*fn

I was looking through a ton of java code for a specific library: car.csclh.server.isr.businesslogic.TypePlatform (although I only knew car and Platform at the time). Unfortunately, none of the other suggestions here worked for me, so I figured I'd post this.

Here's the regex I used to find it:

\bcar\..*Platform

TCPDF not render all CSS properties

Since version 5.7 TCPDF includes support for CSS borders. Margins, padding and float are not yet supported. Check the TCPDF website at http://www.tcpdf.org and consult the official forum for further information.

How to link home brew python version and set it as default

This answer is for upgrading Python 2.7.10 to Python 2.7.11 on Mac OS X El Capitan . On Terminal type:

brew unlink python

After that type on Terminal

brew install python

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);
    }

404 Not Found The requested URL was not found on this server

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

I am sure your issue will be solved...

How do I replace all line breaks in a string with <br /> elements?

Without regex:

str = str.split("\n").join("<br />");

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

Bash scripting missing ']'

You're missing a space after "p1":

if [ -s "p1" ];

How do I specify the platform for MSBuild?

In Visual Studio 2019, version 16.8.4, you can just add

<Prefer32Bit>false</Prefer32Bit>

Convert a space delimited string to list

states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado"
states_list = states.split (' ')

Twitter Bootstrap: Print content of modal window

I was facing two issues Issue 1: all fields were coming one after other and Issue 2 white space at the bottom of the page when used to print from popup.

I Resolved this by

making display none to all body * elements most of them go for visibility hidden which creates space so avoid visibility hidden

    @media print {
        body * {
           display:none;
        width:auto;
        height:auto;
        margin:0px;padding:0px; 
        }
        #printSection, #printSection * {
            display:inline-block!important;
        }
        #printSection {
            position:absolute;
            left:0;
            top:0;  
            margin:0px; 
            page-break-before: none;
            page-break-after: none;
            page-break-inside: avoid;      
        }
#printSection .form-group{

      width:100%!important;
      float:left!important;
      page-break-after: avoid;
    }
#printSection label{
        float:left!important;
        width:200px!important;
        display:inline-block!important;
      }

#printSection .form-control.search-input{
        float:left!important;
        width:200px!important;
        display: inline-block!important;
      }
}

<script> tag vs <script type = 'text/javascript'> tag

<script> is HTML 5.

<script type='text/javascript'> is HTML 4.x (and XHTML 1.x).

<script language="javascript"> is HTML 3.2.

Is it different for different webservers?

No.

when I did an offline javascript test, i realised that i need the <script type = 'text/javascript'> tag.

That isn't the case. Something else must have been wrong with your test case.

Proper way to get page content

A simple, fast way to get the content by id :

echo get_post_field('post_content', $id);

And if you want to get the content formatted :

echo apply_filters('the_content', get_post_field('post_content', $id));

Works with pages, posts & custom posts.

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

If the other solutions here do not work, make sure you are not in 'offline' mode. If enabled, android will not download the required files and you will get this error.

enter image description here

Twitter Bootstrap Datepicker within modal window

I use:

body.modal-open .datepicker {
    z-index: 1200 !important;
}

This way: if the modal isn't open, and you want the datepicker to be at the normal z-index (in my case I needed it to be under the menu drop-down, which has a z-index of 1000), it works.

If the modal is open, the datepicker needs to be over the modal z-index (1040 or 1050), so use the body.modal-open selector.

I'm using Bootstrap 3.1.1

How to create range in Swift?

You can use like this

let nsRange = NSRange(location: someInt, length: someInt)

as in

let myNSString = bigTOTPCode as NSString //12345678
let firstDigit = myNSString.substringWithRange(NSRange(location: 0, length: 1)) //1
let secondDigit = myNSString.substringWithRange(NSRange(location: 1, length: 1)) //2
let thirdDigit = myNSString.substringWithRange(NSRange(location: 2, length: 4)) //3456

Count all values in a matrix greater than a value

You can use numpy.count_nonzero, converting the whole into a one-liner:

za = numpy.count_nonzero(numpy.asarray(o31)<200)  #as written in the code

Clearing Magento Log Data

SET foreign_key_checks = 0;
TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;
SET foreign_key_checks = 1;

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

This is clearly a classpath problem. Take into consideration that the classpath must change a bit when you run your program outside the IDE. This is because the IDE loads the other JARs relative to the root folder of your project, while in the case of the final JAR this is usually not true.

What I like to do in these situations is build the JAR manually. It takes me at most 5 minutes and it always solves the problem. I do not suggest you do this. Find a way to use Maven, that's its purpose.

How to convert an OrderedDict into a regular dict in python3

A version that handles nested dictionaries and iterables but does not use the json module. Nested dictionaries become dict, nested iterables become list, everything else is returned unchanged (including dictionary keys and strings/bytes/bytearrays).

def recursive_to_dict(obj):
    try:
        if hasattr(obj, "split"):    # is string-like
            return obj
        elif hasattr(obj, "items"):  # is dict-like
            return {k: recursive_to_dict(v) for k, v in obj.items()}
        else:                        # is iterable
            return [recursive_to_dict(e) for e in obj]
    except TypeError:                # return everything else
        return obj

Find distance between two points on map using Google Map API V2

All this answers will give you the distance in a straight line. If you need to get the distance by road, you have to parse the JSON that Google sends you back after calling his service. You can use this method:

public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){
    String parsedDistance;
    String response;
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
                    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");

                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray array = jsonObject.getJSONArray("routes");
                    JSONObject routes = array.getJSONObject(0);
                    JSONArray legs = routes.getJSONArray("legs");
                    JSONObject steps = legs.getJSONObject(0);
                    JSONObject distance = steps.getJSONObject("distance");
                    parsedDistance=distance.getString("text");

                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return parsedDistance;
}

lat1 and lon1 are coordinates of origin, lat2 and lon2 are coordinates of destination.

What is the difference between Scrum and Agile Development?

Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.

As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful

ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach. Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.

The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.

Extract text from a string

Using -replace

 $string = '% O0033(SUB RAD MSD 50R III) G91G1X-6.4Z-2.F500 G3I6.4Z-8.G3I6.4 G3R3.2X6.4F500 G91G0Z5. G91G1X-10.4 G3I10.4 G3R5.2X10.4 G90G0Z2. M99 %'
 $program = $string -replace '^%\sO\d{4}\((.+?)\).+$','$1'
 $program

SUB RAD MSD 50R III

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

One of alternatives is MSYS2 , in another words "MinGW-w64"/Git Bash. You can simply ssh to Unix machines and run most of linux commands from it. Also install tmux!

To install tmux in MSYS2:

run command pacman -S tmux

To run tmux on Git Bash:

install MSYS2 and copy tmux.exe and msys-event-2-1-6.dll from MSYS2 folder C:\msys64\usr\bin to your Git Bash directory C:\Program Files\Git\usr\bin.

How can I create a marquee effect?

Based on the previous reply, mainly @fcalderan, this marquee scrolls when hovered, with the advantage that the animation scrolls completely even if the text is shorter than the space within it scrolls, also any text length takes the same amount of time (this may be a pros or a cons) when not hovered the text return in the initial position.

No hardcoded value other than the scroll time, best suited for small scroll spaces

_x000D_
_x000D_
.marquee {_x000D_
    width: 100%;_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    display: inline-flex;    _x000D_
}_x000D_
_x000D_
.marquee span {_x000D_
    display: flex;        _x000D_
    flex-basis: 100%;_x000D_
    animation: marquee-reset;_x000D_
    animation-play-state: paused;                _x000D_
}_x000D_
_x000D_
.marquee:hover> span {_x000D_
    animation: marquee 2s linear infinite;_x000D_
    animation-play-state: running;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% {_x000D_
        transform: translate(0%, 0);_x000D_
    }    _x000D_
    50% {_x000D_
        transform: translate(-100%, 0);_x000D_
    }_x000D_
    50.001% {_x000D_
        transform: translate(100%, 0);_x000D_
    }_x000D_
    100% {_x000D_
        transform: translate(0%, 0);_x000D_
    }_x000D_
}_x000D_
@keyframes marquee-reset {_x000D_
    0% {_x000D_
        transform: translate(0%, 0);_x000D_
    }  _x000D_
}
_x000D_
<span class="marquee">_x000D_
    <span>This is the marquee text</span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

How to install wget in macOS?

You need to do

./configure --with-ssl=openssl --with-libssl-prefix=/usr/local/ssl

Instead of this

./configure --with-ssl=openssl

Find MongoDB records where array field is not empty

ME.find({pictures: {$exists: true}}) 

Simple as that, this worked for me.

JQuery, select first row of table

late in the game , but this worked for me:

$("#container>table>tbody>tr:first").trigger('click');

How to get cumulative sum

Select *, (Select SUM(SOMENUMT) From @t S Where S.id <= M.id) From @t M

Difference between sh and bash

This question has frequently been nominated as a canonical for people who try to use sh and are surprised that it's not behaving the same as bash. Here's a quick rundown of common misunderstandings and pitfalls.

First off, you should understand what to expect.

  • If you run your script with sh scriptname, or run it with scriptname and have #!/bin/sh in the shebang line, you should expect POSIX sh behavior.
  • If you run your script with bash scriptname, or run it with scriptname and have #!/bin/bash (or the local equivalent) in the shebang line, you should expect Bash behavior.

Having a correct shebang and running the script by typing just the script name (possibly with a relative or full path) is generally the preferred solution. In addition to a correct shebang, this requires the script file to have execute permission (chmod a+x scriptname).

So, how do they actually differ?

The Bash Reference manual has a section which attempts to enumerate the differences but some common sources of confusion include

  • [[ is not available in sh (only [ which is more clunky and limited). See also Difference between single and double square brackets in Bash
  • sh does not have arrays.
  • Some Bash keywords like local, source, function, shopt, let, declare, and select are not portable to sh. (Some sh implementations support e.g. local.)
  • Bash has many C-style syntax extensions like the three-argument for((i=0;i<=3;i++)) loop, += increment assignment, etc. The $'string\nwith\tC\aescapes' feature is tentatively accepted for POSIX (meaning it works in Bash now, but will not yet be supported by sh on systems which only adhere to the current POSIX specification, and likely will not for some time to come).
  • Bash supports <<<'here strings'.
  • Bash has *.{png,jpg} and {0..12} brace expansion.
  • ~ refers to $HOME only in Bash (and more generally ~username to the home directory of username).This is in POSIX, but may be missing from some pre-POSIX /bin/sh implementations.
  • Bash has process substitution with <(cmd) and >(cmd).
  • Bash has Csh-style convenience redirection aliases like &| for 2>&1 | and &> for > ... 2>&1
  • Bash supports coprocesses with <> redirection.
  • Bash features a rich set of expanded non-standard parameter expansions such as ${substring:1:2}, ${variable/pattern/replacement}, case conversion, etc.
  • Bash has significantly extended facilities for shell arithmetic (though still no floating-point support). There is an obsolescent legacy $[expression] syntax which however should be replaced with POSIX arithmetic $((expression)) syntax. (Some legacy pre-POSIX sh implementations may not support that, though.)
  • Several built-in commands have options which are not portable, like type -a, printf -v, and the perennial echo -e.
  • Magic variables like $RANDOM, $SECONDS, $PIPESTATUS[@] and $FUNCNAME are Bash extensions.
  • Syntactic differences like export variable=value and [ "x" == "y" ] which are not portable (export variable should be separate from variable assignment, and portable string comparison in [ ... ] uses a single equals sign).
  • Many, many Bash-only extensions to enable or disable optional behavior and expose internal state of the shell.
  • Many, many convenience features for interactive use which however do not affect script behavior.

Remember, this is an abridged listing. Refer to the reference manual for the full scoop, and http://mywiki.wooledge.org/Bashism for many good workarounds; and/or try http://shellcheck.net/ which warns for many Bash-only features.

A common error is to have a #!/bin/bash shebang line, but then nevertheless using sh scriptname to actually run the script. This basically disables any Bash-only functionality, so you get syntax errors e.g. for trying to use arrays. (The shebang line is syntactically a comment, so it is simply ignored in this scenario.)

Unfortunately, Bash will not warn when you try to use these constructs when it is invoked as sh. It doesn't completely disable all Bash-only functionality, either, so running Bash by invoking it as sh is not a good way to check if your script is properly portable to ash/dash/POSIX sh or variants like Heirloom sh

Where is the correct location to put Log4j.properties in an Eclipse project?

If you have a library and you want to append the log4j:

  1. Create a folder named "resources" in your projet.
  2. Create a .properties file named log4j
  3. Set properties in log4j.properties file
  4. Push right button in the project and go to properties->Java Build Path and, finally, go to the "Source" tab.
  5. Push Add folder and search the "resources" folder created in step 1.
  6. Finish.

(I have assumed that you have the log4j library added.)

PD: Sorry for my english.

Extract source code from .jar file

Above tools extract the jar. Also there are certain other tools and commands to extract the jar. But AFAIK you cant get the java code in case code has been obfuscated.

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

Clone an image in cv2 python

If you use cv2, correct method is to use .copy() method in Numpy. It will create a copy of the array you need. Otherwise it will produce only a view of that object.

eg:

In [1]: import numpy as np

In [2]: x = np.arange(10*10).reshape((10,10))

In [4]: y = x[3:7,3:7].copy()

In [6]: y[2,2] = 1000

In [8]: 1000 in x
Out[8]: False     # see, 1000 in y doesn't change values in x, parent array.

What is the difference between the kernel space and the user space?

The correct answer is: There is no such thing as kernel space and user space. The processor instruction set has special permissions to set destructive things like the root of the page table map, or access hardware device memory, etc.

Kernel code has the highest level privileges, and user code the lowest. This prevents user code from crashing the system, modifying other programs, etc.

Generally kernel code is kept under a different memory map than user code (just as user spaces are kept in different memory maps than each other). This is where the "kernel space" and "user space" terms come from. But that is not a hard and fast rule. For example, since the x86 indirectly requires its interrupt/trap handlers to be mapped at all times, part (or some OSes all) of the kernel must be mapped into user space. Again, this does not mean that such code has user privileges.

Why is the kernel/user divide necessary? Some designers disagree that it is, in fact, necessary. Microkernel architecture is based on the idea that the highest privileged sections of code should be as small as possible, with all significant operations done in user privileged code. You would need to study why this might be a good idea, it is not a simple concept (and is famous for both having advantages and drawbacks).

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

This should be able to set to whatever keybindings you want for indent/outdent here:

Menu FilePreferencesKeyboard Shortcuts

editor.action.indentLines

editor.action.outdentLines

How do I fix the indentation of selected lines in Visual Studio

To fix the indentation and formatting in all files of your solution:

  1. Install the Format All Files extension => close VS, execute the .vsix file and reopen VS;
  2. Menu Tools > Options... > Text Editor > All Languages > Tabs:
    1. Click on Smart (for resolving conflicts);
    2. Type the Tab Size and Indent Size you want (e.g. 2);
    3. Click on Insert Spaces if you want to replace tabs by spaces;
  3. In the Solution Explorer (Ctrl+Alt+L) right click in any file and choose from the menu Format All Files (near the bottom).

This will recursively open and save all files in your solution, setting the indentation you defined above.

You might want to check other programming languages tabs (Options...) for Code Style > Formatting as well.

How do I ignore files in Subversion?

Use the following command to create a list not under version control files.

svn status | grep "^\?" | awk "{print \$2}" > ignoring.txt

Then edit the file to leave just the files you want actually to ignore. Then use this one to ignore the files listed in the file:

svn propset svn:ignore -F ignoring.txt .

Note the dot at the end of the line. It tells SVN that the property is being set on the current directory.

Delete the file:

rm ignoring.txt

Finally commit,

svn ci --message "ignoring some files"

You can then check which files are ignored via:

svn proplist -v

How to set -source 1.7 in Android Studio and Gradle

Latest Android Studio 1.4.

Click File->Project Structure->SDK Location->JDK Location.

You could also set individual module JDK Version compatibility by going to the Module (below the SDK Location), and edit the Source Compatibility accordingly. (note, this only applies to Android Module).

Python way to clone a git repository

You can use dload

import dload
dload.git_clone("https://github.com/some_repo.git")

pip install dload

Difficulty with ng-model, ng-repeat, and inputs

You get into a difficult situation when it is necessary to understand how scopes, ngRepeat and ngModel with NgModelController work. Also try to use 1.0.3 version. Your example will work a little differently.

You can simply use solution provided by jm-

But if you want to deal with the situation more deeply, you have to understand:

  • how AngularJS works;
  • scopes have a hierarchical structure;
  • ngRepeat creates new scope for every element;
  • ngRepeat build cache of items with additional information (hashKey); on each watch call for every new item (that is not in the cache) ngRepeat constructs new scope, DOM element, etc. More detailed description.
  • from 1.0.3 ngModelController rerenders inputs with actual model values.

How your example "Binding to each element directly" works for AngularJS 1.0.3:

  • you enter letter 'f' into input;
  • ngModelController changes model for item scope (names array is not changed) => name == 'Samf', names == ['Sam', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat replaces model value from item scope ('Samf') by value from unchanged names array ('Sam');
  • ngModelController rerenders input with actual model value ('Sam').

How your example "Indexing into the array" works:

  • you enter letter 'f' into input;
  • ngModelController changes item in names array => `names == ['Samf', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat can't find 'Samf' in cache;
  • ngRepeat creates new scope, adds new div element with new input (that is why the input field loses focus - old div with old input is replaced by new div with new input);
  • new values for new DOM elements are rendered.

Also, you can try to use AngularJS Batarang and see how changes $id of the scope of div with input in which you enter.

How can you flush a write using a file descriptor?

If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :

                                                          FDOPEN(P)

NAME

       fdopen - associate a stream with a file descriptor

SYNOPSIS

       #include <stdio.h>

       FILE *fdopen(int fildes, const char *mode);

Declare variable MySQL trigger

All DECLAREs need to be at the top. ie.

delimiter //

CREATE TRIGGER pgl_new_user 
AFTER INSERT ON users FOR EACH ROW
BEGIN
    DECLARE m_user_team_id integer;
    DECLARE m_projects_id integer;
    DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;

    SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");

    OPEN cur;
        ins_loop: LOOP
            FETCH cur INTO m_projects_id;
            IF done THEN
                LEAVE ins_loop;
            END IF;
            INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access) 
            VALUES (NEW.id, m_projects_id, now(), now(), 20);
        END LOOP;
    CLOSE cur;
END//

Copy output of a JavaScript variable to the clipboard

I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.

Note: the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of var instead of let or const. I also recommend to use addEventListener for the button.

_x000D_
_x000D_
    function doCopy() {_x000D_
_x000D_
        try{_x000D_
            var unique = document.querySelectorAll('.unique');_x000D_
            var msg ="";_x000D_
_x000D_
            unique.forEach(function (unique) {_x000D_
                msg+=unique.value;_x000D_
            });_x000D_
_x000D_
            var temp =document.createElement("textarea");_x000D_
            var tempMsg = document.createTextNode(msg);_x000D_
            temp.appendChild(tempMsg);_x000D_
_x000D_
            document.body.appendChild(temp);_x000D_
            temp.select();_x000D_
            document.execCommand("copy");_x000D_
            document.body.removeChild(temp);_x000D_
            console.log("Success!")_x000D_
_x000D_
_x000D_
        }_x000D_
        catch(err) {_x000D_
_x000D_
            console.log("There was an error copying");_x000D_
        }_x000D_
    }
_x000D_
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>_x000D_
<input type="text" class="unique" size="18" value="">_x000D_
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>
_x000D_
_x000D_
_x000D_

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I found the problem that was causing the HTTP error.

In the setFalse() function that is triggered by the Save button my code was trying to submit the form that contained the button.

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit();
            document.submitForm.submit();

when I remove the document.submitForm.submit(); it works:

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit()

@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!

Get size of all tables in database

IF you only care about the empty wasted space in the database and not the individual tables you can consider the following:

If the database experiences large amount of data insertion and then deletions, maybe like in an ETL situation, this will cause too much unused space in the database as the file groups auto-grows but never auto-shrinks back.

You can see if this is the case by using the Properties page of your database. You can shrink (right click on the database > Tasks > Shrink) and claim some space back. But, if the underlying reason is still there, the database will grow back (and consume extra time trying to grow back and things gets slowed down until it grows enough - so don't do it in that case)

(KEK: key encryption key)

Settings to Windows Firewall to allow Docker for Windows to share drive

I was not using any third party firewalls when running into this error. I was convinced it was a Windows Firewall issue, though disabling Windows Firewall did not work for me. I finally found this blog post after much research: Docker on windows 10 error: A firewall is blocking file Sharing ...

It ended up NOT having to do with the built in Windows Firewall.

The Fix

  1. Uncheck File and Printer Sharing for Microsoft Networks from the vEthernet (DockerNAT) network adapter (you can find the connection in the Windows Network and Sharing Center).
  2. Recheck it and make sure it is enabled.

Create component to specific module with Angular-CLI

For Angular v4 and Above, simply use:

ng g c componentName -m ModuleName

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

If the extra entries in the log bother you but an extra second of start-up time doesn't, just add this to your logging.properties and forget about it:

org.apache.jasper.servlet.TldScanner.level = WARNING

How to coerce a list object to type 'double'

If your list as multiple elements that need to be converted to numeric, you can achieve this with lapply(a, as.numeric).

Is it possible to log all HTTP request headers with Apache?

mod_log_forensic is what you want, but it may not be included/available with your Apache install by default.

Here is how to use it.

LoadModule log_forensic_module /usr/lib64/httpd/modules/mod_log_forensic.so 
<IfModule log_forensic_module> 
ForensicLog /var/log/httpd/forensic_log 
</IfModule> 

Git error: "Please make sure you have the correct access rights and the repository exists"

For me it was because of no SSH key on the machine. Check the SSH key locally:

$ cat ~/.ssh/id_rsa.pub

This is your SSH key. Add it to your SSH keys in the repository.
In gitlab go to

profile settings -> SSH Keys

and add the key

How do I configure different environments in Angular.js?

You could use lvh.me:9000 to access your AngularJS app, (lvh.me just points to 127.0.0.1) and then specify a different endpoint if lvh.me is the host:

app.service("Configuration", function() {
  if (window.location.host.match(/lvh\.me/)) {
    return this.API = 'http://localhost\\:7080/myapi/';
  } else {
    return this.API = 'http://localhost\\:8099/hisapi/';
  }
});

And then inject the Configuration service and use Configuration.API wherever you need to access the API:

$resource(Configuration.API + '/endpoint/:id', {
  id: '@id'
});

A tad clunky, but works fine for me, albeit in a slightly different situation (API endpoints differ in production and development).

MySQL default datetime through phpmyadmin

You can't set CURRENT_TIMESTAMP as default value with DATETIME.

But you can do it with TIMESTAMP.

See the difference here.

Words from this blog

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.

How do I make a <div> move up and down when I'm scrolling the page?

Here is the Jquery Code

$(document).ready(function () {
     var el = $('#Container');
        var originalelpos = el.offset().top; // take it where it originally is on the page

        //run on scroll
        $(window).scroll(function () {
            var el = $('#Container'); // important! (local)
            var elpos = el.offset().top; // take current situation
            var windowpos = $(window).scrollTop();
            var finaldestination = windowpos + originalelpos;
            el.stop().animate({ 'top': finaldestination }, 1000);
        });
    });

What are valid values for the id attribute in HTML?

Strictly it should match

[A-Za-z][-A-Za-z0-9_:.]*

But jquery seems to have problems with colons so it might be better to avoid them.

bash: mkvirtualenv: command not found

On Windows 7 and Git Bash this helps me:

  1. Create a ~/.bashrc file (under your user home folder)
  2. Add line export WORKON_HOME=$HOME/.virtualenvs (you must create this folder if it doesn't exist)
  3. Add line source "C:\Program Files (x86)\Python36-32\Scripts\virtualenvwrapper.sh" (change path for your virtualenvwrapper.sh)

Restart your git bash and mkvirtualenv command now will work nicely.

How do I change db schema to dbo

You can run the following, which will generate a set of ALTER sCHEMA statements for all your talbes:

SELECT 'ALTER SCHEMA dbo TRANSFER ' + TABLE_SCHEMA + '.' + TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'jonathan'

You then have to copy and run the statements in query analyzer.

Here's an older script that will do that for you, too, I think by changing the object owner. Haven't tried it on 2008, though.

DECLARE @old sysname, @new sysname, @sql varchar(1000)

SELECT
  @old = 'jonathan'
  , @new = 'dbo'
  , @sql = '
  IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES
  WHERE
      QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?''
      AND TABLE_SCHEMA = ''' + @old + '''
  )
  EXECUTE sp_changeobjectowner ''?'', ''' + @new + ''''

EXECUTE sp_MSforeachtable @sql

Got it from this site.

It also talks about doing the same for stored procs if you need to.

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

Install LXML parser in python environment.

pip install lxml

Your problem will be resolve. You can also use built-in python package for the same as:

soup = BeautifulSoup(s,  "html.parser")

Note: The "HTMLParser" module has been renamed to "html.parser" in Python3

Increase number of axis ticks

Based on Daniel Krizian's comment, you can also use the pretty_breaks function from the scales library, which is imported automatically:

ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 10))

All you have to do is insert the number of ticks wanted for n.


A slightly less useful solution (since you have to specify the data variable again), you can use the built-in pretty function:

ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = pretty(dat$x, n = 10)) +
scale_y_continuous(breaks = pretty(dat$y, n = 10))

How to set timeout on python's socket recv method?

As mentioned in previous replies, you can use something like: .settimeout() For example:

import socket

s = socket.socket()

s.settimeout(1) # Sets the socket to timeout after 1 second of no activity

host, port = "somehost", 4444
s.connect((host, port))

s.send("Hello World!\r\n")

try:
    rec = s.recv(100) # try to receive 100 bytes
except socket.timeout: # fail after 1 second of no activity
    print("Didn't receive data! [Timeout]")
finally:
    s.close()

I hope this helps!!

Parsing a comma-delimited std::string

Lots of pretty terrible answers here so I'll add mine (including test program):

#include <string>
#include <iostream>
#include <cstddef>

template<typename StringFunction>
void splitString(const std::string &str, char delimiter, StringFunction f) {
  std::size_t from = 0;
  for (std::size_t i = 0; i < str.size(); ++i) {
    if (str[i] == delimiter) {
      f(str, from, i);
      from = i + 1;
    }
  }
  if (from <= str.size())
    f(str, from, str.size());
}


int main(int argc, char* argv[]) {
    if (argc != 2)
        return 1;

    splitString(argv[1], ',', [](const std::string &s, std::size_t from, std::size_t to) {
        std::cout << "`" << s.substr(from, to - from) << "`\n";
    });

    return 0;
}

Nice properties:

  • No dependencies (e.g. boost)
  • Not an insane one-liner
  • Easy to understand (I hope)
  • Handles spaces perfectly fine
  • Doesn't allocate splits if you don't want to, e.g. you can process them with a lambda as shown.
  • Doesn't add characters one at a time - should be fast.
  • If using C++17 you could change it to use a std::stringview and then it won't do any allocations and should be extremely fast.

Some design choices you may wish to change:

  • Empty entries are not ignored.
  • An empty string will call f() once.

Example inputs and outputs:

""      ->   {""}
","     ->   {"", ""}
"1,"    ->   {"1", ""}
"1"     ->   {"1"}
" "     ->   {" "}
"1, 2," ->   {"1", " 2", ""}
" ,, "  ->   {" ", "", " "}

Call another rest api from my server in Spring-Boot

Does Retrofit have any method to achieve this? If not, how I can do that?

YES

Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.

For more information refer the following link

https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial

How do I directly modify a Google Chrome Extension File? (.CRX)

(Already said) I found this out while making some Chrome themes (which are long gone now... :-P)

Chrome themes, extensions, etc. are just compressed files. Get 7-zip or WinRar to unzip it. Each extension/theme has a manifest.json file. Open the manifest.json file in notepad. Then, if you know the coding, modify the code. There will be some other files. If you look in the manifest file you might be able to figure out what the are for. Then, you can change everything...

Download a file with Android, and showing the progress in a ProgressDialog

Yes the code above will work .But if you are updating your progressbar in onProgressUpdate of Asynctask and you press back button or finish your activity AsyncTask looses its track with your UI .And when you go back to your activity, even if download is running in background you will see no update on progressbar. So on OnResume() try to run a thread like runOnUIThread with a timer task that updates ur progressbar with values updating from the AsyncTask running background.

private void updateProgressBar(){
    Runnable runnable = new updateProgress();
    background = new Thread(runnable);
    background.start();
}

public class updateProgress implements Runnable {
    public void run() {
        while(Thread.currentThread()==background)
            //while (!Thread.currentThread().isInterrupted()) {
            try {
                Thread.sleep(1000); 
                Message msg = new Message();
                progress = getProgressPercentage();        
                handler.sendMessage(msg);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (Exception e) {
        }
    }
}

private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        progress.setProgress(msg.what);
    }
};

Don't forget to Destroy the thread when ur activity is not visible.

private void destroyRunningThreads() {
    if (background != null) {
        background.interrupt();
        background=null;
    }
}

What happens if you mount to a non-empty mount point with fuse?

You need to make sure that the files on the device mounted by fuse will not have the same paths and file names as files which already existing in the nonempty mountpoint. Otherwise this would lead to confusion. If you are sure, pass -o nonempty to the mount command.

You can try what is happening using the following commands.. (Linux rocks!) .. without destroying anything..

// create 10 MB file 
dd if=/dev/zero of=partition bs=1024 count=10240

// create loopdevice from that file
sudo losetup /dev/loop0 ./partition

// create  filesystem on it
sudo e2mkfs.ext3 /dev/loop0

// mount the partition to temporary folder and create a file
mkdir test
sudo mount -o loop /dev/loop0 test
echo "bar" | sudo tee test/foo

# unmount the device
sudo umount /dev/loop0

# create the file again
echo "bar2" > test/foo

# now mount the device (having file with same name on it) 
# and see what happens
sudo mount -o loop /dev/loop0 test

Remove characters from a string

I know this is old but if you do a split then join it will remove all occurrences of a particular character ie:

var str = theText.split('A').join('')

will remove all occurrences of 'A' from the string, obviously it's not case sensitive

constant pointer vs pointer on a constant value

I will explain it verbally first and then with an example:

A pointer object can be declared as a const pointer or a pointer to a const object (or both):

const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee").
Reference variables are thus an alternate syntax for constpointers.

A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object.

const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object.

Example:

void Foo( int * ptr,
         int const * ptrToConst,
         int * const constPtr,
         int const * const constPtrToConst ) 
{ 
    *ptr = 0; // OK: modifies the "pointee" data 
    ptr = 0; // OK: modifies the pointer 

    *ptrToConst = 0; // Error! Cannot modify the "pointee" data
     ptrToConst = 0; // OK: modifies the pointer 

    *constPtr = 0; // OK: modifies the "pointee" data 
    constPtr = 0; // Error! Cannot modify the pointer 

    *constPtrToConst = 0; // Error! Cannot modify the "pointee" data 
    constPtrToConst = 0; // Error! Cannot modify the pointer 
}

Happy to help! Good Luck!

How to read PDF files using Java?

PDFBox contains tools for text extraction.

iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.

iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.

Java 256-bit AES Password-Based Encryption

Use this class for encryption. It works.

public class ObjectCrypter {


    public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] mes) 
            throws NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException, IOException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(mes);

    }

    public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] bytes) 
            throws NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException, IOException, ClassNotFoundException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(bytes);

    }
}

And these are ivBytes and a random key;

String key = "e8ffc7e56311679f12b6fc91aa77a5eb";

byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
keyBytes = key.getBytes("UTF-8");

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

ssh_exchange_identification: Connection closed by remote host under Git bash

Just enter on the server side :

echo 'SSHD: ALL' >> /etc/hosts.allow

It sorted it out for me.

How can I give access to a private GitHub repository?

Struggled to find this as well.

Heres a screenshot of how to do it:

enter image description here

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

How do I create a pause/wait function using Qt?

To use the standard sleep function add the following in your .cpp file:

#include <unistd.h>

As of Qt version 4.8, the following sleep functions are available:

void QThread::msleep(unsigned long msecs)
void QThread::sleep(unsigned long secs)
void QThread::usleep(unsigned long usecs)

To use them, simply add the following in your .cpp file:

#include <QThread>

Reference: QThread (via Qt documentation): http://doc.qt.io/qt-4.8/qthread.html

Otherwise, perform these steps...

Modify the project file as follows:

CONFIG += qtestlib

Note that in newer versions of Qt you will get the following error:

Project WARNING: CONFIG+=qtestlib is deprecated. Use QT+=testlib instead.

... so, instead modify the project file as follows:

QT += testlib

Then, in your .cpp file, be sure to add the following:

#include <QtTest>

And then use one of the sleep functions like so:

usleep(100);

What Does This Mean in PHP -> or =>

-> is used to call a method, or access a property, on the object of a class

=> is used to assign values to the keys of an array

E.g.:

    $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34, 1=>2); 

And since PHP 7.4+ the operator => is used too for the added arrow functions, a more concise syntax for anonymous functions.

how to use a like with a join in sql?

In MySQL you could try:

SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');

Of course this would be a massively inefficient query because it would do a full table scan.

Update: Here's a proof


create table A (MYCOL varchar(255));
create table B (MYCOL varchar(255));
insert into A (MYCOL) values ('foo'), ('bar'), ('baz');
insert into B (MYCOL) values ('fooblah'), ('somethingfooblah'), ('foo');
insert into B (MYCOL) values ('barblah'), ('somethingbarblah'), ('bar');
SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');
+-------+------------------+
| MYCOL | MYCOL            |
+-------+------------------+
| foo   | fooblah          |
| foo   | somethingfooblah |
| foo   | foo              |
| bar   | barblah          |
| bar   | somethingbarblah |
| bar   | bar              |
+-------+------------------+
6 rows in set (0.38 sec)