Programs & Examples On #Search engine api

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

http-server for node.js is very convenient, and is a lot faster than Python's SimpleHTTPServer. This is primarily because it uses asynchronous IO for concurrent handling of requests, instead of serialising requests.

Installation

Install node.js if you haven't already. Then use the node package manager (npm) to install the package, using the -g option to install globally. If you're on Windows you'll need a prompt with administrator permissions, and on Linux/OSX you'll want to sudo the command:

npm install http-server -g

This will download any required dependencies and install http-server.

Use

Now, from any directory, you can type:

http-server [path] [options]

Path is optional, defaulting to ./public if it exists, otherwise ./.

Options are [defaults]:

  • -p The port number to listen on [8080]
  • -a The host address to bind to [localhost]
  • -i Display directory index pages [True]
  • -s or --silent Silent mode won't log to the console
  • -h or --help Displays help message and exits

So to serve the current directory on port 8000, type:

http-server -p 8000

Converting Go struct to JSON

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless:

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.

How to move certain commits to be based on another branch in git?

// on your branch that holds the commit you want to pass
$ git log
// copy the commit hash found
$ git checkout [branch that will copy the commit]
$ git reset --hard [hash of the commit you want to copy from the other branch]
// remove the [brackets]

Other more useful commands here with explanation: Git Guide

Is __init__.py not required for packages in Python 3.3+

Based on my experience, even with python 3.3+, an empty __init__.py is still needed sometimes. One situation is when you want to refer a subfolder as a package. For example, when I ran python -m test.foo, it didn't work until I created an empty __init__.py under the test folder. And I'm talking about 3.6.6 version here which is pretty recent.

Apart from that, even for reasons of compatibility with existing source code or project guidelines, its nice to have an empty __init__.py in your package folder.

How to add local .jar file dependency to build.gradle file?

Goto File -> Project Structure -> Modules -> app -> Dependencies Tab -> Click on +(button) -> Select File Dependency - > Select jar file in the lib folder

This steps will automatically add your dependency to gralde

Very Simple

What are the "spec.ts" files generated by Angular CLI for?

.spec.ts file is used for unit testing of your application.

If you don't to get it generated just use --spec=false while creating new Component. Like this

ng generate component --spec=false mycomponentName

How do I rename a Git repository?

If you are in Eclipse and have installed Egit then you can rename the repository that contains a project by doing the following:

1) In Eclipse: Close all projects that are in the repository.

2) In the file system: Locate the directory/folder that contains the repository.

3) In the file system: Rename the directory/folder that contains the repository.

4) In the file system: Open the directory/folder that contains the repository and rename the project directory/folder of any project you intend to rename so that it will match the new name of the project. (This is not required but it gives consistency between the project name in Eclipse and the project directory/folder in the repository.)

5) In Eclipse: Delete all projects that are in the repository but be sure to NOT check the 'Delete the contents from the file system' checkbox. (The project should no longer contain the correct location of the contents of the file system so the data could not be deleted in any case but it is better to be safe than sorry.)

6) In Eclipse: From the Menu select the File|Import... option.

7) In Eclipse: In dialog box open the 'Git' folder, select 'Projects from Git' and click 'Next'.

8) In Eclipse: In dialog box select 'Local' and click 'Next'.

9) In Eclipse: In dialog box click the 'Add...' button.

10) In Eclipse: In dialog box make sure the check box next to the repository is checked and click 'Finish'.

11) In Eclipse: In dialog box select the repository and click 'Next'.

12) In Eclipse: In dialog box select the 'Import existing projects' radio button, select the "Working Directory" and click 'Next'.

13) In Eclipse: In dialog box check the check box next to the projects you want to work on and click 'Finish'.

14) In Eclipse: Rename any the projects that are in the repository if so desired. (For consistency between Eclipse and the file system give them the same name as the project directory/folder inside the repository directory/folder.)

How to get the android Path string to a file on Assets folder?

Have a look at the ReadAsset.java from API samples that come with the SDK.

       try {
        InputStream is = getAssets().open("read_asset.txt");

        // We guarantee that the available method returns the total
        // size of the asset...  of course, this does mean that a single
        // asset can't be more than 2 gigs.
        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        // Convert the buffer into a string.
        String text = new String(buffer);

        // Finally stick the string into the text view.
        TextView tv = (TextView)findViewById(R.id.text);
        tv.setText(text);
    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }

This app won't run unless you update Google Play Services (via Bazaar)

After updating to ADT 22.0.1, due to Android private libraries, the Google Maps service was giving some error and the app crashed. So I found the solution finally and it worked for me.

Just install the Google Play service library and then go to google-play-service/libproject/google-play-services_lib from https://www.dropbox.com/sh/2ok76ep7lmav0qf/9XVlv61D2b. Import that into your workspace. Clean your project where you want to use gogole-play-services-lib and then build it again and go to the Project -> Properties -> Java BuildPath -> select "Android Private Libraries, Android Dependencies, google-play-service"

In Properties itself, go to Android and then choose any of the versions and then choose add and select google-play-service-lib and then press apply and finally OK.

At last, go to the Project -> Android Tools -> Android Support Libraries. Accept the license and after installing then run your project.

It will work fine.

Choosing a file in Python with simple Dialog

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.

Adding and reading from a Config file

  1. Right click on the project file -> Add -> New Item -> Application Configuration File. This will add an app.config (or web.config) file to your project.

  2. The ConfigurationManager class would be a good start. You can use it to read different configuration values from the configuration file.

I suggest you start reading the MSDN document about Configuration Files.

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

How to replace local branch with remote branch entirely in Git?

I'm kind of surprised no one mentioned this yet; I use it nearly every day:

git reset --hard @{u}

Basically, @{u} is just shorthand for the upstream branch that your current branch is tracking. For example, this typically equates to origin/[my-current-branch-name]. It's nice because it's branch agnostic.

Make sure to git fetch first to get the latest copy of the remote branch.

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

There is some official documentation on that point: Best Practices for Writing Dockerfiles

Because image size matters, using ADD to fetch packages from remote URLs is strongly discouraged; you should use curl or wget instead. That way you can delete the files you no longer need after they've been extracted and you won't have to add another layer in your image.

RUN mkdir -p /usr/src/things \
  && curl -SL http://example.com/big.tar.gz \
    | tar -xJC /usr/src/things \
  && make -C /usr/src/things all

For other items (files, directories) that do not require ADD’s tar auto-extraction capability, you should always use COPY.

Gunicorn worker timeout error

Run Gunicorn with --log-level debug.

It should give you an app stack trace.

Go To Definition: "Cannot navigate to the symbol under the caret."

The last couple of days I've been getting this error, at least twice a day.. really annoying! None of the solutions proposed here has worked for me. What I found, and since it was pretty difficult to find I'm writing it down here, was to:

  • Close Visual
  • Open Console and navigate to Visual installation folder, in my computer is C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE
  • run devenv.exe /resetuserdata
  • Open Visual Studio, it's going to take some time to load.

Disclaimer: I'm using Xamarin

TAKE INTO CONSIDERATION WHAT @OzSolomon and @xCasper HAVE SAID:

@OzSolomon

Know that this will reset many of your IDE customization, including installed plugins.

Make sure you're comfortable with that before using /resetuserdata

@xCasper

If you have your settings synced through Microsoft, however, most of the preferences seem to restore themselves. I say most because it seems my keybindings did not restore and are back to being default. Everything else, such as my selected theme and colorization choices, the layout of my IDE (where I have tabs for instance), and what not seem to of come back.

LINQ syntax where string value is not null or empty

This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.

The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.

Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)

How to get full width in body element

If its in a landscape then you will be needing more width and less height! That's just what all websites have.

Lets go with a basic first then the rest!

The basic CSS:

By CSS you can do this,

#body {
width: 100%;
height: 100%;
}

Here you are using a div with id body, as:

<body>
  <div id="body>
    all the text would go here!
  </div>
</body>

Then you can have a web page with 100% height and width.

What if he tries to resize the window?

The issues pops up, what if he tries to resize the window? Then all the elements inside #body would try to mess up the UI. For that you can write this:

#body {
height: 100%;
width: 100%;
}

And just add min-height max-height min-width and max-width.

This way, the page element would stay at the place they were at the page load.

Using JavaScript:

Using JavaScript, you can control the UI, use jQuery as:

$('#body').css('min-height', '100%');

And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.

How to not add scroll to the web page:

If you are not trying to add a scroll, then you can use this JS

$('#body').css('min-height', screen.height); // or anyother like window.height

This way, the document will get a new height whenever the user would load the page.

Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!

Tip: So try using JS to find current Screen size and edit the page! :)

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

Disable button in angular with two conditions?

Using the ternary operator is possible like following.[disabled] internally required true or false for its operation.

<button type="button" 
  [disabled]="(testVariable1 != 0 || testVariable2!=0)? true:false"
  mat-button>Button</button>

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

About catching ANY exception

You can do this to handle general exceptions

try:
    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message

error: function returns address of local variable

a is an array local to the function.Once the function returns it does not exist anymore and hence you should not return the address of a local variable.
In other words the lifetime of a is within the scope({,}) of the function and if you return a pointer to it what you have is a pointer pointing to some memory which is not valid. Such variables are also called automatic variabels because their lifetime is automatically managed you do not need to manage it explicitly.

Since you need to extend the variable to persist beyond the scope of the function you You need to allocate a array on heap and return a pointer to it.

char *a = malloc(1000); 

This way the array a resides in memory untill you call a free() on the same address.
Do not forget to do so or you end up with a memory leak.

Write string to text file and ensure it always overwrites the existing content.

System.IO.File.WriteAllText (@"D:\path.txt", contents);
  • If the file exists, this overwrites it.
  • If the file does not exist, this creates it.
  • Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.

JavaFX: How to get stage from controller during initialization?

Assign fx:id or declare variable to/of any node: anchorpane, button, etc. Then add event handler to it and within that event handler insert the given code below:

Stage stage = (Stage)((Node)((EventObject) eventVariable).getSource()).getScene().getWindow();

Hope, this works for you!!

How to get substring of NSString?

Here is a little combination of @Regexident Option 1 and @Garett answers, to get a powerful string cutter between a prefix and suffix, with MORE...ANDMORE words on it.

NSString *haystack = @"MOREvalue:hello World:valueANDMORE";
NSString *prefix = @"value:";
NSString *suffix = @":value";
NSRange prefixRange = [haystack rangeOfString:prefix];
NSRange suffixRange = [[haystack substringFromIndex:prefixRange.location+prefixRange.length] rangeOfString:suffix];
NSRange needleRange = NSMakeRange(prefixRange.location+prefix.length, suffixRange.location);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle);

How to add element into ArrayList in HashMap

HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();

public synchronized void addToList(String mapKey, Item myItem) {
    List<Item> itemsList = items.get(mapKey);

    // if list does not exist create it
    if(itemsList == null) {
         itemsList = new ArrayList<Item>();
         itemsList.add(myItem);
         items.put(mapKey, itemsList);
    } else {
        // add if item is not already in list
        if(!itemsList.contains(myItem)) itemsList.add(myItem);
    }
}

Align Bootstrap Navigation to Center

Thank you all for your help, I added this code and it seems it fixed the issue:

.navbar .navbar-nav {
    display: inline-block;
    float: none;
}

.navbar .navbar-collapse {
    text-align: center;
}

Source

Center content in responsive bootstrap navbar

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

Unit testing with Spring Security

General

In the meantime (since version 3.2, in the year 2013, thanks to SEC-2298) the authentication can be injected into MVC methods using the annotation @AuthenticationPrincipal:

@Controller
class Controller {
  @RequestMapping("/somewhere")
  public void doStuff(@AuthenticationPrincipal UserDetails myUser) {
  }
}

Tests

In your unit test you can obviously call this Method directly. In integration tests using org.springframework.test.web.servlet.MockMvc you can use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user() to inject the user like this:

mockMvc.perform(get("/somewhere").with(user(myUserDetails)));

This will however just directly fill the SecurityContext. If you want to make sure that the user is loaded from a session in your test, you can use this:

mockMvc.perform(get("/somewhere").with(sessionUser(myUserDetails)));
/* ... */
private static RequestPostProcessor sessionUser(final UserDetails userDetails) {
    return new RequestPostProcessor() {
        @Override
        public MockHttpServletRequest postProcessRequest(final MockHttpServletRequest request) {
            final SecurityContext securityContext = new SecurityContextImpl();
            securityContext.setAuthentication(
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities())
            );
            request.getSession().setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext
            );
            return request;
        }
    };
}

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

To prevent this dialog box from appearing, do the following:

  1. Right click on the setup.exe for the Oracle 11g 32-bit client, and select Properties.
  2. Select the Compatibility tab, and set the Compatibility mode to Windows 7. Click OK to close the Properties tab.
  3. Double click setup.exe to install the client.

Deciding between HttpClient and WebClient

HttpClient is the newer of the APIs and it has the benefits of

  • has a good async programming model
  • being worked on by Henrik F Nielson who is basically one of the inventors of HTTP, and he designed the API so it is easy for you to follow the HTTP standard, e.g. generating standards-compliant headers
  • is in the .Net framework 4.5, so it has some guaranteed level of support for the forseeable future
  • also has the xcopyable/portable-framework version of the library if you want to use it on other platforms - .Net 4.0, Windows Phone etc.

If you are writing a web service which is making REST calls to other web services, you should want to be using an async programming model for all your REST calls, so that you don't hit thread starvation. You probably also want to use the newest C# compiler which has async/await support.

Note: It isn't more performant AFAIK. It's probably somewhat similarly performant if you create a fair test.

Convert a byte array to integer in Java and vice versa

i think this is a best mode to cast to int

   public int ByteToint(Byte B){
        String comb;
        int out=0;
        comb=B+"";
        salida= Integer.parseInt(comb);
        out=out+128;
        return out;
    }

first comvert byte to String

comb=B+"";

next step is comvert to a int

out= Integer.parseInt(comb);

but byte is in rage of -128 to 127 for this reasone, i think is better use rage 0 to 255 and you only need to do this:

out=out+256;

How to disable mouse scroll wheel scaling with Google Maps API

As of now (October 2017) Google has implemented a specific property to handle the zooming/scrolling, called gestureHandling. Its purpose is to handle mobile devices operation, but it modifies the behaviour for desktop browsers as well. Here it is from official documentation:

function initMap() {
  var locationRio = {lat: -22.915, lng: -43.197};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: locationRio,
    gestureHandling: 'none'
});

The available values for gestureHandling are:

  • 'greedy': The map always pans (up or down, left or right) when the user swipes (drags on) the screen. In other words, both a one-finger swipe and a two-finger swipe cause the map to pan.
  • 'cooperative': The user must swipe with one finger to scroll the page and two fingers to pan the map. If the user swipes the map with one finger, an overlay appears on the map, with a prompt telling the user to use two fingers to move the map. On desktop applications, users can zoom or pan the map by scrolling while pressing a modifier key (the ctrl or ? key).
  • 'none': This option disables panning and pinching on the map for mobile devices, and dragging of the map on desktop devices.
  • 'auto' (default): Depending on whether the page is scrollable, the Google Maps JavaScript API sets the gestureHandling property to either 'cooperative' or 'greedy'

In short, you can easily force the setting to "always zoomable" ('greedy'), "never zoomable" ('none'), or "user must press CRTL/? to enable zoom" ('cooperative').

Getting the last argument passed to a shell script

I found @AgileZebra's answer (plus @starfry's comment) the most useful, but it sets heads to a scalar. An array is probably more useful:

heads=( "${@:1:$(($# - 1))}" )
tail=${@:${#@}}

Note that this is bash-only.

How do you add multi-line text to a UIButton?

It works perfectly.

Add to use this with config file like Plist, you need to use CDATA to write the multilined title, like this:

<string><![CDATA[Line1
Line2]]></string>

When should I use mmap for file access?

One area where I found mmap() to not be an advantage was when reading small files (under 16K). The overhead of page faulting to read the whole file was very high compared with just doing a single read() system call. This is because the kernel can sometimes satisify a read entirely in your time slice, meaning your code doesn't switch away. With a page fault, it seemed more likely that another program would be scheduled, making the file operation have a higher latency.

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

Actually, the default directory where the mongod instance stores its data is

/data/db on Linux and OS X,

\data\db on Windows

To check the same, you can look for dbPath settings in mongodb configuration file.

  • On Linux, the location is /etc/mongod.conf, if you have used package manager to install MongoDB. Run the following command to check the specified directory:
    grep dbpath /etc/mongodb.conf
    
  • On Windows, the location is <install directory>/bin/mongod.cfg. Open mongod.cfg file and check for dbPath option.
  • On macOS, the location is /usr/local/etc/mongod.conf when installing from MongoDB’s official Homebrew tap.

The default mongod.conf configuration file included with package manager installations uses the following platform-specific default values for storage.dbPath:

+--------------------------+-----------------+------------------------+
|         Platform         | Package Manager | Default storage.dbPath |
+--------------------------+-----------------+------------------------+
| RHEL / CentOS and Amazon | yum             | /var/lib/mongo         |
| SUSE                     | zypper          | /var/lib/mongo         |
| Ubuntu and Debian        | apt             | /var/lib/mongodb       |
| macOS                    | brew            | /usr/local/var/mongodb |
+--------------------------+-----------------+------------------------+

The storage.dbPath setting in the configuration file is available only for mongod.

The Linux package init scripts do not expect storage.dbPath to change from the defaults. If you use the Linux packages and change storage.dbPath, you will have to use your own init scripts and disable the built-in scripts.

Source

How to get dictionary values as a generic list

You probably want to flatten all of the lists in Values into a single list:

List<MyType> allItems = myDico.Values.SelectMany(c => c).ToList();

Getting MAC Address

Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:

from uuid import getnode as get_mac
mac = get_mac()

The return value is the mac address as 48 bit integer.

How do I set response headers in Flask?

This was how added my headers in my flask application and it worked perfectly

@app.after_request
def add_header(response):
    response.headers['X-Content-Type-Options'] = 'nosniff'
    return response

The apk must be signed with the same certificates as the previous version

Nothing. Read the documentation: Publishing Updates on Android Market

Before uploading the updated application, be sure that you have incremented the android:versionCode and android:versionName attributes in the element of the manifest file. Also, the package name must be the same and the .apk must be signed with the same private key. If the package name and signing certificate do not match those of the existing version, Market will consider it a new application and will not offer it to users as an update.

data.frame rows to a list

Eureka!

xy.list <- as.list(as.data.frame(t(xy.df)))

PHP Warning Permission denied (13) on session_start()

I have had this issue before, you need more than the standard 755 or 644 permission to store the $_SESSION information. You need to be able to write to that file as that is how it remembers.

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

I think that more accurate is this syntax:

SELECT CONVERT(CHAR(10), GETDATE(), 103)

I add SELECT and GETDATE() for instant testing purposes :)

Sending and Parsing JSON Objects in Android

GSON is easiest to use and the way to go if the data have a definite structure.

Download gson.

Add it to the referenced libraries.

package com.tut.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SimpleJson extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String jString = "{\"username\": \"tom\", \"message\": \"roger that\"}  ";


        GsonBuilder gsonb = new GsonBuilder();
        Gson gson = gsonb.create();
        Post pst;

        try {
            pst = gson.fromJson(jString,  Post.class);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Code for Post class

package com.tut.JSON;

public class Post {

    String message;
    String time;
    String username;
    Bitmap icon;
}

what is the use of Eval() in asp.net

Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.

It is generally used for late-bound data (not known from start) and usually bound to the smallest part of the data-bound control that contains a whole record. The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

For this, I use FLAG_ACTIVITY_CLEAR_TOP flag for starting Intent
(without FLAG_ACTIVITY_NEW_TASK)

and launchMode = "singleTask" in manifest for launched activity.

Seems like it works as I need - activity does not restart and all other activities are closed.

what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

Given this example url:

http://www.example.com/some-dir/yourpage.php?q=bogus&n=10

$_SERVER['REQUEST_URI'] will give you:

/some-dir/yourpage.php?q=bogus&n=10

Whereas $_GET['q'] will give you:

bogus

In other words, $_SERVER['REQUEST_URI'] will hold the full request path including the querystring. And $_GET['q'] will give you the value of parameter q in the querystring.

Java BigDecimal: Round to the nearest whole value

I don't think you can round it like that in a single command. Try

    ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
    list.add(new BigDecimal("100.12"));
    list.add(new BigDecimal("100.44"));
    list.add(new BigDecimal("100.50"));
    list.add(new BigDecimal("100.75"));

    for (BigDecimal bd : list){
        System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
    }

Output:
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

New line in Sql Query

use CHAR(10) for New Line in SQL
char(9) for Tab
and Char(13) for Carriage Return

command/usr/bin/codesign failed with exit code 1- code sign error

delete your certificate in your dev then Reinstall and it will working!

Can I call an overloaded constructor from another constructor of the same class in C#?

EDIT: According to the comments on the original post this is a C# question.

Short answer: yes, using the this keyword.

Long answer: yes, using the this keyword, and here's an example.

class MyClass
{
   private object someData;

   public MyClass(object data)
   {
      this.someData = data;
   }

   public MyClass() : this(new object())
   {
      // Calls the previous constructor with a new object, 
      // setting someData to that object
   }
}

How to check null objects in jQuery

if (typeof($("#btext" + i)) == 'object'){
    $("#btext" + i).text("Branch " + i);
}

bash script use cut command at variable and store result at another variable

The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

You could write your top line as

for line in $(cat $file) ; do ...

(but not recommended).

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I have build a sample android studio project for this question.

output screen shots :-

enter image description here

enter image description here

enter image description here

Download full project source code Click here

Please note: you have to add your API key in Androidmanifest.xml

How to output loop.counter in python jinja template?

The counter variable inside the loop is called loop.index in jinja2.

>>> from jinja2 import Template

>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4

See http://jinja.pocoo.org/docs/templates/ for more.

Check if checkbox is NOT checked on click - jQuery

The Answer already posted .But We can use the jquery in this way also

demo

$(function(){
    $('#check1').click(function() {
        if($('#check1').attr('checked'))
            alert('checked');
        else
            alert('unchecked');
    });

    $('#check2').click(function() {
        if(!$('#check2').attr('checked'))
            alert('unchecked');
        else
            alert('checked');
    });
});

Difference between Git and GitHub

Github is required if you want to collaborate across developers. If you are a single contributor git is enough, make sure you backup your code on regular basis

IBOutlet and IBAction

IBAction and IBOutlet are macros defined to denote variables and methods that can be referred to in Interface Builder.

IBAction resolves to void and IBOutlet resolves to nothing, but they signify to Xcode and Interface builder that these variables and methods can be used in Interface builder to link UI elements to your code.

If you're not going to be using Interface Builder at all, then you don't need them in your code, but if you are going to use it, then you need to specify IBAction for methods that will be used in IB and IBOutlet for objects that will be used in IB.

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

I just ran into this problem and stumbled across a different situation. Although it's probably just a unicorn, I thought I'd lay it out.

I had one session that was smaller, and I noticed that the font sizes were different: the smaller session had the smaller fonts. Apparently, I had changed window font sizes for some reason.

So in OS X, I just did Cmd-+ on the smaller sized session, and it snapped back into place.

Installing specific laravel version with composer create-project

If you want to use a stable version of your preferred Laravel version of choice, use:

composer create-project --prefer-dist laravel/laravel project-name "5.5.*"

That will pick out the most recent or best update of version 5.5.* (5.5.28)

How to center the text in PHPExcel merged cell

<?php
    /** Error reporting */
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    date_default_timezone_set('Europe/London');

    /** Include PHPExcel */
    require_once '../Classes/PHPExcel.php';

    $objPHPExcel = new PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValueByColumnAndRow(0, 1, "test");
    $sheet->mergeCells('A1:B1');
    $sheet->getActiveSheet()->getStyle('A1:B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save("test.xlsx");
?>

Setting action for back button in navigation controller

Using Swift:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if self.navigationController?.topViewController != self {
        print("back button tapped")
    }
}

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

can you try if.else

> col2=ifelse(df1$col=="true",1,0)
> df1
$col
[1] "true"  "false"

> cbind(df1$col)
     [,1]   
[1,] "true" 
[2,] "false"
> cbind(df1$col,col2)
             col2
[1,] "true"  "1" 
[2,] "false" "0" 

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

Just for completeness. There is another situation causing this error:

missing META-INF/services/javax.persistence.spi.PersistenceProvider file.

For Hibernate, it's located in hibernate-entitymanager-XXX.jar, so, if hibernate-entitymanager-XXX.jar is not in your classpath, you will got this error too.

This error message is so misleading, and it costs me hours to get it correct.

See JPA 2.0 using Hibernate as provider - Exception: No Persistence provider for EntityManager.

TypeError: Missing 1 required positional argument: 'self'

You need to initialize it first:

p = Pump().getPumps()

How to convert OutputStream to InputStream?

I encountered the same problem with converting a ByteArrayOutputStream to a ByteArrayInputStream and solved it by using a derived class from ByteArrayOutputStream which is able to return a ByteArrayInputStream that is initialized with the internal buffer of the ByteArrayOutputStream. This way no additional memory is used and the 'conversion' is very fast:

package info.whitebyte.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * This class extends the ByteArrayOutputStream by 
 * providing a method that returns a new ByteArrayInputStream
 * which uses the internal byte array buffer. This buffer
 * is not copied, so no additional memory is used. After
 * creating the ByteArrayInputStream the instance of the
 * ByteArrayInOutStream can not be used anymore.
 * <p>
 * The ByteArrayInputStream can be retrieved using <code>getInputStream()</code>.
 * @author Nick Russler
 */
public class ByteArrayInOutStream extends ByteArrayOutputStream {
    /**
     * Creates a new ByteArrayInOutStream. The buffer capacity is
     * initially 32 bytes, though its size increases if necessary.
     */
    public ByteArrayInOutStream() {
        super();
    }

    /**
     * Creates a new ByteArrayInOutStream, with a buffer capacity of
     * the specified size, in bytes.
     *
     * @param   size   the initial size.
     * @exception  IllegalArgumentException if size is negative.
     */
    public ByteArrayInOutStream(int size) {
        super(size);
    }

    /**
     * Creates a new ByteArrayInputStream that uses the internal byte array buffer 
     * of this ByteArrayInOutStream instance as its buffer array. The initial value 
     * of pos is set to zero and the initial value of count is the number of bytes 
     * that can be read from the byte array. The buffer array is not copied. This 
     * instance of ByteArrayInOutStream can not be used anymore after calling this
     * method.
     * @return the ByteArrayInputStream instance
     */
    public ByteArrayInputStream getInputStream() {
        // create new ByteArrayInputStream that respects the current count
        ByteArrayInputStream in = new ByteArrayInputStream(this.buf, 0, this.count);

        // set the buffer of the ByteArrayOutputStream 
        // to null so it can't be altered anymore
        this.buf = null;

        return in;
    }
}

I put the stuff on github: https://github.com/nickrussler/ByteArrayInOutStream

How to check if another instance of my shell script is running

I didn't want to hardcode abc.sh in the check, so I used the following:

MY_SCRIPT_NAME=`basename "$0"`
if pidof -o %PPID -x $MY_SCRIPT_NAME > /dev/null; then
    echo "$MY_SCRIPT_NAME already running; exiting"
    exit 1
fi

What is the difference between And and AndAlso in VB.NET?

For majority of us OrElse and AndAlso will do the trick except for a few confusing exceptions (less than 1% where we may have to use Or and And).

Try not to get carried away by people showing off their boolean logics and making it look like a rocket science.

It's quite simple and straight forward and occasionally your system may not work as expected because it doesn't like your logic in the first place. And yet your brain keeps telling you that his logic is 100% tested and proven and it should work. At that very moment stop trusting your brain and ask him to think again or (not OrElse or maybe OrElse) you force yourself to look for another job that doesn't require much logic.

Child element click event trigger the parent click event

Click event Bubbles, now what is meant by bubbling, a good point to starts is here. you can use event.stopPropagation(), if you don't want that event should propagate further.

Also a good link to refer on MDN

Big-O summary for Java Collections Framework implementations?

The Javadocs from Sun for each collection class will generally tell you exactly what you want. HashMap, for example:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).

TreeMap:

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

TreeSet:

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

(emphasis mine)

How to sum columns in a dataTable?

You can loop through the DataColumn and DataRow collections in your DataTable:

// Sum rows.
foreach (DataRow row in dt.Rows) {
    int rowTotal = 0;
    foreach (DataColumn col in row.Table.Columns) {
        Console.WriteLine(row[col]);
        rowTotal += Int32.Parse(row[col].ToString());
    }
    Console.WriteLine("row total: {0}", rowTotal);
}
// Sum columns.
foreach (DataColumn col in dt.Columns) {
    int colTotal = 0;
    foreach (DataRow row in col.Table.Rows) {
        Console.WriteLine(row[col]);
        colTotal += Int32.Parse(row[col].ToString());
    }
    Console.WriteLine("column total: {0}", colTotal);
}

Beware: The code above does not do any sort of checking before casting an object to an int.

EDIT: add a DataRow displaying the column sums

Try this to create a new row to display your column sums:

DataRow totalsRow = dt.NewRow();
foreach (DataColumn col in dt.Columns) {
    int colTotal = 0;
    foreach (DataRow row in col.Table.Rows) {
        colTotal += Int32.Parse(row[col].ToString());
    }
    totalsRow[col.ColumnName] = colTotal;
}
dt.Rows.Add(totalsRow);

This approach is fine if the data type of any of your DataTable's DataRows are non-numeric or if you want to inspect the value of each cell as you sum. Otherwise I believe @Tim's response using DataTable.Compute is a better.

Difference between Inheritance and Composition

Are Composition and Inheritance the same?

They are not same.

Composition : It enables a group of objects have to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies

Inheritance: A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits.

If I want to implement the composition pattern, how can I do that in Java?

Wikipedia article is good enough to implement composite pattern in java.

enter image description here

Key Participants:

Component:

  1. Is the abstraction for all components, including composite ones
  2. Declares the interface for objects in the composition

Leaf:

  1. Represents leaf objects in the composition
  2. Implements all Component methods

Composite:

  1. Represents a composite Component (component having children)
  2. Implements methods to manipulate children
  3. Implements all Component methods, generally by delegating them to its children

Code example to understand Composite pattern:

import java.util.List;
import java.util.ArrayList;

interface Part{
    public double getPrice();
    public String getName();
}
class Engine implements Part{
    String name;
    double price;
    public Engine(String name,double price){
        this.name = name;
        this.price = price;
    }
    public double getPrice(){
        return price;
    }
    public String getName(){
        return name;
    }
}
class Trunk implements Part{
    String name;
    double price;
    public Trunk(String name,double price){
        this.name = name;
        this.price = price;
    }
    public double getPrice(){
        return price;
    }
    public String getName(){
        return name;
    }
}
class Body implements Part{
    String name;
    double price;
    public Body(String name,double price){
        this.name = name;
        this.price = price;
    }
    public double getPrice(){
        return price;
    }
    public String getName(){
        return name;
    }
}
class Car implements Part{
    List<Part> parts;
    String name;

    public Car(String name){
        this.name = name;
        parts = new ArrayList<Part>();
    }
    public void addPart(Part part){
        parts.add(part);
    }
    public String getName(){
        return name;
    }
    public String getPartNames(){
        StringBuilder sb = new StringBuilder();
        for ( Part part: parts){
            sb.append(part.getName()).append(" ");
        }
        return sb.toString();
    }
    public double getPrice(){
        double price = 0;
        for ( Part part: parts){
            price += part.getPrice();
        }
        return price;
    }   
}

public class CompositeDemo{
    public static void main(String args[]){
        Part engine = new Engine("DiselEngine",15000);
        Part trunk = new Trunk("Trunk",10000);
        Part body = new Body("Body",12000);

        Car car = new Car("Innova");
        car.addPart(engine);
        car.addPart(trunk);
        car.addPart(body);

        double price = car.getPrice();

        System.out.println("Car name:"+car.getName());
        System.out.println("Car parts:"+car.getPartNames());
        System.out.println("Car price:"+car.getPrice());
    }

}

output:

Car name:Innova
Car parts:DiselEngine Trunk Body
Car price:37000.0

Explanation:

  1. Part is a leaf
  2. Car contains many Parts
  3. Different Parts of the car have been added to Car
  4. The price of Car = sum of ( Price of each Part )

Refer to below question for Pros and Cons of Composition and Inheritance.

Prefer composition over inheritance?

Is there a simple way to use button to navigate page as a link does in angularjs

Your ngClick is correct; you just need the right service. $location is what you're looking for. Check out the docs for the full details, but the solution to your specific question is this:

$location.path( '/new-page.html' );

The $location service will add the hash (#) if it's appropriate based on your current settings and ensure no page reload occurs.

You could also do something more flexible with a directive if you so chose:

.directive( 'goClick', function ( $location ) {
  return function ( scope, element, attrs ) {
    var path;

    attrs.$observe( 'goClick', function (val) {
      path = val;
    });

    element.bind( 'click', function () {
      scope.$apply( function () {
        $location.path( path );
      });
    });
  };
});

And then you could use it on anything:

<button go-click="/go/to/this">Click!</button>

There are many ways to improve this directive; it's merely to show what could be done. Here's a Plunker demonstrating it in action: http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=preview.

How do you input command line arguments in IntelliJ IDEA?

maytham-???i???, you can use this code to simulate input of file:

System.setIn(new FileInputStream("FILE_NAME"));

Or send file name as parameter and then put it into FileInputStream:

System.setIn(new FileInputStream(args[0]));

Strings in C, how to get subString

#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator

How can I represent an 'Enum' in Python?

What I use:

class Enum(object):
    def __init__(self, names, separator=None):
        self.names = names.split(separator)
        for value, name in enumerate(self.names):
            setattr(self, name.upper(), value)
    def tuples(self):
        return tuple(enumerate(self.names))

How to use:

>>> state = Enum('draft published retracted')
>>> state.DRAFT
0
>>> state.RETRACTED
2
>>> state.FOO
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'Enum' object has no attribute 'FOO'
>>> state.tuples()
((0, 'draft'), (1, 'published'), (2, 'retracted'))

So this gives you integer constants like state.PUBLISHED and the two-tuples to use as choices in Django models.

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

What are you doing: (I am using bytes instead of in for better reading)

You start with int *ap and so on, so your (your computers) memory looks like this:

-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory  --------
100: something          <- here is *ap
101: 41                 <- here starts a[] 
102: 42
103: 43
104: 44
105: 45
106: something          <- here waits x

lets take a look waht happens when (print short cut for ...print("$d", ...)

print a[0]  -> 41   //no surprise
print a     -> 101  // because a points to the start of the array
print *a    -> 41   // again the first element of array
print a+1   -> guess? 102
print *(a+1)    -> whats behind 102? 42 (we all love this number)

and so on, so a[0] is the same as *a, a[1] = *(a+1), ....

a[n] just reads easier.

now, what happens at line 9?

ap=a[4] // we know a[4]=*(a+4) somehow *105 ==>  45 
// warning! converting int to pointer!
-------------- your memory  --------
100: 45         <- here is *ap now 45

x = *ap;   // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang!      // dont touch neighbours garden

So the "warning" is not just a warning it's a severe error.

How to print a single backslash?

You need to escape your backslash by preceding it with, yes, another backslash:

print("\\")

And for versions prior to Python 3:

print "\\"

The \ character is called an escape character, which interprets the character following it differently. For example, n by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character.

As you can probably guess, \ also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.

See the Python 3 documentation for string literals.

How does `scp` differ from `rsync`?

rysnc can be useful to run on slow and unreliable connections. So if your download aborts in the middle of a large file rysnc will be able to continue from where it left off when invoked again.

Use rsync -vP username@host:/path/to/file .

The -P option preserves partially downloaded files and also shows progress.

As usual check man rsync

Angularjs - Pass argument to directive

<button my-directive="push">Push to Go</button>

app.directive("myDirective", function() {
    return {
        restrict : "A",
         link: function(scope, elm, attrs) {
                elm.bind('click', function(event) {

                    alert("You pressed button: " + event.target.getAttribute('my-directive'));
                });
        }
    };
});

here is what I did

I'm using directive as html attribute and I passed parameter as following in my HTML file. my-directive="push" And from the directive I retrieved it from the Mouse-click event object. event.target.getAttribute('my-directive').

Round to 2 decimal places

Create a class called Round and try using the method round as Round.round(targetValue, roundToDecimalPlaces) in your code

public class Round {

        public static float round(float targetValue, int roundToDecimalPlaces ){

            int valueInTwoDecimalPlaces = (int) (targetValue * Math.pow(10, roundToDecimalPlaces));

            return (float) (valueInTwoDecimalPlaces / Math.pow(10, roundToDecimalPlaces));
        }

    }

Get current directory name (without full path) in a Bash script

You can use a combination of pwd and basename. E.g.

#!/bin/bash

CURRENT=`pwd`
BASENAME=`basename "$CURRENT"`

echo "$BASENAME"

exit;

How to hide a div from code (c#)

In code behind:

{
    yourDiv.Visible = false;
}

How to use pip on windows behind an authenticating proxy

same issue on windows10 and above solutions are not working for me.

use a emulator console tool like cygwin and then do it the default linux way:

export http_proxy=<proxy>
export https_proxy=<proxy>
pip install <package>

and things are working fine.

How to subtract X day from a Date object in Java?

@JigarJoshi it's the good answer, and of course also @Tim recommendation to use .joda-time.

I only want to add more possibilities to subtract days from a java.util.Date.

Apache-commons

One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:

Date dateBefore30Days = DateUtils.addDays(new Date(),-30);

Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.

Java 8

Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:

LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);

How exactly to use Notification.Builder

I was having a problem building notifications (only developing for Android 4.0+). This link showed me exactly what I was doing wrong and says the following:

Required notification contents

A Notification object must contain the following:

A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()

Basically I was missing one of these. Just as a basis for troubleshooting with this, make sure you have all of these at the very least. Hopefully this will save someone else a headache.

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

I had the same problem in my Vue.js and SpringBoot projects. If somebody work with spring you can add this code:

@Bean
public FilterRegistrationBean simpleCorsFilter() {  
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  
    CorsConfiguration config = new CorsConfiguration();  
    config.setAllowCredentials(true); 
    // *** URL below needs to match the Vue client URL and port ***
    config.setAllowedOrigins(Collections.singletonList("http://localhost:8080")); 
    config.setAllowedMethods(Collections.singletonList("*"));  
    config.setAllowedHeaders(Collections.singletonList("*"));  
    source.registerCorsConfiguration("/**", config);  
    FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);  
    return bean;  
}   

I found solution in this article Build a Simple CRUD App with Spring Boot and Vue.js

Insert a row to pandas dataframe

One way to achieve this is

>>> pd.DataFrame(np.array([[2, 3, 4]]), columns=['A', 'B', 'C']).append(df, ignore_index=True)
Out[330]: 
   A  B  C
0  2  3  4
1  5  6  7
2  7  8  9

Generally, it's easiest to append dataframes, not series. In your case, since you want the new row to be "on top" (with starting id), and there is no function pd.prepend(), I first create the new dataframe and then append your old one.

ignore_index will ignore the old ongoing index in your dataframe and ensure that the first row actually starts with index 1 instead of restarting with index 0.

Typical Disclaimer: Cetero censeo ... appending rows is a quite inefficient operation. If you care about performance and can somehow ensure to first create a dataframe with the correct (longer) index and then just inserting the additional row into the dataframe, you should definitely do that. See:

>>> index = np.array([0, 1, 2])
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[0:1] = [list(s1), list(s2)]
>>> df2
Out[336]: 
     A    B    C
0    5    6    7
1    7    8    9
2  NaN  NaN  NaN
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[1:] = [list(s1), list(s2)]

So far, we have what you had as df:

>>> df2
Out[339]: 
     A    B    C
0  NaN  NaN  NaN
1    5    6    7
2    7    8    9

But now you can easily insert the row as follows. Since the space was preallocated, this is more efficient.

>>> df2.loc[0] = np.array([2, 3, 4])
>>> df2
Out[341]: 
   A  B  C
0  2  3  4
1  5  6  7
2  7  8  9

align right in a table cell with CSS

Use

text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

See

text-align

<td class='alnright'>text to be aligned to right</td>

<style>
    .alnright { text-align: right; }
</style>

Changing the action of a form with JavaScript/jQuery

just to add a detail to what Tamlyn wrote, instead of
$('form').get(0).setAttribute('action', 'baz'); //this works

$('form')[0].setAttribute('action', 'baz');
works equally well

What is two way binding?

Two-way binding just means that:

  1. When properties in the model get updated, so does the UI.
  2. When UI elements get updated, the changes get propagated back to the model.

Backbone doesn't have a "baked-in" implementation of #2 (although you can certainly do it using event listeners). Other frameworks like Knockout do wire up two-way binding automagically.


enter image description here


In Backbone, you can easily achieve #1 by binding a view's "render" method to its model's "change" event. To achieve #2, you need to also add a change listener to the input element, and call model.set in the handler.

Here's a Fiddle with two-way binding set up in Backbone.

How to set a parameter in a HttpServletRequest?

The missing getParameterMap override ended up being a real problem for me. So this is what I ended up with:

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/***
 * Request wrapper enabling the update of a request-parameter.
 * 
 * @author E.K. de Lang
 *
 */
final class HttpServletRequestReplaceParameterWrapper
    extends HttpServletRequestWrapper
{

    private final Map<String, String[]> keyValues;

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, String key, String value)
    {
        super(request);

        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        // Can override the values in the request
        keyValues.put(key, new String[] { value });

    }

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, Map<String, String> additionalRequestParameters)
    {
        super(request);
        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        for (Map.Entry<String, String> entry : additionalRequestParameters.entrySet()) {
            keyValues.put(entry.getKey(), new String[] { entry.getValue() });
        }

    }

    @Override
    public String getParameter(String name)
    {
        if (keyValues.containsKey(name)) {
            String[] strings = keyValues.get(name);
            if (strings == null || strings.length == 0) {
                return null;
            }
            else {
                return strings[0];
            }
        }
        else {
            // Just in case the request has some tricks of it's own.
            return super.getParameter(name);
        }
    }

    @Override
    public String[] getParameterValues(String name)
    {
        String[] value = this.keyValues.get(name);
        if (value == null) {
            // Just in case the request has some tricks of it's own.
            return super.getParameterValues(name);
        }
        else {
            return value;
        }
    }

    @Override
    public Map<String, String[]> getParameterMap()
    {
        return this.keyValues;
    }

}

When should I use the Visitor Design Pattern?

The Visitor design pattern works really well for "recursive" structures like directory trees, XML structures, or document outlines.

A Visitor object visits each node in the recursive structure: each directory, each XML tag, whatever. The Visitor object doesn't loop through the structure. Instead Visitor methods are applied to each node of the structure.

Here's a typical recursive node structure. Could be a directory or an XML tag. [If your a Java person, imagine of a lot of extra methods to build and maintain the children list.]

class TreeNode( object ):
    def __init__( self, name, *children ):
        self.name= name
        self.children= children
    def visit( self, someVisitor ):
        someVisitor.arrivedAt( self )
        someVisitor.down()
        for c in self.children:
            c.visit( someVisitor )
        someVisitor.up()

The visit method applies a Visitor object to each node in the structure. In this case, it's a top-down visitor. You can change the structure of the visit method to do bottom-up or some other ordering.

Here's a superclass for visitors. It's used by the visit method. It "arrives at" each node in the structure. Since the visit method calls up and down, the visitor can keep track of the depth.

class Visitor( object ):
    def __init__( self ):
        self.depth= 0
    def down( self ):
        self.depth += 1
    def up( self ):
        self.depth -= 1
    def arrivedAt( self, aTreeNode ):
        print self.depth, aTreeNode.name

A subclass could do things like count nodes at each level and accumulate a list of nodes, generating a nice path hierarchical section numbers.

Here's an application. It builds a tree structure, someTree. It creates a Visitor, dumpNodes.

Then it applies the dumpNodes to the tree. The dumpNode object will "visit" each node in the tree.

someTree= TreeNode( "Top", TreeNode("c1"), TreeNode("c2"), TreeNode("c3") )
dumpNodes= Visitor()
someTree.visit( dumpNodes )

The TreeNode visit algorithm will assure that every TreeNode is used as an argument to the Visitor's arrivedAt method.

Squash the first two commits in Git?

You could use rebase interactive to modify the last two commits before they've been pushed to a remote

git rebase HEAD^^ -i

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

I'd like to give my give my practice.

Use your preferred IDE, take eclipse for for example here:

  1. Find an appropriate location within the exception stack
  2. Set conditional breakpoint
  3. Debug it
  4. It will print the corrupted jar before exception

enter image description here

Redirect to specified URL on PHP script completion?

Note that this will not work:

header('Location: $url');

You need to do this (for variable expansion):

header("Location: $url");

TypeScript: Property does not exist on type '{}'

let propertyName= data['propertyName'];

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

In the old days, "/opt" was used by UNIX vendors like AT&T, Sun, DEC and 3rd-party vendors to hold "Option" packages; i.e. packages that you might have paid extra money for. I don't recall seeing "/opt" on Berkeley BSD UNIX. They used "/usr/local" for stuff that you installed yourself.

But of course, the true "meaning" of the different directories has always been somewhat vague. That is arguably a good thing, because if these directories had precise (and rigidly enforced) meanings you'd end up with a proliferation of different directory names.

According to the Filesystem Hierarchy Standard, /opt is for "the installation of add-on application software packages". /usr/local is "for use by the system administrator when installing software locally".

z-index not working with position absolute

The second div is position: static (the default) so the z-index does not apply to it.

You need to position (set the position property to anything other than static, you probably want relative in this case) anything you want to give a z-index to.

How to convert a datetime to string in T-SQL

There are 3 different methods depending on what I is my requirement and which version I am using.

Here are the methods..

1) Using Convert

DECLARE @DateTime DATETIME = GETDATE();
--Using Convert
SELECT
    CONVERT(NVARCHAR, @DateTime,120) AS 'myDateTime'
    ,CONVERT(NVARCHAR(10), @DateTime, 120) AS 'myDate'
    ,RIGHT(CONVERT(NVARCHAR, @DateTime, 120),8) AS 'myTime'

2) Using Cast (SQL Server 2008 and beyond)

SELECT
    CAST(@DateTime AS DATETIME2) AS 'myDateTime'
    ,CAST(@DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
    ,CAST(@DateTime AS DATE) AS 'myDate'
    ,CAST(@DateTime AS TIME) AS 'myTime'
    ,CAST(@DateTime AS TIME(3)) AS 'myTimeWithPrecision'

3) Using Fixed-length character data type

DECLARE @myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, @DateTime, 120);
DECLARE @myDate NVARCHAR(10) = CONVERT(NVARCHAR, @DateTime, 120);

SELECT
    @myDateTime AS 'myDateTime'
    ,@myDate AS 'myDate'

How to get array keys in Javascript?

... ????

Alternatively, if you have a list of items you want to use...

var range = [46, 66, 90]
    , widthRange=[]
    , write=[];

    widthRange[46] = { min:0, max:52 }; 
    widthRange[66] = { min:52, max:70 }; 
    widthRange[90] = { min:70, max:94 }; 

for(var x=0; x<range.length; x++){var key, wr;

    key = range[x];

    wr = widthRange[key] || false;

    if(wr===false){continue;}

    write.push(['key: #',key, ', min: ', wr.min, 'max:', wr.max].join(''));

    }

How do I add a linker or compile flag in a CMake file?

Try setting the variable CMAKE_CXX_FLAGS instead of CMAKE_C_FLAGS:

set (CMAKE_CXX_FLAGS "-fexceptions")

The variable CMAKE_C_FLAGS only affects the C compiler, but you are compiling C++ code.

Adding the flag to CMAKE_EXE_LINKER_FLAGS is redundant.

.htaccess File Options -Indexes on Subdirectories

htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.

http://www.javascriptkit.com/howto/htaccess.shtml

How to obtain the total numbers of rows from a CSV file in Python?

You can also use a classic for loop:

import pandas as pd
df = pd.read_csv('your_file.csv')

count = 0
for i in df['a_column']:
    count = count + 1

print(count)

How can we run a test method with multiple parameters in MSTest?

MSTest has a powerful attribute called DataSource. Using this you can perform data-driven tests as you asked. You can have your test data in XML, CSV, or in a database. Here are few links that will guide you

How to round the minute of a datetime object

i'm using this. it has the advantage of working with tz aware datetimes.

def round_minutes(some_datetime: datetime, step: int):
    """ round up to nearest step-minutes """
    if step > 60:
        raise AttrbuteError("step must be less than 60")

    change = timedelta(
        minutes= some_datetime.minute % step,
        seconds=some_datetime.second,
        microseconds=some_datetime.microsecond
    )

    if change > timedelta():
        change -= timedelta(minutes=step)

    return some_datetime - change

it has the disadvantage of only working for timeslices less than an hour.

Best way of invoking getter by reflection

The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Just another way of doing it.

[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]

SQL Server - Create a copy of a database table and place it in the same database?

use sql server manegement studio or netcat and that will be easier to manipulate sql

How to inspect Javascript Objects

Use console.dir(object) and the Firebug plugin

Convert string with comma to integer

The following is another method that will work, although as with some of the other methods it will strip decimal places.

a = 1,112
b = a.scan(/\d+/).join().to_i => 1112

PHP string "contains"

You can use these string functions,

strstr — Find the first occurrence of a string

stristr — Case-insensitive strstr()

strrchr — Find the last occurrence of a character in a string

strpos — Find the position of the first occurrence of a substring in a string

strpbrk — Search a string for any of a set of characters

If that doesn't help then you should use preg regular expression

preg_match — Perform a regular expression match

Dead simple example of using Multiprocessing Queue, Pool and Locking

The best solution for your problem is to utilize a Pool. Using Queues and having a separate "queue feeding" functionality is probably overkill.

Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool. I believe it's the easiest way to go, with minimal changes to original code:

import multiprocessing
import time

data = (
    ['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
    ['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)

def mp_worker((inputs, the_time)):
    print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs

def mp_handler():
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

if __name__ == '__main__':
    mp_handler()

Note that mp_worker() function now accepts a single argument (a tuple of the two previous arguments) because the map() function chunks up your input data into sublists, each sublist given as a single argument to your worker function.

Output:

Processs a  Waiting 2 seconds
Processs b  Waiting 4 seconds
Process a   DONE
Processs c  Waiting 6 seconds
Process b   DONE
Processs d  Waiting 8 seconds
Process c   DONE
Processs e  Waiting 1 seconds
Process e   DONE
Processs f  Waiting 3 seconds
Process d   DONE
Processs g  Waiting 5 seconds
Process f   DONE
Processs h  Waiting 7 seconds
Process g   DONE
Process h   DONE

Edit as per @Thales comment below:

If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:

A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...

then change the handler function to launch pools (of 2 processes) for each pair of data:

def mp_handler():
    subdata = zip(data[0::2], data[1::2])
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

Now your output is:

 Processs a Waiting 2 seconds
 Processs b Waiting 4 seconds
 Process a  DONE
 Process b  DONE
 Processs c Waiting 6 seconds
 Processs d Waiting 8 seconds
 Process c  DONE
 Process d  DONE
 Processs e Waiting 1 seconds
 Processs f Waiting 3 seconds
 Process e  DONE
 Process f  DONE
 Processs g Waiting 5 seconds
 Processs h Waiting 7 seconds
 Process g  DONE
 Process h  DONE

Datatable vs Dataset

It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object.

Performance-wise, you're more likely to get inefficiency from unoptimized queries than from the "wrong" choice of .NET construct. At least, that's been my experience.

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Generate a sequence of numbers in Python

Write a function that takes a number as an argument and prints the Fibonacci series till that number

def Series(n):  
    a = 0  
    b = 1  
    print(a)  
    print(b)  
    S = 0  
    for i in range(0,n):  
        if S <= n-1:  
            S = a + b  
            print(S)  
            a = b  
            b = S

Centering elements in jQuery Mobile

Adjust as your requirement

   .ui-btn{
      margin:0.5em 10px;
    }

How to resolve Nodejs: Error: ENOENT: no such file or directory

92% additional asset processing scripts-webpack-plugin× ?wdm?: Error: ENOENT: no such file or directory, open....==> if anyone faced to such error, you should do followings: 1) you should check the if the file path is correct in angular.json file.

 "scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/bootstrap/dist/js/bootstrap.js"
        ],

2) you should press crtl+c and re run the project.

A valid provisioning profile for this executable was not found... (again)

This happened to me yesterday. What happened was that when I added the device Xcode included it in the wrong profile by default. This is easier to fix now that Apple has updated the provisioning portal:

  1. Log in to developer.apple.com/ios and click Certificates, Identifiers & Profiles
  2. Click devices and make sure that the device in question is listed
  3. Click provisioning profiles > All and select the one you want to use
  4. Click the edit button
  5. You will see another devices list which also has a label which will probably say "3 of 4 devices selected" or something of that nature.
  6. Check the select all box or scroll through the list and check the device. If your device was unchecked, this is your problem.
  7. Click "Generate"
  8. DON'T hit Download & Install – while this will work it's likely to screw up your project file if you've already installed the provisioning profile (see this question for more info).
  9. Open Xcode, open the Organizer, switch to the Devices tab, and hit the Refresh button in the lower right corner. This will pull in the changes to the provisioning profile.

Now it should work.

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

The Role Manager feature has not been enabled

I found this question due the exception mentioned in it. My Web.Config didn't have any <roleManager> tag. I realized that even if I added it (as Infotekka suggested), it ended up in a Database exception. After following the suggestions in the other answers in here, none fully solved the problem.

Since these Web.Config tags can be automatically generated, it felt wrong to solve it by manually adding them. If you are in a similar case, undo all the changes you made to Web.Config and in Visual Studio:

  1. Press Ctrl+Q, type nuget and click on "Manage NuGet Packages";
  2. Press Ctrl+E, type providers and in the list it should show up "Microsoft ASP.NET Universal Providers Core Libraries" and "Microsoft ASP.NET Universal Providers for LocalDB" (both created by Microsoft);
  3. Click on the Install button in both of them and close the NuGet window;
  4. Check your Web.config and now you should have at least one <providers> tag inside Profile, Membership, SessionState tags and also inside the new RoleManager tag, like this:

    <roleManager defaultProvider="DefaultRoleProvider">
        <providers>
           <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=NUMBER" connectionStringName="DefaultConnection" applicationName="/" />
        </providers>
    </roleManager>
    
  5. Add enabled="true" like so:

    <roleManager defaultProvider="DefaultRoleProvider" enabled="true">
    
  6. Press F6 to Build and now it should be OK to proceed to a database update without having that exception:

    1. Press Ctrl+Q, type manager, click on "Package Manager Console";
    2. Type update-database -verbose and the Seed method will run just fine (if you haven't messed elsewhere) and create a few tables in your Database;
    3. Press Ctrl+W+L to open the Server Explorer and you should be able to check in Data Connections > DefaultConnection > Tables the Roles and UsersInRoles tables among the newly created tables!

How to initialize all the elements of an array to any specific value in java

You could do this if it's short:

int[] array = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

but that gets bad for more than just a few.

Easier would be a for loop:

  int[] myArray = new int[10];
  for (int i = 0; i < array.length; i++)
       myArray[i] = -1;

Edit: I also like the Arrays.fill() option other people have mentioned.

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Startup.cs in WebAPI.

app.UseCors(options => options.AllowAnyOrigin());  

In ConfigureServices method:

services.AddCors(c =>  
{  
    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());  
});

In Controller:

[HttpGet]  
     [Route("GetAllAuthor")]  
     [EnableCors("AllowOrigin")] 

Scanner vs. BufferedReader

  1. BufferedReader has significantly larger buffer memory than Scanner. Use BufferedReader if you want to get long strings from a stream, and use Scanner if you want to parse specific type of token from a stream.

  2. Scanner can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader can only read and store String.

  3. BufferedReader is synchronous while Scanner is not. Use BufferedReader if you're working with multiple threads.

  4. Scanner hides IOException while BufferedReader throws it immediately.

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

The methods provide different layers of abstraction.

  • $.ajax() gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.

  • $.get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler.

  • $(selector).load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).

It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax().

E.g. you won't use $.load(), if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax() or $.get().

How to increase the gap between text and underlining in CSS

No, but you could go with something like border-bottom: 1px solid #000 and padding-bottom: 3px.

If you want the same color of the "underline" (which in my example is a border), you just leave out the color declaration, i.e. border-bottom-width: 1px and border-bottom-style: solid.

For multiline, you can wrap you multiline texts in a span inside the element. E.g. <a href="#"><span>insert multiline texts here</span></a> then just add border-bottom and padding on the <span> - Demo

How to check string length with JavaScript

UPDATE: Since I wrote this, the input event has gotten a decent level of support. It is still not 100% in IE9, so you will have to wait a bit until IE9 is fully phased out. In light of my answer to this question, however, input is more than a decent replacement for the method I've presented, so I recommend switching.

Use keyup event

_x000D_
_x000D_
var inp = document.getElementById('myinput');_x000D_
var chars = document.getElementById('chars');_x000D_
inp.onkeyup = function() {_x000D_
  chars.innerHTML = inp.value.length;_x000D_
}
_x000D_
<input id="myinput"><span id="chars">0</span>
_x000D_
_x000D_
_x000D_

EDIT:

Just a note for those that suggest keydown. That won't work. The keydown fires before character is added to the input box or textarea, so the length of the value would be wrong (one step behind). Therefore, the only solution that works is keyup, which fires after the character is added.

How to convert .pem into .key?

If you're looking for a file to use in httpd-ssl.conf as a value for SSLCertificateKeyFile, a PEM file should work just fine.

See this SO question/answer for more details on the SSL options in that file.

Why is SSLCertificateKeyFile needed for Apache?

Run text file as commands in Bash

You can use something like this:

for i in `cat foo.txt`
do
    sudo $i
done

Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo as a command. But it gives you an idea on how to start.

How to get primary key column in Oracle?

Same as the answer from 'Richie' but a bit more concise.

  1. Query for user constraints only

    SELECT column_name FROM all_cons_columns WHERE constraint_name = (
      SELECT constraint_name FROM user_constraints 
      WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
    );
    
  2. Query for all constraints

    SELECT column_name FROM all_cons_columns WHERE constraint_name = (
      SELECT constraint_name FROM all_constraints 
      WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
    );
    

HTML.ActionLink vs Url.Action in ASP.NET Razor

You can easily present Html.ActionLink as a button by using the appropriate CSS style. For example:

@Html.ActionLink("Save", "ActionMethod", "Controller", new { @class = "btn btn-primary" })

Getting permission denied (public key) on gitlab

My issue was that I used a non-root user with sudo access. But even sudo git clone ... didn't work. The solution was to create the folder for the project, chown user projectfolder and then run the clone without sudo.

JavaScript - Get Browser Height

I prefer the way I just figured out... No JS... 100% HTML & CSS:

(Will center it perfectly in the middle, regardless of the content size.

HTML FILE

<html><head>
<link href="jane.css" rel="stylesheet" />
</head>
<body>
<table id="container">
<tr>
<td id="centerpiece">
123
</td></tr></table>
</body></html>

CSS FILE

#container{
    border:0;
    width:100%;
    height:100%;
}
#centerpiece{
    vertical-align:middle;
    text-align:center;
}

for centering images / div's held within the td, you may wish to try margin:auto; and specify a div dimension instead. -Though, saying that... the 'text-align' property will align much more than just a simple text element.

Common elements in two lists

consider two list L1 ans L2

Using Java8 we can easily find it out

L1.stream().filter(L2::contains).collect(Collectors.toList())

How to get the latest record in each group using GROUP BY?

Just complementing what Devart said, the below code is not ordering according to the question:

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;

The "GROUP BY" clause must be in the main query since that we need first reorder the "SOURCE" to get the needed "grouping" so:

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages ORDER BY timestamp DESC) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp GROUP BY t2.timestamp;

Regards,

What is the right way to write my script 'src' url for a local development environment?

Write the src tag for calling the js file as

<script type='text/javascript' src='../Users/myUserName/Desktop/myPage.js'></script>

This should work.

ASP.NET MVC3 - textarea with @Html.EditorFor

@Html.TextAreaFor(model => model.Text)

Initializing multiple variables to the same value in Java

Way too late to this but the simplest way I've found is:

String foo = bar = baz = "hello"
println(foo)
println(bar)
println(baz)

Output:

hello
hello
hello

How do I print the content of a .txt file in Python?

Just do this:

>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
...     print f.read()

This will print the file in the terminal.

Javascript | Set all values of an array

There's no built-in way, you'll have to loop over all of them:

function setAll(a, v) {
    var i, n = a.length;
    for (i = 0; i < n; ++i) {
        a[i] = v;
    }
}

http://jsfiddle.net/alnitak/xG88A/

If you really want, do this:

Array.prototype.setAll = function(v) {
    var i, n = this.length;
    for (i = 0; i < n; ++i) {
        this[i] = v;
    }
};

and then you could actually do cool.setAll(42) (see http://jsfiddle.net/alnitak/ee3hb/).

Some people frown upon extending the prototype of built-in types, though.

EDIT ES5 introduced a way to safely extend both Object.prototype and Array.prototype without breaking for ... in ... enumeration:

Object.defineProperty(Array.prototype, 'setAll', {
    value: function(v) {
        ...
    }
});

EDIT 2 In ES6 draft there's also now Array.prototype.fill, usage cool.fill(42)

Why doesn't logcat show anything in my Android?

If you tried all of others, and still got losing on Empty logcat. I got an another simple way.

Download a old version of adb, and try again, It might be working, at least working for me with Android 7.0 phone (vendor stopped updating).

Here is the useful link for old versions.

Reading in double values with scanf in c

As far as i know %d means decadic which is number without decimal point. if you want to load double value, use %lf conversion (long float). for printf your values are wrong for same reason, %d is used only for integer (and possibly chars if you know what you are doing) numbers.

Example:

double a,b;
printf("--------\n"); //seperate lines
scanf("%lf",&a);
printf("--------\n"); 
scanf("%lf",&b);
printf("%lf %lf",a,b);

What are the differences between LDAP and Active Directory?

https://jumpcloud.com/blog/difference-between-ldap-and-active-directory/

Realistically, there are probably more differences than similarities between the two directory solutions. Microsoft’s AD is largely a directory for Windows users, devices, and applications. AD requires a Microsoft Domain Controller to be present and when it is, users are able to single sign-on to Windows resources that live within the domain structure.

LDAP, on the other hand, has largely worked outside of the Windows structure focusing on the Linux / Unix environment and with more technical applications. LDAP doesn’t have the same concepts of domains or single sign-on. LDAP is largely implemented with open source solutions and as a result has more flexibility than AD.

Another critical difference between LDAP and Active Directory is how AD and LDAP each approach device management. AD manages Windows devices through and Group Policy Objects (GPOs). A similar concept doesn’t exist within LDAP. Both LDAP and AD are highly different solutions and as a result many organization must leverage both to serve different purposes.

This is why there’s an obvious opportunity for innovation. Why leverage and manage two complete systems, when one system can effectively merge the two?

Print all key/value pairs in a Java ConcurrentHashMap

The HashMap has forEach as part of its structure. You can use that with a lambda expression to print out the contents in a one liner such as:

map.forEach((k,v)-> System.out.println(k+", "+v));

or

map.forEach((k,v)-> System.out.println("key: "+k+", value: "+v));

Run a command over SSH with JSch

The following code example written in Java will allow you to execute any command on a foreign computer through SSH from within a java program. You will need to include the com.jcraft.jsch jar file.

  /* 
  * SSHManager
  * 
  * @author cabbott
  * @version 1.0
  */
  package cabbott.net;

  import com.jcraft.jsch.*;
  import java.io.IOException;
  import java.io.InputStream;
  import java.util.logging.Level;
  import java.util.logging.Logger;

  public class SSHManager
  {
  private static final Logger LOGGER = 
      Logger.getLogger(SSHManager.class.getName());
  private JSch jschSSHChannel;
  private String strUserName;
  private String strConnectionIP;
  private int intConnectionPort;
  private String strPassword;
  private Session sesConnection;
  private int intTimeOut;

  private void doCommonConstructorActions(String userName, 
       String password, String connectionIP, String knownHostsFileName)
  {
     jschSSHChannel = new JSch();

     try
     {
        jschSSHChannel.setKnownHosts(knownHostsFileName);
     }
     catch(JSchException jschX)
     {
        logError(jschX.getMessage());
     }

     strUserName = userName;
     strPassword = password;
     strConnectionIP = connectionIP;
  }

  public SSHManager(String userName, String password, 
     String connectionIP, String knownHostsFileName)
  {
     doCommonConstructorActions(userName, password, 
                connectionIP, knownHostsFileName);
     intConnectionPort = 22;
     intTimeOut = 60000;
  }

  public SSHManager(String userName, String password, String connectionIP, 
     String knownHostsFileName, int connectionPort)
  {
     doCommonConstructorActions(userName, password, connectionIP, 
        knownHostsFileName);
     intConnectionPort = connectionPort;
     intTimeOut = 60000;
  }

  public SSHManager(String userName, String password, String connectionIP, 
      String knownHostsFileName, int connectionPort, int timeOutMilliseconds)
  {
     doCommonConstructorActions(userName, password, connectionIP, 
         knownHostsFileName);
     intConnectionPort = connectionPort;
     intTimeOut = timeOutMilliseconds;
  }

  public String connect()
  {
     String errorMessage = null;

     try
     {
        sesConnection = jschSSHChannel.getSession(strUserName, 
            strConnectionIP, intConnectionPort);
        sesConnection.setPassword(strPassword);
        // UNCOMMENT THIS FOR TESTING PURPOSES, BUT DO NOT USE IN PRODUCTION
        // sesConnection.setConfig("StrictHostKeyChecking", "no");
        sesConnection.connect(intTimeOut);
     }
     catch(JSchException jschX)
     {
        errorMessage = jschX.getMessage();
     }

     return errorMessage;
  }

  private String logError(String errorMessage)
  {
     if(errorMessage != null)
     {
        LOGGER.log(Level.SEVERE, "{0}:{1} - {2}", 
            new Object[]{strConnectionIP, intConnectionPort, errorMessage});
     }

     return errorMessage;
  }

  private String logWarning(String warnMessage)
  {
     if(warnMessage != null)
     {
        LOGGER.log(Level.WARNING, "{0}:{1} - {2}", 
           new Object[]{strConnectionIP, intConnectionPort, warnMessage});
     }

     return warnMessage;
  }

  public String sendCommand(String command)
  {
     StringBuilder outputBuffer = new StringBuilder();

     try
     {
        Channel channel = sesConnection.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
        InputStream commandOutput = channel.getInputStream();
        channel.connect();
        int readByte = commandOutput.read();

        while(readByte != 0xffffffff)
        {
           outputBuffer.append((char)readByte);
           readByte = commandOutput.read();
        }

        channel.disconnect();
     }
     catch(IOException ioX)
     {
        logWarning(ioX.getMessage());
        return null;
     }
     catch(JSchException jschX)
     {
        logWarning(jschX.getMessage());
        return null;
     }

     return outputBuffer.toString();
  }

  public void close()
  {
     sesConnection.disconnect();
  }

  }

For testing.

  /**
     * Test of sendCommand method, of class SSHManager.
     */
  @Test
  public void testSendCommand()
  {
     System.out.println("sendCommand");

     /**
      * YOU MUST CHANGE THE FOLLOWING
      * FILE_NAME: A FILE IN THE DIRECTORY
      * USER: LOGIN USER NAME
      * PASSWORD: PASSWORD FOR THAT USER
      * HOST: IP ADDRESS OF THE SSH SERVER
     **/
     String command = "ls FILE_NAME";
     String userName = "USER";
     String password = "PASSWORD";
     String connectionIP = "HOST";
     SSHManager instance = new SSHManager(userName, password, connectionIP, "");
     String errorMessage = instance.connect();

     if(errorMessage != null)
     {
        System.out.println(errorMessage);
        fail();
     }

     String expResult = "FILE_NAME\n";
     // call sendCommand for each command and the output 
     //(without prompts) is returned
     String result = instance.sendCommand(command);
     // close only after all commands are sent
     instance.close();
     assertEquals(expResult, result);
  }

How should a model be structured in MVC?

Everything that is business logic belongs in a model, whether it is a database query, calculations, a REST call, etc.

You can have the data access in the model itself, the MVC pattern doesn't restrict you from doing that. You can sugar coat it with services, mappers and what not, but the actual definition of a model is a layer that handles business logic, nothing more, nothing less. It can be a class, a function, or a complete module with a gazillion objects if that's what you want.

It's always easier to have a separate object that actually executes the database queries instead of having them being executed in the model directly: this will especially come in handy when unit testing (because of the easiness of injecting a mock database dependency in your model):

class Database {
   protected $_conn;

   public function __construct($connection) {
       $this->_conn = $connection;
   }

   public function ExecuteObject($sql, $data) {
       // stuff
   }
}

abstract class Model {
   protected $_db;

   public function __construct(Database $db) {
       $this->_db = $db;
   }
}

class User extends Model {
   public function CheckUsername($username) {
       // ...
       $sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
       return $this->_db->ExecuteObject($sql, $data);
   }
}

$db = new Database($conn);
$model = new User($db);
$model->CheckUsername('foo');

Also, in PHP, you rarely need to catch/rethrow exceptions because the backtrace is preserved, especially in a case like your example. Just let the exception be thrown and catch it in the controller instead.

Repeat string to certain length

Yay recursion!

def trunc(s,l):
    if l > 0:
        return s[:l] + trunc(s, l - len(s))
    return ''

Won't scale forever, but it's fine for smaller strings. And it's pretty.

I admit I just read the Little Schemer and I like recursion right now.

Make a nav bar stick

CSS:

.headercss {
    width: 100%;
    height: 320px;
    background-color: #000000;
    position: fixed;
}

Attribute position: fixed will keep it stuck, while other content will be scrollable. Don't forget to set width:100% to make it fill fully to the right.

Example

SQL keys, MUL vs PRI vs UNI

Let's understand in simple words

  • PRI - It's a primary key, and used to identify records uniquely.
  • UNI - It's a unique key, and also used to identify records uniquely. It looks similar like primary key but a table can have multiple unique keys and unique key can have one null value, on the other hand table can have only one primary key and can't store null as a primary key.
  • MUL - It's doesn't have unique constraint and table can have multiple MUL columns.

Note: These keys have more depth as a concept but this is good to start.

Exact difference between CharSequence and String in java

Consider UTF-8. In UTF-8 Unicode code points are built from one or more bytes. A class encapsulating a UTF-8 byte array can implement the CharSequence interface but is most decidedly not a String. Certainly you can't pass a UTF-8 byte array where a String is expected but you certainly can pass a UTF-8 wrapper class that implements CharSequence when the contract is relaxed to allow a CharSequence. On my project, I am developing a class called CBTF8Field (Compressed Binary Transfer Format - Eight Bit) to provide data compression for xml and am looking to use the CharSequence interface to implement conversions from CBTF8 byte arrays to/from character arrays (UTF-16) and byte arrays (UTF-8).

The reason I came here was to get a complete understanding of the subsequence contract.

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

Reading CSV files using C#

I use this here:

http://www.codeproject.com/KB/database/GenericParser.aspx

Last time I was looking for something like this I found it as an answer to this question.

Is there anyway to exclude artifacts inherited from a parent POM?

We can add the parent pom as a dependency with type pom and make exclusion on that. Because anyhow parent pom is downloaded. This worked for me

<dependency>
  <groupId>com.abc.boot</groupId>
  <artifactId>abc-boot-starter-parent</artifactId>
  <version>2.1.5.RELEASE</version>
  <type>pom</type>
  <exclusions>
    <exclusion>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
    </exclusion>
  </exclusions>   
</dependency>

How to initialize HashSet values by construction?

I feel the most readable is to simply use google Guava:

Set<String> StringSet = Sets.newSet("a", "b", "c");

asp.net mvc @Html.CheckBoxFor

If only one checkbox should be checked in the same time use RadioButtonFor instead:

      @Html.RadioButtonFor(model => model.Type,1, new { @checked = "checked" }) fultime
      @Html.RadioButtonFor(model => model.Type,2) party
      @Html.RadioButtonFor(model => model.Type,3) next option...

If one more one could be checked in the same time use excellent extension: CheckBoxListFor:

Hope,it will help

jQuery Set Cursor Position in Text Area

I had to get this working for contenteditable elements and jQuery and tought someone might want it ready to use:

$.fn.getCaret = function(n) {
    var d = $(this)[0];
    var s, r;
    r = document.createRange();
    r.selectNodeContents(d);
    s = window.getSelection();
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return s.anchorOffset;
};

$.fn.setCaret = function(n) {
    var d = $(this)[0];
    d.focus();
    var r = document.createRange();
    var s = window.getSelection();
    r.setStart(d.childNodes[0], n);
    r.collapse(true);
    s.removeAllRanges();
    s.addRange(r);
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return this;
};

Usage $(selector).getCaret() returns the number offset and $(selector).setCaret(num) establishes the offeset and sets focus on element.

Also a small tip, if you run $(selector).setCaret(num) from console it will return the console.log but you won't visualize the focus since it is established at the console window.

Bests ;D

Using the last-child selector

If you are floating the elements you can reverse the order

i.e. float: right; instead of float: left;

And then use this method to select the first-child of a class.

/* 1: Apply style to ALL instances */
#header .some-class {
  padding-right: 0;
}
/* 2: Remove style from ALL instances except FIRST instance */
#header .some-class~.some-class {
  padding-right: 20px;
}

This is actually applying the class to the LAST instance only because it's now in reversed order.

Here is a working example for you:

<!doctype html>
<head><title>CSS Test</title>
<style type="text/css">
.some-class { margin: 0; padding: 0 20px; list-style-type: square; }
.lfloat { float: left; display: block; }
.rfloat { float: right; display: block; }
/* apply style to last instance only */
#header .some-class {
  border: 1px solid red;
  padding-right: 0;
}
#header .some-class~.some-class {
  border: 0;
  padding-right: 20px;
}
</style>
</head>
<body>
<div id="header">
  <img src="some_image" title="Logo" class="lfloat no-border"/>
  <ul class="some-class rfloat">
    <li>List 1-1</li>
    <li>List 1-2</li>
    <li>List 1-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 2-1</li>
    <li>List 2-2</li>
    <li>List 2-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 3-1</li>
    <li>List 3-2</li>
    <li>List 3-3</li>
  </ul>
  <img src="some_other_img" title="Icon" class="rfloat no-border"/>
</div>
</body>
</html>

Python: access class property from string

x = getattr(self, source) will work just perfectly if source names ANY attribute of self, including the other_data in your example.

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

if no other solution worked, then just rename the inherits class of that problem causing aspx file and aspx.cs file to a new name, then rebuild the solution. then the issue will be solved for sure. this only worked for me.

eg :

in the aspx file do the following change the inherits class name to Defaultnew

<%@ Page Title="" Language="C#"  MasterPageFile="~/Main.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Defaultnew" %>

in the aspx.cs file rename the class to the same as used in aspx file

using System;
using System.Collections.Generic;
using System.Web;

public partial class Defaultnew : System.Web.UI.Page
{

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Angular 1 - get current URL parameters

ex: url/:id

var sample= app.controller('sample', function ($scope, $routeParams) {
  $scope.init = function () {
    var qa_id = $routeParams.qa_id;
  }
});

error: package com.android.annotations does not exist

if error from butterknife auto generated file then update butterknife dependency version

implementation 'com.jakewharton:butterknife:10.0.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'

Android + Pair devices via bluetooth programmatically

Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.

Try this to do pairing:

If you are able to search the devices then this would be your next step

ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;

I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices:

BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);

Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
    Log.i("Log","Paired");
}
} catch (Exception e) 
{
    e.printStackTrace(); 
}

The createBond() method:

public boolean createBond(BluetoothDevice btDevice)  
    throws Exception  
    { 
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }  

Add this line into your Receiver in the ACTION_FOUND

if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    arrayListBluetoothDevices.add(device);
                }

Getting the first character of a string with $str[0]

Lets say you just want the first char from a part of $_POST, lets call it 'type'. And that $_POST['type'] is currently 'Control'. If in this case if you use $_POST['type'][0], or substr($_POST['type'], 0, 1)you will get C back.

However, if the client side were to modify the data they send you, from type to type[] for example, and then send 'Control' and 'Test' as the data for this array, $_POST['type'][0] will now return Control rather than C whereas substr($_POST['type'], 0, 1) will simply just fail.

So yes, there may be a problem with using $str[0], but that depends on the surrounding circumstance.

The application may be doing too much work on its main thread

As others answered above, "Skipped 55 frames!" means some heavy processing is in your application.

For my case, there is no heavy process in my application. I double and triple checked everything and removed those process I think was a bit heavy.

I removed Fragments, Activities, Libraries until only the skeleton was left. But still the problem did not go away. I decided to check the resources and found some icons and background I use are pretty big as I forgot to check the size of those resources.

So, my suggestion is if none of the above answers help, you may also check your resource files size.

anaconda - graphviz - can't import after installation

for me the problem was solved by installing another supportive package.

so I installed graphviz package through anaconda then I failed to import it

after that I installed a second package named python-graphviz also through anaconda

then I succeeded in importing graphviz module into my code

I hope this will help someone :)

Mathematical functions in Swift

You can use them right inline:

var square = 9.4
var floored = floor(square)
var root = sqrt(floored)

println("Starting with \(square), we rounded down to \(floored), then took the square root to end up with \(root)")

Beginner question: returning a boolean value from a function in Python

Have your tried using the 'return' keyword?

def rps():
    return True

How to move git repository with all branches from bitbucket to github?

Simplest way of doing it:

git remote rename origin repo_bitbucket

git remote add origin https://github.com/abc/repo.git

git push origin master

Once the push to GitHub is successful, delete the old remote by running:

git remote rm repo_bitbucket

OwinStartup not firing

I had same problem when I added Owin to an existing web project. I eventually found the problem was due to the following in the web.config file.

<assemblies>
  <remove assembly="*" />
  <add assembly="System.Web.Mvc" />
  <add assembly="System.Web.WebPages" />

   ...

</assemblies>

The remove assembly="*" was causing the problem. When I remove this line the Owin startup code ran. I eventually change it to the following and it worked perfectly

<assemblies>
  <remove assembly="*" />
  <add assembly="Microsoft.Owin.Host.SystemWeb" />
  <add assembly="System.Web.Mvc" />
  <add assembly="System.Web.WebPages" />
  <add assembly="System.Web.Helpers" />
...
</assemblies>

Uncaught TypeError: .indexOf is not a function

Basically indexOf() is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.

document.getElementById("oset").innerHTML = timeD2C(timeofday + "");

_x000D_
_x000D_
 var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
    var pos = time.indexOf('.');_x000D_
    var hrs = time.substr(1, pos - 1);_x000D_
    var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
    if (hrs > 11) {_x000D_
        hrs = (hrs - 12) + ":" + min + " PM";_x000D_
    } else {_x000D_
        hrs += ":" + min + " AM";_x000D_
    }_x000D_
    return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
_x000D_
_x000D_


And it is good to do the string conversion inside your function definition,

function timeD2C(time) { 
  time = time + "";
  var pos = time.indexOf('.');

So that the code flow won't break at times when devs forget to pass a string into this function.

When restoring a backup, how do I disconnect all active connections?

I ran across this problem while automating a restore proccess in SQL Server 2008. My (successfull) approach was a mix of two of the answers provided.

First, I run across all the connections of said database, and kill them.

DECLARE @SPID int = (SELECT TOP 1 SPID FROM sys.sysprocess WHERE dbid = db_id('dbName'))
While @spid Is Not Null
Begin
        Execute ('Kill ' + @spid)
        Select @spid = top 1 spid from master.dbo.sysprocesses
        where dbid = db_id('dbName')
End

Then, I set the database to a single_user mode

ALTER DATABASE dbName SET SINGLE_USER

Then, I run the restore...

RESTORE DATABASE and whatnot

Kill the connections again

(same query as above)

And set the database back to multi_user.

ALTER DATABASE dbName SET MULTI_USER

This way, I ensure that there are no connections holding up the database before setting to single mode, since the former will freeze if there are.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

How to do what @connor said:

iOS

  • Open platforms/ios on XCode
  • Find & Replace io.ionic.starter in all files for a unique identifier
  • Click the project to open settings
  • Signing > Select a team
  • Go to your device Settings > General > DeviceManagement
    • Trust your account/team
  • ionic cordova run ios --device --livereload

MVC 4 Edit modal form using Bootstrap

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

What is the difference between logical data model and conceptual data model?

In the conceptual data model you worry only about the high level design - what tables should exist and the connections between them. In this phase you recognize entities in your model and the relationships between them.

The logical model comes after the conceptual modeling when you explicitly define what the columns in each table are. While writing the logical model, you might also take into consideration the actual database system you're designing for, but only if it affects the design (i.e., if there are no triggers you might want to remove some redundancy column etc.)

There is also physical model which elaborates on the logical model and assigns each column with it's type/length etc.

Here is a good table and picture that describes each of the three levels.

|----------------------|------------|---------|----------|
| Feature              | Conceptual | Logical | Physical | 
|----------------------|------------|---------|----------|
| Entity Names         | X          | X       |          |
| Entity Relationships | X          | X       |          |
| Attributes           |            | X       |          |
| Primary Keys         |            | X       | X        |
| Foreign Keys         |            | X       | X        |
| Table Names          |            |         | X        |
| Column Names         |            |         | X        |
| Column Data Types    |            |         | X        |
|----------------------|------------|---------|----------|

data modeling levels from https://www.1keydata.com/datawarehousing/data-modeling-levels.html

How can I sort a dictionary by key?

From Python's collections library documentation:

>>> from collections import OrderedDict

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key -- OrderedDict(sorted(d.items()) also works
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])

How to calculate modulus of large numbers?

This is part of code I made for IBAN validation. Feel free to use.

    static void Main(string[] args)
    {
        int modulo = 97;
        string input = Reverse("100020778788920323232343433");
        int result = 0;
        int lastRowValue = 1;

        for (int i = 0; i < input.Length; i++)
        {
            // Calculating the modulus of a large number Wikipedia http://en.wikipedia.org/wiki/International_Bank_Account_Number                                                                        
            if (i > 0)
            {
                lastRowValue = ModuloByDigits(lastRowValue, modulo);
            }
            result += lastRowValue * int.Parse(input[i].ToString());
        }
        result = result % modulo;
        Console.WriteLine(string.Format("Result: {0}", result));            
    }

    public static int ModuloByDigits(int previousValue, int modulo)
    {
        // Calculating the modulus of a large number Wikipedia http://en.wikipedia.org/wiki/International_Bank_Account_Number                        
        return ((previousValue * 10) % modulo);
    }
    public static string Reverse(string input)
    {
        char[] arr = input.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }

Check if a variable exists in a list in Bash

Assuming TARGET variable can be only 'binomial' or 'regression', then following would do:

# Check for modeling types known to this script
if [ $( echo "${TARGET}" | egrep -c "^(binomial|regression)$" ) -eq 0 ]; then
    echo "This scoring program can only handle 'binomial' and 'regression' methods now." >&2
    usage
fi

You could add more strings into the list by separating them with a | (pipe) character.

Advantage of using egrep, is that you could easily add case insensitivity (-i), or check more complex scenarios with a regular expression.

How to handle change of checkbox using jQuery?

Hope, this would be of some help.

$('input[type=checkbox]').change(function () {
    if ($(this).prop("checked")) {
        //do the stuff that you would do when 'checked'

        return;
    }
    //Here do the stuff you want to do when 'unchecked'
});

Remove warning messages in PHP

I do it as follows in my php.ini:

error_reporting = E_ALL & ~E_WARNING  & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED

This logs only fatal errors and no warnings.

Exception thrown in catch and finally clause

To handle this kind of situation i.e. handling the exception raised by finally block. You can surround the finally block by try block: Look at the below example in python:

try:
   fh = open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print "Going to close the file"
      fh.close()
except IOError:
   print "Error: can\'t find file or read data"

SVN upgrade working copy

This problem due to that you try to compile project that has the files of OLder SVN than you currently use.

You have two solutions to resolve this problem

  1. to install the version 1.6 SVN to be compatible with project SVN files
  2. try to upgrade the project ..( not always working ).

How to change text color of cmd with windows batch script every 1 second

To have a colorful user experience, I have used this script to execute the whole set of commands. I hope it helps.

@echo off
color 01
timeout /t 2
color 02
timeout /t 2
color 03
timeout /t 2
color 04
timeout /t 2
color 05
timeout /t 2

Difference between DOM parentNode and parentElement

Use .parentElement and you can't go wrong as long as you aren't using document fragments.

If you use document fragments, then you need .parentNode:

let div = document.createDocumentFragment().appendChild(document.createElement('div'));
div.parentElement // null
div.parentNode // document fragment

Also:

_x000D_
_x000D_
let div = document.getElementById('t').content.firstChild_x000D_
div.parentElement // null_x000D_
div.parentNode // document fragment
_x000D_
<template id="t"><div></div></template>
_x000D_
_x000D_
_x000D_


Apparently the <html>'s .parentNode links to the Document. This should be considered a decision phail as documents aren't nodes since nodes are defined to be containable by documents and documents can't be contained by documents.

Jquery find nearest matching element

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

how to add lines to existing file using python

Open the file for 'append' rather than 'write'.

with open('file.txt', 'a') as file:
    file.write('input')

Oracle client and networking components were not found

In my case this was because a file named ociw32.dll had been placed in c:\windows\system32. This is however only allowed to exist in c:\oracle\11.2.0.3\bin.

Deleting the file from system32, which had been placed there by an installation of Crystal Reports, fixed this issue

Attach a body onload event with JS

There are several different methods you have to use for different browsers. Libraries like jQuery give you a cross-browser interface that handles it all for you, though.

How To Set A JS object property name from a variable

Along the lines of Sainath S.R's comment above, I was able to set a js object property name from a variable in Google Apps Script (which does not support ES6 yet) by defining the object then defining another key/value outside of the object:

var salesperson = ...

var mailchimpInterests = { 
        "aGroupId": true,
    };

mailchimpInterests[salesperson] = true;

Parsing string as JSON with single quotes?

Using single quotes for keys are not allowed in JSON. You need to use double quotes.

For your use-case perhaps this would be the easiest solution:

str = '{"a":1}';

Source:

If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

How to export table as CSV with headings on Postgresql?

From psql command line:

\COPY my_table TO 'filename' CSV HEADER

no semi-colon at the end.

Android Studio - Emulator - eglSurfaceAttrib not implemented

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

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