Programs & Examples On #Listobject

How do I reference tables in Excel using VBA?

The OP asked, is it possible to reference a table, not how to add a table. So the working equivalent of

Sheets("Sheet1").Table("A_Table").Select

would be this statement:

Sheets("Sheet1").ListObjects("A_Table").Range.Select

or to select parts (like only the data in the table):

Dim LO As ListObject
Set LO = Sheets("Sheet1").ListObjects("A_Table")
LO.HeaderRowRange.Select        ' Select just header row
LO.DataBodyRange.Select         ' Select just data cells
LO.TotalsRowRange.Select        ' Select just totals row

For the parts, you may want to test for the existence of the header and totals rows before selecting them.

And seriously, this is the only question on referencing tables in VBA in SO? Tables in Excel make so much sense, but they're so hard to work with in VBA!

Creating a new user and password with Ansible

I want to propose yet another solution:

- name: Create madhead user
  user:
    name: madhead
    password: "{{ 'password' | password_hash('sha512') }}"
    shell: /bin/zsh
    update_password: on_create
  register: madhead
- name: Force madhead to change password
  shell: chage -d 0 madhead
  when: madhead.changed

Why it is better? Like already has been noted here, Ansible plays should be idempotent. You should think of them not as a sequence of actions in imperative style, but like a desired state, declarative style. As a result you should be able to run it multiple times and get the same result, the same server state.

This all sounds great, but there are some nuances. One of them is managing users. "Desired state" means that every time you run a play that creates a user he will be updated to match exactly that state. By "updated" I mean that his password will be changed too. But most probably it is not what you need. Usually, you need to create user, set and expire his password only once, further play runs shouldn't update his password.

Fortunately, Ansible has update_password attribute in user module that solves this issue. Mixing this with registered variables you can also expire his password only when the user is actually updated.

Note that if you change user's shell manually (suppose, you don't like the shell that evil admin forced in his play) the user will be updated, thus his password will be expired.

Also note how you can easily use plain text initial passwords in plays. No need to encode them somewhere else and paste hashes, you can use Jinja2 filter for that. However, this can be a security flaw if someone happens to login before you initially do.

Why do multiple-table joins produce duplicate rows?

This might sound like a really basic "DUH" answer, but make sure that the column you're using to Lookup from on the merging file is actually full of unique values!

I noticed earlier today that PowerQuery won't throw you an error (like in PowerPivot) and will happily allow you to run a Many-Many merge. This will result in multiple rows being produced for each record that matches with a non-unique value.

Multiple file upload in php

I know this is an old post but some further explanation might be useful for someone trying to upload multiple files... Here is what you need to do:

  • Input name must be be defined as an array i.e. name="inputName[]"
  • Input element must have multiple="multiple" or just multiple
  • In your PHP file use the syntax "$_FILES['inputName']['param'][index]"
  • Make sure to look for empty file names and paths, the array might contain empty strings. Use array_filter() before count.

Here is a down and dirty example (showing just relevant code)

HTML:

<input name="upload[]" type="file" multiple="multiple" />

PHP:

//$files = array_filter($_FILES['upload']['name']); //something like that to be used before processing files.

// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);

// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {

  //Get the temp file path
  $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

  //Make sure we have a file path
  if ($tmpFilePath != ""){
    //Setup our new file path
    $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];

    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {

      //Handle other code here

    }
  }
}

Hope this helps out!

EC2 instance types's exact network performance?

Bandwidth is tiered by instance size, here's a comprehensive answer:

For t2/m3/c3/c4/r3/i2/d2 instances:

  • t2.nano = ??? (Based on the scaling factors, I'd expect 20-30 MBit/s)
  • t2.micro = ~70 MBit/s (qiita says 63 MBit/s) - t1.micro gets about ~100 Mbit/s
  • t2.small = ~125 MBit/s (t2, qiita says 127 MBit/s, cloudharmony says 125 Mbit/s with spikes to 200+ Mbit/s)
  • *.medium = t2.medium gets 250-300 MBit/s, m3.medium ~400 MBit/s
  • *.large = ~450-600 MBit/s (the most variation, see below)
  • *.xlarge = 700-900 MBit/s
  • *.2xlarge = ~1 GBit/s +- 10%
  • *.4xlarge = ~2 GBit/s +- 10%
  • *.8xlarge and marked specialty = 10 Gbit, expect ~8.5 GBit/s, requires enhanced networking & VPC for full throughput

m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.

I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).

Caveats & Notes:

The large instance size has the most variation reported:

  • m1.large is ~800 Mbit/s (!!!)
  • t2.large = ~500 MBit/s
  • c3.large = ~500-570 Mbit/s (different results from different sources)
  • c4.large = ~520 MBit/s (I've confirmed this independently, by the way)
  • m3.large is better at ~700 MBit/s
  • m4.large is ~445 Mbit/s
  • r3.large is ~390 Mbit/s

Burstable (T2) instances appear to exhibit burstable networking performance too:

  • The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:

  • t2.small (PDF)

  • t2.medium (PDF)
  • t2.large (PDF)

Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.

CodeIgniter 404 Page Not Found, but why?

It happens cause of multiple reasons but the answer missing above there's the "className" while extending your controller.

Make sure your class name is the same as your controller name is your controllers. e.g., If your controller name is Settings.php, you must extend the controller like.

class Settings extends CI_Controller
{
// some actions like...
     public function __construct(){
     // and so and so...
     }
}

How to terminate a python subprocess launched with shell=True

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p.kill()

p.kill() ends up killing the shell process and cmd is still running.

I found a convenient fix this by:

p = subprocess.Popen("exec " + cmd, stdout=subprocess.PIPE, shell=True)

This will cause cmd to inherit the shell process, instead of having the shell launch a child process, which does not get killed. p.pid will be the id of your cmd process then.

p.kill() should work.

I don't know what effect this will have on your pipe though.

CSS Layout - Dynamic width DIV

Or, if you know the width of the two "side" images and don't want to deal with floats:

<div class="container">
    <div class="left-panel"><img src="myleftimage" /></div>
    <div class="center-panel">Content goes here...</div>
    <div class="right-panel"><img src="myrightimage" /></div>
</div>

CSS:

.container {
    position:relative;
    padding-left:50px;
    padding-right:50px;
}

.container .left-panel {
    width: 50px;
    position:absolute;
    left:0px;
    top:0px;
}

.container .right-panel {
    width: 50px;
    position:absolute;
    right:0px;
    top:0px;
}

.container .center-panel {
    background: url('mymiddleimage');
}

Notes:

Position:relative on the parent div is used to make absolutely positioned children position themselves relative to that node.

How does the SQL injection from the "Bobby Tables" XKCD comic work?

It drops the students table.

The original code in the school's program probably looks something like

q = "INSERT INTO Students VALUES ('" + FNMName.Text + "', '" + LName.Text + "')";

This is the naive way to add text input into a query, and is very bad, as you will see.

After the values from the first name, middle name textbox FNMName.Text (which is Robert'); DROP TABLE STUDENTS; --) and the last name textbox LName.Text (let's call it Derper) are concatenated with the rest of the query, the result is now actually two queries separated by the statement terminator (semicolon). The second query has been injected into the first. When the code executes this query against the database, it will look like this

INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --', 'Derper')

which, in plain English, roughly translates to the two queries:

Add a new record to the Students table with a Name value of 'Robert'

and

Delete the Students table

Everything past the second query is marked as a comment: --', 'Derper')

The ' in the student's name is not a comment, it's the closing string delimiter. Since the student's name is a string, it's needed syntactically to complete the hypothetical query. Injection attacks only work when the SQL query they inject results in valid SQL.

Edited again as per dan04's astute comment

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Create a .c file containing just the line:

_MSC_VER

or

CompilerVersion=_MSC_VER

then pre-process with

cl /nologo /EP <filename>.c

It is easy to parse the output.

Handle Button click inside a row in RecyclerView

I find that typically:

  • I need to use multiple listeners because I have several buttons.
  • I want my logic to be in the activity and not the adapter or viewholder.

So @mark-keen's answer works well but having an interface provides more flexibility:

public static class MyViewHolder extends RecyclerView.ViewHolder {

    public ImageView iconImageView;
    public TextView iconTextView;

    public MyViewHolder(final View itemView) {
        super(itemView);

        iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
        iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);

        iconTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickListener.iconTextViewOnClick(v, getAdapterPosition());
            }
        });
        iconImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickListener.iconImageViewOnClick(v, getAdapterPosition());
            }
        });
    }
}

Where onClickListener is defined in your adapter:

public MyAdapterListener onClickListener;

public interface MyAdapterListener {

    void iconTextViewOnClick(View v, int position);
    void iconImageViewOnClick(View v, int position);
}

And probably set through your constructor:

public MyAdapter(ArrayList<MyListItems> newRows, MyAdapterListener listener) {

    rows = newRows;
    onClickListener = listener;
}

Then you can handle the events in your Activity or wherever your RecyclerView is being used:

mAdapter = new MyAdapter(mRows, new MyAdapter.MyAdapterListener() {
                    @Override
                    public void iconTextViewOnClick(View v, int position) {
                        Log.d(TAG, "iconTextViewOnClick at position "+position);
                    }

                    @Override
                    public void iconImageViewOnClick(View v, int position) {
                        Log.d(TAG, "iconImageViewOnClick at position "+position);
                    }
                });
mRecycler.setAdapter(mAdapter);

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

What you need is a quadrangle instead of a rotated rectangle. RotatedRect will give you incorrect results. Also you will need a perspective projection.

Basicly what must been done is:

  • Loop through all polygon segments and connect those which are almost equel.
  • Sort them so you have the 4 most largest line segments.
  • Intersect those lines and you have the 4 most likely corner points.
  • Transform the matrix over the perspective gathered from the corner points and the aspect ratio of the known object.

I implemented a class Quadrangle which takes care of contour to quadrangle conversion and will also transform it over the right perspective.

See a working implementation here: Java OpenCV deskewing a contour

What is the HTML unicode character for a "tall" right chevron?

From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.

In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).

Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family list or to use a downloadable font. See my Guide to using special characters in HTML.

Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?

Git and nasty "error: cannot lock existing info/refs fatal"

In my case I had to manually delete old tags which had been removed on remote.

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:

  • Verbose - Show all log messages (the default).
  • Debug - Show debug log messages that are useful during development only, as well as the message levels lower in this list.
  • Info - Show expected log messages for regular usage, as well as the message levels lower in this list.
  • Warn - Show possible issues that are not yet errors, as well as the message levels lower in this list.
  • Error - Show issues that have caused errors, as well as the message level lower in this list.
  • Assert - Show issues that the developer expects should never happen.

Maven: Command to update repository after adding dependency to POM

If you want to only download dependencies without doing anything else, then it's:

mvn dependency:resolve

Or to download a single dependency:

mvn dependency:get -Dartifact=groupId:artifactId:version

If you need to download from a specific repository, you can specify that with -DrepoUrl=...

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Perhaps NSValue, just make sure your pointers are still valid after the delay (ie. no objects allocated on stack).

How to set a Default Route (To an Area) in MVC

Locating the different building blocks is done in the request life cycle. One of the first steps in the ASP.NET MVC request life cycle is mapping the requested URL to the correct controller action method. This process is referred to as routing. A default route is initialized in the Global.asax file and describes to the ASP.NET MVC framework how to handle a request. Double-clicking on the Global.asax file in the MvcApplication1 project will display the following code:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing;

namespace MvcApplication1 {

   public class GlobalApplication : System.Web.HttpApplication
   {
       public static void RegisterRoutes(RouteCollection routes)
       {
           routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

           routes.MapRoute(
               "Default",                                          // Route name
               "{controller}/{action}/{id}",                       // URL with parameters
               new { controller = "Home", action = "Index",
                     id = "" }  // Parameter defaults
           );

       }

       protected void Application_Start()
       {
           RegisterRoutes(RouteTable.Routes);
       }
   }

}

In the Application_Start() event handler, which is fired whenever the application is compiled or the web server is restarted, a route table is registered. The default route is named Default, and responds to a URL in the form of http://www.example.com/{controller}/{action}/{id}. The variables between { and } are populated with actual values from the request URL or with the default values if no override is present in the URL. This default route will map to the Home controller and to the Index action method, according to the default routing parameters. We won't have any other action with this routing map.

By default, all the possible URLs can be mapped through this default route. It is also possible to create our own routes. For example, let's map the URL http://www.example.com/Employee/Maarten to the Employee controller, the Show action, and the firstname parameter. The following code snippet can be inserted in the Global.asax file we've just opened. Because the ASP.NET MVC framework uses the first matching route, this code snippet should be inserted above the default route; otherwise the route will never be used.

routes.MapRoute(

   "EmployeeShow",                    // Route name
   "Employee/{firstname}",            // URL with parameters
    new {                             // Parameter defaults
       controller = "Employee",
       action = "Show", 
       firstname = "" 
   }  

);

Now, let's add the necessary components for this route. First of all, create a class named EmployeeController in the Controllers folder. You can do this by adding a new item to the project and selecting the MVC Controller Class template located under the Web | MVC category. Remove the Index action method, and replace it with a method or action named Show. This method accepts a firstname parameter and passes the data into the ViewData dictionary. This dictionary will be used by the view to display data.

The EmployeeController class will pass an Employee object to the view. This Employee class should be added in the Models folder (right-click on this folder and then select Add | Class from the context menu). Here's the code for the Employee class:

namespace MvcApplication1.Models {

   public class Employee
   {
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Email { get; set; }
   }

} 

How do relative file paths work in Eclipse?

Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:

The classes under java.io resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.

Eclipse sets the working directory to the top-level project folder.

Setting a div's height in HTML with CSS

Here's an example of equal-height columns - Equal Height Columns - revisited

You can also check out the idea of "Faux Columns" as well - Faux Columns

Don't go the table route. If it's not tabular data, don't treat it as such. It's bad for accessibility and flexibility.

ITextSharp HTML to PDF?

I came across the same question a few weeks ago and this is the result from what I found. This method does a quick dump of HTML to a PDF. The document will most likely need some format tweaking.

private MemoryStream createPDF(string html)
{
    MemoryStream msOutput = new MemoryStream();
    TextReader reader = new StringReader(html);

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 30, 30);

    // step 2:
    // we create a writer that listens to the document
    // and directs a XML-stream to a file
    PdfWriter writer = PdfWriter.GetInstance(document, msOutput);

    // step 3: we create a worker parse the document
    HTMLWorker worker = new HTMLWorker(document);

    // step 4: we open document and start the worker on the document
    document.Open();
    worker.StartDocument();

    // step 5: parse the html into the document
    worker.Parse(reader);

    // step 6: close the document and the worker
    worker.EndDocument();
    worker.Close();
    document.Close();

    return msOutput;
}

How do I copy folder with files to another folder in Unix/Linux?

The option you're looking for is -R.

cp -R path_to_source path_to_destination/
  • If destination doesn't exist, it will be created.
  • -R means copy directories recursively. You can also use -r since it's case-insensitive.
  • Note the nuances with adding the trailing / as per @muni764's comment.

Twitter Bootstrap - borders

If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.

For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:

.row {
    zoom: 1;
    margin-left: -20px;
}

.row > [class*="span"] {
    display: inline;
    float: left;
    margin-left: 20px;
}

.span4 {
    width: 220px;
}

To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).

Screenshot of Example Page

For example, to allow for the left border on the sidebar, they added this CSS in the <head> after the the main <link href="../bootstrap.css" rel="stylesheet">.

.content .span4 {
    margin-left: 0;
    padding-left: 19px;
    border-left: 1px solid #eee;
}

You'll see they've reduced padding-left by 1px to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.

I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.

Python: Random numbers into a list

import random
my_randoms = [random.randrange(1, 101, 1) for _ in range(10)]

How to close the current fragment by using Button like the back button?

You can try this logic because it is worked for me.

frag_profile profile_fragment = new frag_profile();

boolean flag = false;
@SuppressLint("ResourceType")
public void profile_Frag(){
    if (flag == false) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.setCustomAnimations(R.anim.transition_anim0, R.anim.transition_anim1);
        transaction.replace(R.id.parentPanel, profile_fragment, "FirstFragment");
        transaction.commit();
        flag = true;
    }

}

@Override
public void onBackPressed() {
    if (flag == true) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.remove(profile_fragment);
        transaction.commit();
        flag = false;
    }
    else super.onBackPressed();
}

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

There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.

I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.

Using success/error/finally/catch with Promises in AngularJS

I do it like Bradley Braithwaite suggests in his blog:

app
    .factory('searchService', ['$q', '$http', function($q, $http) {
        var service = {};

        service.search = function search(query) {
            // We make use of Angular's $q library to create the deferred instance
            var deferred = $q.defer();

            $http
                .get('http://localhost/v1?=q' + query)
                .success(function(data) {
                    // The promise is resolved once the HTTP call is successful.
                    deferred.resolve(data);
                })
                .error(function(reason) {
                    // The promise is rejected if there is an error with the HTTP call.
                    deferred.reject(reason);
                });

            // The promise is returned to the caller
            return deferred.promise;
        };

        return service;
    }])
    .controller('SearchController', ['$scope', 'searchService', function($scope, searchService) {
        // The search service returns a promise API
        searchService
            .search($scope.query)
            .then(function(data) {
                // This is set when the promise is resolved.
                $scope.results = data;
            })
            .catch(function(reason) {
                // This is set in the event of an error.
                $scope.error = 'There has been an error: ' + reason;
            });
    }])

Key Points:

  • The resolve function links to the .then function in our controller i.e. all is well, so we can keep our promise and resolve it.

  • The reject function links to the .catch function in our controller i.e. something went wrong, so we can’t keep our promise and need to reject it.

It is quite stable and safe and if you have other conditions to reject the promise you can always filter your data in the success function and call deferred.reject(anotherReason) with the reason of the rejection.

As Ryan Vice suggested in the comments, this may not be seen as useful unless you fiddle a bit with the response, so to speak.

Because success and error are deprecated since 1.4 maybe it is better to use the regular promise methods then and catch and transform the response within those methods and return the promise of that transformed response.

I am showing the same example with both approaches and a third in-between approach:

success and error approach (success and error return a promise of an HTTP response, so we need the help of $q to return a promise of data):

function search(query) {
  // We make use of Angular's $q library to create the deferred instance
  var deferred = $q.defer();

  $http.get('http://localhost/v1?=q' + query)
  .success(function(data,status) {
    // The promise is resolved once the HTTP call is successful.
    deferred.resolve(data);              
  })

  .error(function(reason,status) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.error){
      deferred.reject({text:reason.error, status:status});
    }else{
      //if we don't get any answers the proxy/api will probably be down
      deferred.reject({text:'whatever', status:500});
    }
  });

  // The promise is returned to the caller
  return deferred.promise;
};

then and catch approach (this is a bit more difficult to test, because of the throw):

function search(query) {

  var promise=$http.get('http://localhost/v1?=q' + query)

  .then(function (response) {
    // The promise is resolved once the HTTP call is successful.
    return response.data;
  },function(reason) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.statusText){
      throw reason;
    }else{
      //if we don't get any answers the proxy/api will probably be down
      throw {statusText:'Call error', status:500};
    }

  });

  return promise;
}

There is a halfway solution though (this way you can avoid the throw and anyway you'll probably need to use $q to mock the promise behavior in your tests):

function search(query) {
  // We make use of Angular's $q library to create the deferred instance
  var deferred = $q.defer();

  $http.get('http://localhost/v1?=q' + query)

  .then(function (response) {
    // The promise is resolved once the HTTP call is successful.
    deferred.resolve(response.data);
  },function(reason) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.statusText){
      deferred.reject(reason);
    }else{
      //if we don't get any answers the proxy/api will probably be down
      deferred.reject({statusText:'Call error', status:500});
    }

  });

  // The promise is returned to the caller
  return deferred.promise;
}

Any kind of comments or corrections are welcome.

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

Remove an array element and shift the remaining ones

Depending on your requirements, you may want to use stl lists for these types of operations. You can iterate through your list until you find the element, and erase the element. If you can't use lists, then you'll have to shift everything yourself, either by some sort of stl algorithm or manually.

Can I style an image's ALT text with CSS?

as this question is the first result at search engines

There are a problem with the selected -and right by the way- solution, is that if you want to add style that will apply to images like ( borders for example ) .

for example :

_x000D_
_x000D_
img {_x000D_
  color:#fff;_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  background-color: #ccc;_x000D_
}
_x000D_
<img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /> <hr />_x000D_
<img src="https://cdn4.iconfinder.com/data/icons/miu-square-flat-social/60/stackoverflow-square-social-media-128.png" alt="BLAH BLAH BLAH" />
_x000D_
_x000D_
_x000D_

as you can see, all of images will apply the same style


there is another approach to easily work around such an issue, using onerror and injecting some special class to deal with the interrupted images :

_x000D_
_x000D_
.invalidImageSrc {_x000D_
  color:#fff;_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  background-color: #ccc;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
_x000D_
<img onerror="$(this).addClass('invalidImageSrc')" src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /> <hr />_x000D_
<img onerror="$(this).addClass('invalidImageSrc')" src="https://cdn4.iconfinder.com/data/icons/miu-square-flat-social/60/stackoverflow-square-social-media-128.png" alt="BLAH BLAH BLAH" />
_x000D_
_x000D_
_x000D_

No suitable records were found verify your bundle identifier is correct

Once check this.

Open your .plist file and check for "Bundle OS Type code" key. If that is not there, add a row and give that key and check the type it should be a string. And give "APPL" as value.

Clean the project and go for Archive.

I hope it will work for you.

PHP - Notice: Undefined index:

For starters,

mysql_connect() should not have a $ accompanying it; it is not a variable, it is a predefined function. Remove the $ to properly connect to the database.

Why do you have an XML tag at the top of this document? This is HTML/PHP - a HTML doctype should suffice.

From line 215, update:

if (isset($_POST)) {
    $Name = $_POST['Name'];
    $Surname = $_POST['Surname'];

    $Username = $_POST['Username'];

    $Email = $_POST['Email'];
    $C_Email = $_POST['C_Email'];

    $Password = $_POST['password'];
    $C_Password = $_POST['c_password'];

    $SecQ = $_POST['SecQ'];
    $SecA = $_POST['SecA'];
}

POST variables are coming from your form, and you have to check whether they exist or not, else PHP will give you a NOTICE error. You can disable these notices by placing error_reporting(0); at the top of your document. It's best to keep these visible for development purposes.

You should only be interacting with the database (inserting, checking) under the condition that the form has been submitted. If you do not, PHP will run all of these operations without any input from the user. Its best to use an IF statement, like so:

if (isset($_POST['submit']) {
// blah blah
// check if user exists, check if fields are blank
// insert the user if all of this stuff checks out..
} else {
// just display the form
}

Awesome form tutorial: http://php.about.com/od/learnphp/ss/php_forms.htm

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

ImportError: No module named six

pip install --ignore-installed six

Source: 1233 thumbs up on this comment

How to store file name in database, with other info while uploading image to server using PHP?

Here is the answer for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database. Please let me know if it helped.

Firstly the form you need:

    <form method="post" action="addMember.php" enctype="multipart/form-data">
    <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Band Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
            </p>
            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
          </form>

Then this code processes you data from the form:

   <?php

// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;

// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?> 

Code edited from www.about.com

How to make an HTML back link?

history.go(-1) doesn't work if you click around in the 2nd domain or if the referrer is empty.

So we have to store the historyCount on arriving to this domain and go back the number of navigations in this side minus 1.


// if referrer is different from this site
if (!document.referrer.includes(window.location.host)) {
  // store current history length
  localStorage.setItem('historyLength', `${history.length}`);
}

// Return to stored referrer on logo click
document.querySelector('header .logo').addEventListener('click', 
  () =>
   history.go(Number(localStorage.getItem('historyLength')) - history.length -1)
);

Convert varchar into datetime in SQL Server

I found this helpful for my conversion, without string manipulation. https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

CONVERT(VARCHAR(23), @lastUploadEndDate, 121)

yyyy-mm-dd hh:mi:ss.mmm(24h) was the format I needed.

JQuery Number Formatting

Putting this http://www.mredkj.com/javascript/numberFormat.html and $('.number').formatNumber(); concept together, you may use the following line of code;

e.g. <td class="number">1172907.50</td> will be formatted like <td class="number">1,172,907.50</td>

$('.number').text(function () { 
    var str = $(this).html() + ''; 
    x = str.split('.'); 
    x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; 
    var rgx = /(\d+)(\d{3})/; 
    while (rgx.test(x1)) { 
        x1 = x1.replace(rgx, '$1' + ',' + '$2'); 
    } 
    $(this).html(x1 + x2); 
});

What is the difference between utf8mb4 and utf8 charsets in MySQL?

  • utf8 is MySQL's older, flawed implementation of UTF-8 which is in the process of being deprecated.
  • utf8mb4 is what they named their fixed UTF-8 implementation, and is what you should use right now.

In their flawed version, only characters in the first 64k character plane - the basic multilingual plane - work, with other characters considered invalid. The code point values within that plane - 0 to 65535 (some of which are reserved for special reasons) can be represented by multi-byte encodings in UTF-8 of up to 3 bytes, and MySQL's early version of UTF-8 arbitrarily decided to set that as a limit. At no point was this limitation a correct interpretation of the UTF-8 rules, because at no point was UTF-8 defined as only allowing up to 3 bytes per character. In fact, the earliest definitions of UTF-8 defined it as having up to 6 bytes (since revised to 4). MySQL's original version was always arbitrarily crippled.

Back when MySQL released this, the consequences of this limitation weren't too bad as most Unicode characters were in that first plane. Since then, more and more newly defined character ranges have been added to Unicode with values outside that first plane. Unicode itself defines 17 planes, though so far only 7 of these are used.

In an effort not to break old code making any particular assumptions, MySQL retained the broken implementation and called the newer, fixed version utf8mb4. This has led to some confusion with the name being misinterpreted as if it's some kind of extension to UTF-8 or alternative form of UTF-8, rather than MySQL's implementation of the true UTF-8.

Future versions of MySQL will eventually phase out the older version, and for now it can be considered deprecated. For the foreseeable future you need to use utf8mb4 to ensure correct UTF-8 encoding. After sufficient time has passed, the current utf8 will be removed, and at some future date utf8 will rise again, this time referring to the fixed version, though utf8mb4 will continue to unambiguously refer to the fixed version.

R: rJava package install failing

below is one of my answers on another post - error: unable to load installed packages just now
(this is also relevant to this question)

For Linux(Ubuntu) users: If you have oracle-java (7/8) installed. It'll be at this location /usr/lib/jvm and sudo access is required.

Create the file /etc/ld.so.conf.d/java.conf with the following entries:

/usr/lib/jvm/java-8-oracle/jre/lib/amd64
/usr/lib/jvm/java-8-oracle/jre/lib/amd64/server

(Replace java-8-oracle with java-7-oracle depending on your java version)

Then:

sudo ldconfig

Restart RStudio and then install the rJava package.

ASP.NET MVC3 Razor - Html.ActionLink style

VB sample:

 @Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})

Sample Css:

.someClass
{
    color: Green !important;
}

In my case, I found that I need the !important attribute to over ride the site.css a:link css class

Hide/encrypt password in bash file to stop accidentally seeing it

OpenSSL provides a passwd command that can encrypt but doesn't decrypt as it only does hashes. You could also download something like aesutil so you can use a capable and well-known symmetric encryption routine.

For example:

#!/bin/sh    
# using aesutil
SALT=$(mkrand 15) # mkrand generates a 15-character random passwd
MYENCPASS="i/b9pkcpQAPy7BzH2JlqHVoJc2mNTBM=" # echo "passwd" | aes -e -b -B -p $SALT 
MYPASS=$(echo "$MYENCPASS" | aes -d -b -p $SALT)

# and usage
serverControl.sh -u admin -p $MYPASS -c shutdown

How to stop asynctask thread in android?

declare your asyncTask in your activity:

private YourAsyncTask mTask;

instantiate it like this:

mTask = new YourAsyncTask().execute();

kill/cancel it like this:

mTask.cancel(true);

How to print HTML content on click of a button, but not the page?

According to this SO link you can print a specific div with

w=window.open();
w.document.write(document.getElementsByClassName('report_left_inner')[0].innerH??TML);
w.print();
w.close();

What properties can I use with event.target?

event.target returns the DOM element, so you can retrieve any property/ attribute that has a value; so, to answer your question more specifically, you will always be able to retrieve nodeName, and you can retrieve href and id, provided the element has a href and id defined; otherwise undefined will be returned.

However, inside an event handler, you can use this, which is set to the DOM element as well; much easier.

$('foo').bind('click', function () {
    // inside here, `this` will refer to the foo that was clicked
});

How do you sort an array on multiple columns?

I had a similar problem while displaying memory pool blocks from the output of some virtual DOM h-functions composition. Basically I faced to the same problem as sorting multi-criteria data like scoring results from players around the world.

I have noticed that multi-criteria sorting is:

- sort by the first column
- if equal, sort by the second
- if equal, sort by the third
-  etc... nesting and nesting if-else

And if you don't care, you could fail quickly in a if-else nesting hell... like callback hell of promises...

What about if we write a "predicate" function to decide if which part of alternative using ? The predicate is simply :

// useful for chaining test
const decide = (test, other) => test === 0 ? other : test

Now after having written your classifying tests (byCountrySize, byAge, byGameType, byScore, byLevel...) whatever who need, you can weight your tests (1 = asc, -1 = desc, 0 = disable), put them in an array, and apply a reducing 'decide' function like this:

const multisort = (s1, s2) => {
  const bcs = -1 * byCountrySize(s1, s2) // -1 = desc 
  const ba =  1 *byAge(s1, s2)
  const bgt = 0 * byGameType(s1, s2) // 0 = doesn't matter
  const bs = 1 * byScore(s1, s2)
  const bl = -1 * byLevel(s1, s2) // -1 = desc

  // ... other weights and criterias

  // array order matters !
  return [bcs, ba, bgt, bs, bl].reduce((acc, val) => decide(val, acc), 0)
}

// invoke [].sort with custom sort...
scores.sort(multisort)

And voila ! It's up to you to define your own criterias / weights / orders... but you get the idea. Hope this helps !

EDIT: * ensure that there is a total sorting order on each column * be aware of not having dependencies between columns orders, and no circular dependencies

if, not, sorting can be unstable !

What is the difference between UTF-8 and ISO-8859-1?

From another perspective, files that both unicode and ascii encodings fail to read because they have a byte 0xc0 in them, seem to get read by iso-8859-1 properly. The caveat is that the file shouldn't have unicode characters in it of course.

Get most recent row for given ID

I had a similar problem. I needed to get the last version of page content translation, in other words - to get that specific record which has highest number in version column. So I select all records ordered by version and then take the first row from result (by using LIMIT clause).

SELECT *
FROM `page_contents_translations`
ORDER BY version DESC
LIMIT 1

How do you pass a function as a parameter in C?

It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.

#include <stdio.h>

int IncMultInt(int a, int b)
{
    a++;
    return a * b;
}

int main(int argc, char *argv[])

{
    int a = 5;
    int b = 7;

    printf("%d * %d = %d\n", a, b, IncMultInt(a, b));

    b = 9;

    // Create some local code with it's own local variable
    printf("%d * %d = %d\n", a, b,  ( { int _a = a+1; _a * b; } ) );

    return 0;
}

delete all from table

There is a mySQL bug report from 2004 that still seems to have some validity. It seems that in 4.x, this was fastest:

DROP table_name
CREATE TABLE table_name

TRUNCATE table_name was DELETE FROM internally back then, providing no performance gain.

This seems to have changed, but only in 5.0.3 and younger. From the bug report:

[11 Jan 2005 16:10] Marko Mäkelä

I've now implemented fast TRUNCATE TABLE, which will hopefully be included in MySQL 5.0.3.

CSS / HTML Navigation and Logo on same line

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

Codepen Demo

HTML

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

CSS

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

Clearing UIWebview cache

I am loading html pages from Documents and if they have the same name of css file UIWebView it seem it does not throw the previous css rules. Maybe because they have the same URL or something.

I tried this:

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];

I tried this :

[[NSURLCache sharedURLCache] removeAllCachedResponses];

I am loading the initial page with:

NSURLRequest *appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];

It refuses to throw its cached data! Frustrating!

I am doing this inside a PhoneGap (Cordova) application. I have not tried it in isolated UIWebView.

Update1: I have found this.
Changing the html files, though seems very messy.

Read/write to file using jQuery

Yes it is possible.

The technique is described below

http://jquery.tiddlywiki.org/twFile.html

Change <br> height using CSS

The line height of the br tag can be different from the line height of the rest of the text inside a paragraph text by setting font-size for br tag.

Example: br { font-size: 200%; }

How to write LDAP query to test if user is member of a group?

I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

What are the differences between "=" and "<-" assignment operators in R?

What are the differences between the assignment operators = and <- in R?

As your example shows, = and <- have slightly different operator precedence (which determines the order of evaluation when they are mixed in the same expression). In fact, ?Syntax in R gives the following operator precedence table, from highest to lowest:

…
‘-> ->>’           rightwards assignment
‘<- <<-’           assignment (right to left)
‘=’                assignment (right to left)
…

But is this the only difference?

Since you were asking about the assignment operators: yes, that is the only difference. However, you would be forgiven for believing otherwise. Even the R documentation of ?assignOps claims that there are more differences:

The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

Let’s not put too fine a point on it: the R documentation is wrong. This is easy to show: we just need to find a counter-example of the = operator that isn’t (a) at the top level, nor (b) a subexpression in a braced list of expressions (i.e. {…; …}). — Without further ado:

x
# Error: object 'x' not found
sum((x = 1), 2)
# [1] 3
x
# [1] 1

Clearly we’ve performed an assignment, using =, outside of contexts (a) and (b). So, why has the documentation of a core R language feature been wrong for decades?

It’s because in R’s syntax the symbol = has two distinct meanings that get routinely conflated (even by experts, including in the documentation cited above):

  1. The first meaning is as an assignment operator. This is all we’ve talked about so far.
  2. The second meaning isn’t an operator but rather a syntax token that signals named argument passing in a function call. Unlike the = operator it performs no action at runtime, it merely changes the way an expression is parsed.

So how does R decide whether a given usage of = refers to the operator or to named argument passing? Let’s see.

In any piece of code of the general form …

‹function_name›(‹argname› = ‹value›, …)
‹function_name›(‹args›, ‹argname› = ‹value›, …)

… the = is the token that defines named argument passing: it is not the assignment operator. Furthermore, = is entirely forbidden in some syntactic contexts:

if (‹var› = ‹value›) …
while (‹var› = ‹value›) …
for (‹var› = ‹value› in ‹value2›) …
for (‹var1› in ‹var2› = ‹value›) …

Any of these will raise an error “unexpected '=' in ‹bla›”.

In any other context, = refers to the assignment operator call. In particular, merely putting parentheses around the subexpression makes any of the above (a) valid, and (b) an assignment. For instance, the following performs assignment:

median((x = 1 : 10))

But also:

if (! (nf = length(from))) return()

Now you might object that such code is atrocious (and you may be right). But I took this code from the base::file.copy function (replacing <- with =) — it’s a pervasive pattern in much of the core R codebase.

The original explanation by John Chambers, which the the R documentation is probably based on, actually explains this correctly:

[= assignment is] allowed in only two places in the grammar: at the top level (as a complete program or user-typed expression); and when isolated from surrounding logical structure, by braces or an extra pair of parentheses.


In sum, by default the operators <- and = do the same thing. But either of them can be overridden separately to change its behaviour. By contrast, <- and -> (left-to-right assignment), though syntactically distinct, always call the same function. Overriding one also overrides the other. Knowing this is rarely practical but it can be used for some fun shenanigans.

#1214 - The used table type doesn't support FULLTEXT indexes

*************Resolved - #1214 - The used table type doesn't support FULLTEXT indexes***************

Its Very Simple to resolve this issue. People are answering here in very difficult words which are not easily understandable by the people who are not technical.

So i am mentioning here steps in very simple words will resolve your issue.

1.) Open your .sql file with Notepad by right clicking on file>Edit Or Simply open a Notepad file and drag and drop the file on Notepad and the file will be opened. (Note: Please don't change the extention .sql of file as its still your sql database. Also to keep a copy of your sql file to save yourself from any mishappening)

2.) Click on Notepad Menu Edit > Replace (A Window will be pop us with Find What & Replace With Fields)

3.) In Find What Field Enter ENGINE=InnoDB & In Replace With Field Enter ENGINE=MyISAM

4.) Now Click on Replace All Button

5.) Click CTRL+S or File>Save

6.) Now Upload This File and I am Sure your issue will be resolved....

Break out of a While...Wend loop

A While/Wend loop can only be exited prematurely with a GOTO or by exiting from an outer block (Exit sub/function or another exitable loop)

Change to a Do loop instead:

Do While True
    count = count + 1

    If count = 10 Then
        Exit Do
    End If
Loop

Or for looping a set number of times:

for count = 1 to 10
   msgbox count
next

(Exit For can be used above to exit prematurely)

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

However, the code below allows spaces.

No, it doesn't. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a + following the character class:

var regexp = /^[a-zA-Z0-9-_]+$/;
var check = "checkme";
if (check.search(regexp) === -1)
    { alert('invalid'); }
else
    { alert('valid'); }

Note that neither the - (in this instance) nor the _ need escaping.

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

Impact of Xcode build options "Enable bitcode" Yes/No

Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):

When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.

Note: the answer was edited on Jan 2016 to reflect most recent changes

How can I send JSON response in symfony2 controller

Symfony 2.1 has a JsonResponse class.

return new JsonResponse(array('name' => $name));

The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.

There is also a handy setCallback function for JSONP.

App can't be opened because it is from an unidentified developer

Terminal type:

Last login: Thu Dec 20 08:28:43 on console
 ~ ? sudo spctl --master-disable
Password:
 ~ ? spctl --status
assessments disabled
 ~ ?

System Preferences->Security & Privacy

enter image description here

.Net System.Mail.Message adding multiple "To" addresses

I wasn't able to replicate your bug:

var message = new MailMessage();

message.To.Add("[email protected]");
message.To.Add("[email protected]");

message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.Body = "Test";

var client = new SmtpClient("localhost", 25);
client.Send(message);

Dumping the contents of the To: MailAddressCollection:

MailAddressCollection (2 items)
DisplayName User Host Address

user example.com [email protected]
user2 example.com [email protected]

And the resulting e-mail as caught by smtp4dev:

Received: from mycomputername (mycomputername [127.0.0.1])
     by localhost (Eric Daugherty's C# Email Server)
     3/8/2010 12:50:28 PM
MIME-Version: 1.0
From: [email protected]
To: [email protected], [email protected]
Date: 8 Mar 2010 12:50:28 -0800
Subject: Test
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

Test

Are you sure there's not some other issue going on with your code or SMTP server?

In Angular, I need to search objects in an array

A dirty and easy solution could look like

$scope.showdetails = function(fish_id) {
    angular.forEach($scope.fish, function(fish, key) {
        fish.more = fish.id == fish_id;
    });
};

Padding a table row

In CSS 1 and CSS 2 specifications, padding was available for all elements including <tr>. Yet support of padding for table-row (<tr>) has been removed in CSS 2.1 and CSS 3 specifications. I have never found the reason behind this annoying change which also affect margin property and a few other table elements (header, footer, and columns).

Update: in Feb 2015, this thread on the [email protected] mailing list discussed about adding support of padding and border for table-row. This would apply the standard box model also to table-row and table-column elements. It would permit such examples. The thread seems to suggest that table-row padding support never existed in CSS standards because it would have complicated layout engines. In the 30 September 2014 Editor's Draft of CSS basic box model, padding and border properties exist for all elements including table-row and table-column elements. If it eventually becomes a W3C recommendation, your html+css example may work as intended in browsers at last.

How to remove word wrap from textarea?

textarea {
  white-space: pre;
  overflow-wrap: normal;
  overflow-x: scroll;
}

white-space: nowrap also works if you don't care about whitespace, but of course you don't want that if you're working with code (or indented paragraphs or any content where there might deliberately be multiple spaces) ... so i prefer pre.

overflow-wrap: normal (was word-wrap in older browsers) is needed in case some parent has changed that setting; it can cause wrapping even if pre is set.

also -- contrary to the currently accepted answer -- textareas do often wrap by default. pre-wrap seems to be the default on my browser.

Dynamically changing font size of UILabel

Its a little bit not sophisticated but this should work, for example lets say you want to cap your uilabel to 120x120, with max font size of 28:

magicLabel.numberOfLines = 0;
magicLabel.lineBreakMode = NSLineBreakByWordWrapping;
...
magicLabel.text = text;
    for (int i = 28; i>3; i--) {
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:(CGFloat)i] constrainedToSize:CGSizeMake(120.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        if (size.height < 120) {
            magicLabel.font = [UIFont systemFontOfSize:(CGFloat)i];
            break;
        }
    }

How to create a hex dump of file containing only the hex characters without spaces in bash?

I think this is the most widely supported version (requiring only POSIX defined tr and od behavior):

cat "$file" | od -v -t x1 -A n | tr -d ' \n'

This uses od to print each byte as hex without address without skipping repeated bytes and tr to delete all spaces and linefeeds in the output. Note that not even the trailing linefeed is emitted here. (The cat is intentional to allow multicore processing where cat can wait for filesystem while od is still processing previously read part. Single core users may want replace that with < "$file" od ... to save starting one additional process.)

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

Setting Camera Parameters in OpenCV/Python

Not all parameters are supported by all cameras - actually, they are one of the most troublesome part of the OpenCV library. Each camera type - from android cameras to USB cameras to professional ones offer a different interface to modify its parameters. There are many branches in OpenCV code to support as many of them, but of course not all possibilities are covered.

What you can do is to investigate your camera driver, write a patch for OpenCV and send it to code.opencv.org. This way others will enjoy your work, the same way you enjoy others'.

There is also a possibility that your camera does not support your request - most USB cams are cheap and simple. Maybe that parameter is just not available for modifications.

If you are sure the camera supports a given param (you say the camera manufacturer provides some code) and do not want to mess with OpenCV, you can wrap that sample code in C++ with boost::python, to make it available in Python. Then, enjoy using it.

Using LIKE in an Oracle IN clause

What would be useful here would be a LIKE ANY predicate as is available in PostgreSQL

SELECT * 
FROM tbl
WHERE my_col LIKE ANY (ARRAY['%val1%', '%val2%', '%val3%', ...])

Unfortunately, that syntax is not available in Oracle. You can expand the quantified comparison predicate using OR, however:

SELECT * 
FROM tbl
WHERE my_col LIKE '%val1%' OR my_col LIKE '%val2%' OR my_col LIKE '%val3%', ...

Or alternatively, create a semi join using an EXISTS predicate and an auxiliary array data structure (see this question for details):

SELECT *
FROM tbl t
WHERE EXISTS (
  SELECT 1
  -- Alternatively, store those values in a temp table:
  FROM TABLE (sys.ora_mining_varchar2_nt('%val1%', '%val2%', '%val3%'/*, ...*/))
  WHERE t.my_col LIKE column_value
)

For true full-text search, you might want to look at Oracle Text: http://www.oracle.com/technetwork/database/enterprise-edition/index-098492.html

jQuery or Javascript - how to disable window scroll without overflow:hidden;

If you want to scroll the element you're over and prevent the window to scroll, here's a really useful function :

$('.Scrollable').on('DOMMouseScroll mousewheel', function(ev) {
    var $this = $(this),
        scrollTop = this.scrollTop,
        scrollHeight = this.scrollHeight,
        height = $this.height(),
        delta = (ev.type == 'DOMMouseScroll' ?
            ev.originalEvent.detail * -40 :
            ev.originalEvent.wheelDelta),
        up = delta > 0;

    var prevent = function() {
        ev.stopPropagation();
        ev.preventDefault();
        ev.returnValue = false;
        return false;
    }

    if (!up && -delta > scrollHeight - height - scrollTop) {
        // Scrolling down, but this will take us past the bottom.
        $this.scrollTop(scrollHeight);

        return prevent();
    } else if (up && delta > scrollTop) {
        // Scrolling up, but this will take us past the top.
        $this.scrollTop(0);
        return prevent();
    }
});

Apply the class "Scrollable" to your element and that's it!

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

Rails does not use the stdlib's ERB by default, it uses erubis. Sources: this dev's comment, ActionView's gemspec, accepted merge request I did while writing this.

There are behavior differences between them, in particular on how the hyphen operators %- and -% work.

Documentation is scarce, Where is Ruby's ERB format "officially" defined? so what follows are empirical conclusions.

All tests suppose:

require 'erb'
require 'erubis'

When you can use -

  • ERB: you must pass - to trim_mode option of ERB.new to use it.
  • erubis: enabled by default.

Examples:

begin ERB.new("<%= 'a' -%>\nb").result; rescue SyntaxError ; else raise; end
ERB.new("<%= 'a' -%>\nb"  , nil, '-') .result == 'ab'  or raise
Erubis::Eruby.new("<%= 'a' -%>  \n b").result == 'a b' or raise

What -% does:

  • ERB: remove the next character if it is a newline.

  • erubis:

    • in <% %> (without =), - is useless because <% %> and <% -%> are the same. <% %> removes the current line if it only contains whitespaces, and does nothing otherwise.

    • in <%= -%> (with =):

      • remove the entire line if it only contains whitespaces
      • else, if there is a non-space before the tag, and only whitesapces after, remove the whitespces that come after
      • else, there is a non-space after the tag: do nothing

Examples:

# Remove
ERB.new("a \nb <% 0 -%>\n c", nil, '-').result == "a \nb  c" or raise

# Don't do anything: not followed by newline, but by space:
ERB.new("a\n<% 0 -%> \nc", nil, '-').result == "a\nb \nc" or raise

# Remove the current line because only whitesapaces:
Erubis::Eruby.new(" <% 0 %> \nb").result == 'b' or raise

# Same as above, thus useless because longer.
Erubis::Eruby.new(" <% 0 -%> \nb").result == 'b' or raise

# Don't do anything because line not empty.
Erubis::Eruby.new("a <% 0 %> \nb").result == "a  \nb" or raise
Erubis::Eruby.new(" <% 0 %> a\nb").result == "  a\nb" or raise
Erubis::Eruby.new(" <% 0 -%> a\nb").result == "  a\nb" or raise

# Don't remove the current line because of `=`:
Erubis::Eruby.new(" <%= 0 %> \nb").result == " 0 \nb" or raise

# Remove the current line even with `=`:
Erubis::Eruby.new(" <%= 0 -%> \nb").result == " 0b"   or raise

# Remove forward only because of `-` and non space before:
Erubis::Eruby.new("a <%= 0 -%> \nb").result == "a 0b"   or raise

# Don't do anything because non-whitespace forward:
Erubis::Eruby.new(" <%= 0 -%> a\nb").result == " 0 a\nb"   or raise

What %- does:

  • ERB: remove whitespaces before tag and after previous newlines, but only if there are only whitespaces before.

  • erubis: useless because <%- %> is the same as <% %> (without =), and this cannot be used with = which is the only case where -% can be useful. So never use this.

Examples:

# Remove
ERB.new("a \n  <%- 0 %> b\n c", nil, '-').result == "a \n b\n c" or raise

# b is not whitespace: do nothing:
ERB.new("a \nb  <%- 0 %> c\n d", nil, '-').result == "a \nb   c\n d" or raise

What %- and -% do together

The exact combination of both effects separately.

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

Just come across it and got an answer somewhere. you can use below annotation since 2.7.0

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class Point {
    final private double x;
    final private double y;

    @ConstructorProperties({"x", "y"})
    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

You can use shuf. On some systems at least (doesn't appear to be in POSIX).

As jleedev pointed out: sort -R might also be an option. On some systems at least; well, you get the picture. It has been pointed out that sort -R doesn't really shuffle but instead sort items according to their hash value.

[Editor's note: sort -R almost shuffles, except that duplicate lines / sort keys always end up next to each other. In other words: only with unique input lines / keys is it a true shuffle. While it's true that the output order is determined by hash values, the randomness comes from choosing a random hash function - see manual.]

What causing this "Invalid length for a Base-64 char array"

After urlDecode processes the text, it replaces all '+' chars with ' ' ... thus the error. You should simply call this statement to make it base 64 compatible again:

        sEncryptedString = sEncryptedString.Replace(' ', '+');

cleanup php session files

In case someone want's to do this with a cronjob, please keep in mind that this:

find .session/ -atime +7  -exec rm {} \;

is really slow, when having a lot of files.

Consider using this instead:

find .session/ -atime +7 | xargs -r rm

In Case you have spaces in you file names use this:

find .session/ -atime +7 -print0 | xargs -0 -r rm

xargs will fill up the commandline with files to be deleted, then run the rm command a lot lesser than -exec rm {} \;, which will call the rm command for each file.

Just my two cents

Remove all the elements that occur in one list from another

Alternate Solution :

reduce(lambda x,y : filter(lambda z: z!=y,x) ,[2,3,5,8],[1,2,6,8])

How to install plugins to Sublime Text 2 editor?

According to John Day's answer

You should have a Data/Packages folder in your Sublime Text 2 install directory. All you need to do is download the plugin and put the plugin folder in the Packages folder.

In case if you are searching for Data/Packages folder you can find it here

Windows: %APPDATA%\Sublime Text 2

OS X: ~/Library/Application Support/Sublime Text 2

Linux: ~/.Sublime Text 2

Portable Installation: Sublime Text 2/Data

Could not find method compile() for arguments Gradle

Make sure that you are editing the correct build.gradle file. I received this error when editing android/build.gradle rather than android/app/build.gradle.

Submitting a form on 'Enter' with jQuery?

Also to maintain accessibility, you should use this to determine your keycode:

c = e.which ? e.which : e.keyCode;

if (c == 13) ...

How to set encoding in .getJSON jQuery

Use encodeURI() in client JS and use URLDecoder.decode() in server Java side works.


Example:

  • Javascript:

    $.getJSON(
        url,
        {
            "user": encodeURI(JSON.stringify(user))
        },
        onSuccess
    );
    
  • Java:

    java.net.URLDecoder.decode(params.user, "UTF-8");

Javascript "Not a Constructor" Exception while creating objects

I've googled around also and found this solution:

You have a variable Project somewhere that is not a function. Then the new operator will complain about it. Try console.log(Project) at the place where you would have used it as a construcotr, and you will find it.

How do I stop a program when an exception is raised in Python?

import sys

try:
    import feedparser
except:
    print "Error: Cannot import feedparser.\n" 
    sys.exit(1)

Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.

What is the command to exit a Console application in C#?

You can use Environment.Exit(0) and Application.Exit.

Environment.Exit(): terminates this process and gives the underlying operating system the specified exit code.

How do I remove link underlining in my HTML email?

place your "a href" tag without any styling before div / span of text. then make your styling in the div/span tag.

for the most restricted styling email client.

<div><a href=""><span style="text-decoration:none">title</span><a/></div>

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

$mysql -u root --host=127.0.0.1 -p

mysql>use mysql

mysql>GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'redhat@123';

mysql>FLUSH PRIVILEGES;

mysql> SELECT host FROM mysql.user WHERE User = 'root';

Select unique values with 'select' function in 'dplyr' library

The dplyr select function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by function. For example:

library(dplyr)

# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))

# Return the distinct values of x
dat %>%
  group_by(x) %>%
  summarise() 

    x
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

If you want to change the column name you can add the following:

dat %>%
  group_by(x) %>%
  summarise() %>%
  select(unique.x=x)

This both selects column x from among all the columns in the data frame that dplyr returns (and of course there's only one column in this case) and changes its name to unique.x.

You can also get the unique values directly in base R with unique(dat$x).

If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:

set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE), 
                 y=sample(letters[1:5], 100, replace=TRUE))

dat %>% 
  group_by(x,y) %>%
  summarise() %>%
  select(unique.x=x, unique.y=y)

Jenkins: Cannot define variable in pipeline stage

I think error is not coming from the specified line but from the first 3 lines. Try this instead :

node {
   stage("first") {
     def foo = "foo"
     sh "echo ${foo}"
   }
}

I think you had some extra lines that are not valid...

From declaractive pipeline model documentation, it seems that you have to use an environment declaration block to declare your variables, e.g.:

pipeline {
   environment {
     FOO = "foo"
   }

   agent none
   stages {
       stage("first") {
           sh "echo ${FOO}"
       }
   }
}

How do you run a .bat file from PHP?

<?php
 pclose(popen("start /B test.bat", "r")); die();
?> 

Execute php file from another php

This came across while working on a project on linux platform.

exec('wget http://<url to the php script>)

This runs as if you run the script from browser.

Hope this helps!!

How to retrieve a single file from a specific revision in Git?

This will help you get all deleted files between commits without specifying the path, useful if there are a lot of files deleted.

git diff --name-only --diff-filter=D $commit~1 $commit | xargs git checkout $commit~1

JavaScript get window X/Y position for scroll

Using pure javascript you can use Window.scrollX and Window.scrollY

window.addEventListener("scroll", function(event) {
    var top = this.scrollY,
        left =this.scrollX;
}, false);

Notes

The pageXOffset property is an alias for the scrollX property, and The pageYOffset property is an alias for the scrollY property:

window.pageXOffset == window.scrollX; // always true
window.pageYOffset == window.scrollY; // always true

Here is a quick demo

_x000D_
_x000D_
window.addEventListener("scroll", function(event) {_x000D_
  _x000D_
    var top = this.scrollY,_x000D_
        left = this.scrollX;_x000D_
  _x000D_
    var horizontalScroll = document.querySelector(".horizontalScroll"),_x000D_
        verticalScroll = document.querySelector(".verticalScroll");_x000D_
    _x000D_
    horizontalScroll.innerHTML = "Scroll X: " + left + "px";_x000D_
      verticalScroll.innerHTML = "Scroll Y: " + top + "px";_x000D_
  _x000D_
}, false);
_x000D_
*{box-sizing: border-box}_x000D_
:root{height: 200vh;width: 200vw}_x000D_
.wrapper{_x000D_
    position: fixed;_x000D_
    top:20px;_x000D_
    left:0px;_x000D_
    width:320px;_x000D_
    background: black;_x000D_
    color: green;_x000D_
    height: 64px;_x000D_
}_x000D_
.wrapper div{_x000D_
    display: inline;_x000D_
    width: 50%;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    line-height: 64px_x000D_
}_x000D_
.horizontalScroll{color: orange}
_x000D_
<div class=wrapper>_x000D_
    <div class=horizontalScroll>Scroll (x,y) to </div>_x000D_
    <div class=verticalScroll>see me in action</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Target WSGI script cannot be loaded as Python module

For me the issue was that the WSGI script wasn't executable.

sudo chmod a+x django.wsgi

or just

sudo chmod u+x django.wsgi

so long as you have the correct owner

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

I think we're over analyzing and maybe complicating a bit the "continuous" suite of words. In this context continuous means automation. For the other words attached to "continuous" use the English language as your translation guide and please don't try to complicate things! In "continuous build" we automatically build (write/compile/link/etc) our application into something that's executable for a specific platform/container/runtime/etc. "Continuous integration" means that your new functionality tests and performs as intended when interacting with another entity. Obviously, before integration takes place, the build must happen and thorough testing would also be used to validate the integration. So, in "continuous integration" one uses automation to add value to an existing bucket of functionality in a way that doesn't negatively disrupt the existing functionality but rather integrates nicely with it, adding a perceived value to the whole. Integration implies, by its mere English definition, that things jive harmoniously so in code-talk my add compiles, links, tests and runs perfectly within the whole. You wouldn't call something integrated if it failed the end product, would you?! In our context "Continuous deployment" is synonymous with "continuos delivery" since at the end of the day we've provided functionality to our customers. However, by over analyzing this, I could argue that deploy is a subset of delivery because deploying something doesn't necessarily mean that we delivered. We deployed the code but because we haven't effectively communicated to our stakeholders, we failed to deliver from a business perspective! We deployed the troops but we haven't delivered the promised water and food to the nearby town. What if I were to add the "continuous transition" term, would it have its own merit? After all, maybe it's better suited to describe the movement of code through environments since it has the connotation of "from/to" more so than deployment or delivery which could imply one location only, in perpetuity! This is what we get if we don't apply common sense.

In conclusion, this is simple stuff to describe (doing it is a bit more ...complicated!), just use common sense, the English language and you'll be fine.

How to show/hide JPanels in a JFrame?

You can hide a JPanel by calling setVisible(false). For example:

public static void main(String args[]){
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    //create a button which will hide the panel when clicked.
    JButton b = new JButton("HIDE");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p.setVisible(false);
        }
    });

    f.add(b,BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
}

How to fill color in a cell in VBA?

  1. Select all cells by left-top corner
  2. Choose [Home] >> [Conditional Formatting] >> [New Rule]
  3. Choose [Format only cells that contain]
  4. In [Format only cells with:], choose "Errors"
  5. Choose proper formats in [Format..] button

Setting up a cron job in Windows

If you don't want to use Scheduled Tasks you can use the Windows Subsystem for Linux which will allow you to use cron jobs like on Linux.

To make sure cron is actually running you can type service cron status from within the Linux terminal. If it isn't currently running then type service cron start and you should be good to go.

How to determine the IP address of a Solaris system

/usr/sbin/host `hostname`

should do the trick. Bear in mind that it's a pretty common configuration for a solaris box to have several IP addresses, though, in which case

 /usr/sbin/ifconfig -a inet | awk '/inet/ {print $2}'

will list them all

javascript functions to show and hide divs

<script> 
    function show() { 
        if(document.getElementById('benefits').style.display=='none') { 
            document.getElementById('benefits').style.display='block'; 
        } 
        return false;
    } 
    function hide() { 
        if(document.getElementById('benefits').style.display=='block') { 
            document.getElementById('benefits').style.display='none'; 
        } 
        return false;
    }   
</script> 


 <div id="opener"><a href="#1" name="1" onclick="return show();">click here</a></div> 
    <div id="benefits" style="display:none;">some input in here plus the close button 
           <div id="upbutton"><a onclick="return hide();">click here</a></div> 
    </div> 

Bad Request - Invalid Hostname IIS7

If working on local server or you haven't got domain name, delete "Host Name:" field. enter image description here

Programmatically obtain the phone number of the Android phone

Just want to add a bit here to above explanations in the above answers. Which will save time for others as well.

In my case this method didn't returned any mobile number, an empty string was returned. It was due to the case that I had ported my number on the new sim. So if I go into the Settings>About Phone>Status>My Phone Number it shows me "Unknown".

How to read single Excel cell value

The issue with reading single Excel Cell in .Net comes from the fact, that the empty cell is evaluated to a Null. Thus, one cannot use its .Value or .Value2 properties, because an error shows up.

To return an empty string, when the cell is Null the Convert.ToString(Cell) can be used in the following way:

Excel.Workbook wkb = Open(excel, filePath);
Excel.Worksheet wk = (Excel.Worksheet)excel.Worksheets.get_Item(1);

for (int i = 1; i < 5; i++)
{
    string a = Convert.ToString(wk.Cells[i, 1].Value2);
    Console.WriteLine(a);
}

How to select date without time in SQL

Try this.

SELECT DATEADD(DD, 0, DATEDIFF(DD, 0, GETDATE()))

Making the Android emulator run faster

I noticed that the emulator defaults to only Core 0, where most Windows applications will default to "any" core. Also, if you put it on another core (like the last core), it may make the emulator go crazy. If you can, you can try putting your heavy-CPU usage applications on the other CPU cores for a boost in speed.

Hardware-wise, get the fastest CPU you can get that works for single-core applications. More than 2 cores might not experience a huge difference in terms of emulator performance.

Eclipse + the Android emulator together eat up a ton of RAM. I would recommend 3 gigs of RAM at least because I used a system with 2 gigs of RAM, and it slowed down because the system ran out of RAM and started to use the page file.

I feel that the best CPUs for it will probably have a high clock (only use clock as a measure for CPUs in the same series btw), handle non-SIMD operations well, and have a turbo boost mechanism. There aren't many Java-based benchmarks, but overall look for application benchmarks like compression and office. Don't look at gaming or media since those are affected greatly by SIMD. If you find a Java one, even better.

How to start an Android application from the command line?

Example here.

Pasted below:

This is about how to launch android application from the adb shell.

Command: am

Look for invoking path in AndroidManifest.xml

Browser app::

# am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity
Starting: Intent { action=android.intent.action.MAIN comp={com.android.browser/com.android.browser.BrowserActivity} }
Warning: Activity not started, its current task has been brought to the front

Settings app::

# am start -a android.intent.action.MAIN -n com.android.settings/.Settings
Starting: Intent { action=android.intent.action.MAIN comp={com.android.settings/com.android.settings.Settings} }

How to write to the Output window in Visual Studio?

Use the OutputDebugString function or the TRACE macro (MFC) which lets you do printf-style formatting:

int x = 1;
int y = 16;
float z = 32.0;
TRACE( "This is a TRACE statement\n" );    
TRACE( "The value of x is %d\n", x );
TRACE( "x = %d and y = %d\n", x, y );
TRACE( "x = %d and y = %x and z = %f\n", x, y, z );

How can I read a large text file line by line using Java?

You need to use the readLine() method in class BufferedReader. Create a new object from that class and operate this method on him and save it to a string.

BufferReader Javadoc

How to configure the web.config to allow requests of any length

HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.

To resolve this problem, check in the source code whether the Form tag has a property method is get/set state.

If so, the method property should be removed.

Hashing a dictionary?

If your dictionary is not nested, you could make a frozenset with the dict's items and use hash():

hash(frozenset(my_dict.items()))

This is much less computationally intensive than generating the JSON string or representation of the dictionary.

UPDATE: Please see the comments below, why this approach might not produce a stable result.

What exactly does the .join() method do?

Look carefully at your output:

5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^                 ^                 ^

I've highlighted the "5", "9", "5" of your original string. The Python join() method is a string method, and takes a list of things to join with the string. A simpler example might help explain:

>>> ",".join(["a", "b", "c"])
'a,b,c'

The "," is inserted between each element of the given list. In your case, your "list" is the string representation "595", which is treated as the list ["5", "9", "5"].

It appears that you're looking for + instead:

print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid

MongoError: connect ECONNREFUSED 127.0.0.1:27017

I had the same error because i had not installed mongoDB. Make sure that you have mongodb installed and if not, you can download it from here https://www.mongodb.com/download-center/community

Ansible date variable

The lookup module of ansible works fine for me. The yml is:

- hosts: test
  vars:
    time: "{{ lookup('pipe', 'date -d \"1 day ago\" +\"%Y%m%d\"') }}"

You can replace any command with date to get result of the command.

Difference between getAttribute() and getParameter()

from http://www.coderanch.com/t/361868/Servlets/java/request-getParameter-request-getAttribute

A "parameter" is a name/value pair sent from the client to the server - typically, from an HTML form. Parameters can only have String values. Sometimes (e.g. using a GET request) you will see these encoded directly into the URL (after the ?, each in the form name=value, and each pair separated by an &). Other times, they are included in the body of the request, when using methods such as POST.

An "attribute" is a server-local storage mechanism - nothing stored in scoped attribues is ever transmitted outside the server unless you explicitly make that happen. Attributes have String names, but store Object values. Note that attributes are specific to Java (they store Java Objects), while parameters are platform-independent (they are only formatted strings composed of generic bytes).

There are four scopes of attributes in total: "page" (for JSPs and tag files only), "request" (limited to the current client's request, destroyed after request is completed), "session" (stored in the client's session, invalidated after the session is terminated), "application" (exist for all components to access during the entire deployed lifetime of your application).

The bottom line is: use parameters when obtaining data from the client, use scoped attributes when storing objects on the server for use internally by your application only.

When is TCP option SO_LINGER (0) required?

The typical reason to set a SO_LINGER timeout of zero is to avoid large numbers of connections sitting in the TIME_WAIT state, tying up all the available resources on a server.

When a TCP connection is closed cleanly, the end that initiated the close ("active close") ends up with the connection sitting in TIME_WAIT for several minutes. So if your protocol is one where the server initiates the connection close, and involves very large numbers of short-lived connections, then it might be susceptible to this problem.

This isn't a good idea, though - TIME_WAIT exists for a reason (to ensure that stray packets from old connections don't interfere with new connections). It's a better idea to redesign your protocol to one where the client initiates the connection close, if possible.

How can you check for a #hash in a URL using JavaScript?

Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although window.location instanceof Location is true, any attempt to invoke Location will tell you that it's an illegal constructor. You can still get to things like hash, query, protocol etc by setting your string as the href property of a DOM anchor element, which will then share all the address properties with window.location.

Simplest way of doing this is:

var a = document.createElement('a');
a.href = string;

string.hash;

For convenience, I wrote a little library that utilises this to replace the native Location constructor with one that will take strings and produce window.location-like objects: Location.js

Taskkill /f doesn't kill a process

Running as an admin works for me:

1.search cmd in windows

2.right click on cmd select as "Run as administrator"

3.netstat -ano | findstr :8080

4.taskkill/pid (your number) /F

My result

Open button in new window?

I couldn't get your method to work @Damien-at-SF...

So I resorted to my old knowledge.

By encasing the input type="button" within a hyperlink element, you can simply declare the target property as so:

<a href="http://www.site.org" target="_blank">
<input type="button" class="button" value="Open" />
</a>

The 'target="_blank"' is the property which makes the browser open the link within a new tab. This attribute has other properties, See: http://www.w3schools.com/tags/att_a_target.asp for further details.

Since the 'value=""' attribute on buttons will write the contained string to the button, a span is not necessary.

Instead of writing:

<element></element>

for most HTML elements you can simply close them with a trailing slash, like so:

<element />

Oh, and finally... a 'button' element has a refresh trigger within it, so I use an 'input type[button]' to avoid triggering the form.

Good Luck Programmers.

Due to StackOverflow's policy I had to change the domain in the example: https://meta.stackexchange.com/questions/208963/why-are-certain-example-urls-like-http-site-com-and-http-mysite-com-blocke

How can I use getSystemService in a non-activity class (LocationManager)?

You need to pass your context to your fyl class..
One solution is make a constructor like this for your fyl class:

public class fyl {
 Context mContext;
 public fyl(Context mContext) {
       this.mContext = mContext;
 }

 public Location getLocation() {
       --
       locationManager = (LocationManager)mContext.getSystemService(context);

       --
 }
}

So in your activity class create the object of fyl in onCreate function like this:

package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;

public class lmt extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        fyl lfyl = new fyl(this); //Here the context is passing 

        Location location = lfyl.getLocation();
        String latLongString = lfyl.updateWithNewLocation(location);

        TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
        myLocationText.setText("Your current position is:\n" + latLongString);
    }
}

Why is using onClick() in HTML a bad practice?

  • onclick events run in the global scope and may cause unexpected error.
  • Adding onclick events to many DOM elements will slow down the
    performance and efficiency.

How to change the button color when it is active using bootstrap?

CSS has many pseudo selector like, :active, :hover, :focus, so you can use.

Html

<div class="col-sm-12" id="my_styles">
     <button type="submit" class="btn btn-warning" id="1">Button1</button>
     <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css

.btn{
    background: #ccc;
} .btn:focus{
    background: red;
}

JsFiddle

Default string initialization: NULL or Empty?

For most software that isn't actually string-processing software, program logic ought not to depend on the content of string variables. Whenever I see something like this in a program:

if (s == "value")

I get a bad feeling. Why is there a string literal in this method? What's setting s? Does it know that logic depends on the value of the string? Does it know that it has to be lower case to work? Should I be fixing this by changing it to use String.Compare? Should I be creating an Enum and parsing into it?

From this perspective, one gets to a philosophy of code that's pretty simple: you avoid examining a string's contents wherever possible. Comparing a string to String.Empty is really just a special case of comparing it to a literal: it's something to avoid doing unless you really have to.

Knowing this, I don't blink when I see something like this in our code base:

string msg = Validate(item);
if (msg != null)
{
   DisplayErrorMessage(msg);
   return;
}

I know that Validate would never return String.Empty, because we write better code than that.

Of course, the rest of the world doesn't work like this. When your program is dealing with user input, databases, files, and so on, you have to account for other philosophies. There, it's the job of your code to impose order on chaos. Part of that order is knowing when an empty string should mean String.Empty and when it should mean null.

(Just to make sure I wasn't talking out of my ass, I just searched our codebase for `String.IsNullOrEmpty'. All 54 occurrences of it are in methods that process user input, return values from Python scripts, examine values retrieved from external APIs, etc.)

CSS Font Border?

I created a comparison of all the solutions mentioned here to have a quick overview:

<h1>with mixin</h1>
<h2>with text-shadow</h2>
<h3>with css text-stroke-width</h3>

https://codepen.io/Grienauer/pen/GRRdRJr

React js change child component's state from parent component

You can use the createRef to change the state of the child component from the parent component. Here are all the steps.

  1. Create a method to change the state in the child component.

    2 - Create a reference for the child component in parent component using React.createRef().

    3 - Attach reference with the child component using ref={}.

    4 - Call the child component method using this.yor-reference.current.method.

Parent component


class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
  render() {
    return (
      <div>
        <button onClick={this.changeChild.current.toggleMenu()}>
          Toggle Menu from Parent
        </button>
        <ChildComponent ref={this.changeChild} />
      </div>
    );
  }
}

Child Component


class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false;
    }
  }

  toggleMenu=() => {
    this.setState({
      open: !this.state.open
    });
  }

  render() {
    return (
      <Drawer open={this.state.open}/>
    );
  }
}



How do I show a running clock in Excel?

See the below code (taken from this post)

Put this code in a Module in VBA (Developer Tab -> Visual Basic)

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub
Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
    TimerActive = False
End Sub
Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
    End If
End Sub

You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.

Private Sub Workbook_Open()
    Module1.StartTimer
End Sub

Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.

How can I keep my branch up to date with master with git?

If your branch is local only and hasn't been pushed to the server, use

git rebase master

Otherwise, use

git merge master

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

$('input[type="text"]').keyup(function(evt){
    var txt = $(this).val();


    // Regex taken from php.js (http://phpjs.org/functions/ucwords:569)
    $(this).val(txt.replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCase( ); }));
});

How to post query parameters with Axios?

In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.

        var data = {};

        const params = new URLSearchParams({
          contact: this.ContactPerson,
          phoneNumber: this.PhoneNumber,
          email: this.Email
        }).toString();

        const url =
          "https://test.com/api/UpdateProfile?" +
          params;

        axios
          .post(url, data, {
            headers: {
              aaid: this.ID,
              token: this.Token
            }
          })
          .then(res => {
            this.Info = JSON.parse(res.data);
          })
          .catch(err => {
            console.log(err);
          });

What are libtool's .la file for?

I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html

Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

It is explained here http://erabhinavrana.blogspot.in/2014/01/how-to-execute-update-query-by-applying.html

It also has other useful code snippets which are commonly used.

update <dbname of 1st table>.<table name of 1st table> A INNER JOIN <dbname of 2nd table>.<table name of 2nd table> RA ON A.<field name of table 1>=RA.<field name of table 2> SET A.<field name of table 1 to be updated>=RA.<field name of table 2 to set value in table 1>

Replace data in <> with your appropriate values.

That's It. source:

http://www.dynamic-coders.com/how-to-update-two-different-tables-in-different-databases-on-same-server

How to find whether a ResultSet is empty or not in Java?

Do this using rs.next():

while (rs.next())
{
    ...
}

If the result set is empty, the code inside the loop won't execute.

How to make CSS width to fill parent?

Use the styles

left: 0px;

or/and

right: 0px;

or/and

top: 0px;

or/and

bottom: 0px;

I think for most cases that will do the job

What is the technology behind wechat, whatsapp and other messenger apps?

The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.

Here is the general explanation from the link

  • WhatsApp server is almost completely implemented in Erlang.

  • Server systems that do the backend message routing are done in Erlang.

  • Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.

  • Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.

  • WhatsApp server has started from ejabberd

  • Ejabberd is a famous open source Jabber server written in Erlang.

  • Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.

  • The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.

  • To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.

  • A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.

  • Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).

  • Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.

  • What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message

  • How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.

Cron job every three days

I am not a cron specialist, but how about:

0 */72 * * *

It will run every 72 hours non-interrupted.

https://crontab.guru/#0_/72___

How to find the statistical mode?

Adding in raster::modal() as an option, although note that raster is a hefty package and may not be worth installing if you don't do geospatial work.

The source code could be pulled out of https://github.com/rspatial/raster/blob/master/src/modal.cpp and https://github.com/rspatial/raster/blob/master/R/modal.R into a personal R package, for those who are particularly keen.

Angular2 - TypeScript : Increment a number after timeout in AppComponent

This is not valid TypeScript code. You can not have method invocations in the body of a class.

// INVALID CODE
export class AppComponent {
  public n: number = 1;
  setTimeout(function() {
    n = n + 10;
  }, 1000);
}

Instead move the setTimeout call to the constructor of the class. Additionally, use the arrow function => to gain access to this.

export class AppComponent {
  public n: number = 1;

  constructor() {
    setTimeout(() => {
      this.n = this.n + 10;
    }, 1000);
  }

}

In TypeScript, you can only refer to class properties or methods via this. That's why the arrow function => is important.

How to set ssh timeout?

You could also connect with flag

-o ServerAliveInterval=<secs>
so the SSH client will send a null packet to the server each <secs> seconds, just to keep the connection alive. In Linux this could be also set globally in /etc/ssh/ssh_config or per-user in ~/.ssh/config.

How do I get LaTeX to hyphenate a word that contains a dash?

From https://texfaq.org/FAQ-nohyph:

TeX won’t hyphenate a word that’s already been hyphenated. For example, the (caricature) English surname Smyth-Postlethwaite wouldn’t hyphenate, which could be troublesome. This is correct English typesetting style (it may not be correct for other languages), but if needs must, you can replace the hyphen in the name with a \hyph command, defined

 \def\hyph{-\penalty0\hskip0pt\relax}

This is not the sort of thing this FAQ would ordinarily recommend… The hyphenat package defines a bundle of such commands (for introducing hyphenation points at various punctuation characters).


Or you could \newcommand a command that expands to multi-discipli\-nary (use Search + Replace All to replace existing words).

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

Android Studio - debug keystore

If you use Windows, you will found it follow this: File-->Project Structure-->Facets

chose your Android project and in the "Facet 'Android'" window click TAB "Packaging",you will found what you want

Pass C# ASP.NET array to Javascript array

Simple

The array of integers is quite simple to pass. However this solution works for more complex data as well. In your model:

public int[] Numbers => new int[5];

In your view:

numbers = @(new HtmlString(JsonSerializer.Serialize(Model.Numbers)))

Optional

A tip for passing strings. You may want JSON encoder to not escape some symbols in your strings. In this example I want raw unescaped cyrillic letters. In your view:

strings = @(
new HtmlString(
    JsonSerializer.Serialize(Model.Strings, new JsonSerializerOptions
    {
        Encoder = JavaScriptEncoder.Create(
            UnicodeRanges.BasicLatin,
            UnicodeRanges.Cyrillic)
    })))

Why is lock(this) {...} bad?

Here's a much simpler illustration (taken from Question 34 here) why lock(this) is bad and may result in deadlocks when consumer of your class also try to lock on the object. Below, only one of three thread can proceed, the other two are deadlocked.

class SomeClass
{
    public void SomeMethod(int id)
    {
        **lock(this)**
        {
            while(true)
            {
                Console.WriteLine("SomeClass.SomeMethod #" + id);
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        SomeClass o = new SomeClass();

        lock(o)
        {
            for (int threadId = 0; threadId < 3; threadId++)
            {
                Thread t = new Thread(() => {
                    o.SomeMethod(threadId);
                        });
                t.Start();
            }

            Console.WriteLine();
        }

To work around, this guy used Thread.TryMonitor (with timeout) instead of lock:

            Monitor.TryEnter(temp, millisecondsTimeout, ref lockWasTaken);
            if (lockWasTaken)
            {
                doAction();
            }
            else
            {
                throw new Exception("Could not get lock");
            }

https://blogs.appbeat.io/post/c-how-to-lock-without-deadlocks

Use jQuery to get the file input's selected filename without the path

Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.

To get just the filename portion of a string, you can use split()...

var file = path.split('\\').pop();

jsFiddle.

...or a regular expression...

var file = path.match(/\\([^\\]+)$/)[1];

jsFiddle.

...or lastIndexOf()...

var file = path.substr(path.lastIndexOf('\\') + 1);

jsFiddle.

Get IPv4 addresses from Dns.GetHostEntry()

    public static string GetIPAddress(string hostname)
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(hostname);

        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                //System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip);
                return ip.ToString();
            }
        }
        return string.Empty;
    }

How to split a dataframe string column into two columns?

You can use str.split by whitespace (default separator) and parameter expand=True for DataFrame with assign to new columns:

df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA', 
                           '01001 Autauga County, AL', '01003 Baldwin County, AL', 
                           '01005 Barbour County, AL']})
print (df)
                        row
0       00000 UNITED STATES
1             01000 ALABAMA
2  01001 Autauga County, AL
3  01003 Baldwin County, AL
4  01005 Barbour County, AL



df[['a','b']] = df['row'].str.split(n=1, expand=True)
print (df)
                        row      a                   b
0       00000 UNITED STATES  00000       UNITED STATES
1             01000 ALABAMA  01000             ALABAMA
2  01001 Autauga County, AL  01001  Autauga County, AL
3  01003 Baldwin County, AL  01003  Baldwin County, AL
4  01005 Barbour County, AL  01005  Barbour County, AL

Modification if need remove original column with DataFrame.pop

df[['a','b']] = df.pop('row').str.split(n=1, expand=True)
print (df)
       a                   b
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

What is same like:

df[['a','b']] = df['row'].str.split(n=1, expand=True)
df = df.drop('row', axis=1)
print (df)

       a                   b
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

If get error:

#remove n=1 for split by all whitespaces
df[['a','b']] = df['row'].str.split(expand=True)

ValueError: Columns must be same length as key

You can check and it return 4 column DataFrame, not only 2:

print (df['row'].str.split(expand=True))
       0        1        2     3
0  00000   UNITED   STATES  None
1  01000  ALABAMA     None  None
2  01001  Autauga  County,    AL
3  01003  Baldwin  County,    AL
4  01005  Barbour  County,    AL

Then solution is append new DataFrame by join:

df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA', 
                           '01001 Autauga County, AL', '01003 Baldwin County, AL', 
                           '01005 Barbour County, AL'],
                    'a':range(5)})
print (df)
   a                       row
0  0       00000 UNITED STATES
1  1             01000 ALABAMA
2  2  01001 Autauga County, AL
3  3  01003 Baldwin County, AL
4  4  01005 Barbour County, AL

df = df.join(df['row'].str.split(expand=True))
print (df)

   a                       row      0        1        2     3
0  0       00000 UNITED STATES  00000   UNITED   STATES  None
1  1             01000 ALABAMA  01000  ALABAMA     None  None
2  2  01001 Autauga County, AL  01001  Autauga  County,    AL
3  3  01003 Baldwin County, AL  01003  Baldwin  County,    AL
4  4  01005 Barbour County, AL  01005  Barbour  County,    AL

With remove original column (if there are also another columns):

df = df.join(df.pop('row').str.split(expand=True))
print (df)
   a      0        1        2     3
0  0  00000   UNITED   STATES  None
1  1  01000  ALABAMA     None  None
2  2  01001  Autauga  County,    AL
3  3  01003  Baldwin  County,    AL
4  4  01005  Barbour  County,    AL   

Automatically pass $event with ng-click?

As others said, you can't actually strictly do what you are asking for. That said, all of the tools available to the angular framework are actually available to you as well! What that means is you can actually write your own elements and provide this feature yourself. I wrote one of these up as an example which you can see at the following plunkr (http://plnkr.co/edit/Qrz9zFjc7Ud6KQoNMEI1).

The key parts of this are that I define a "clickable" element (don't do this if you need older IE support). In code that looks like:

<clickable>
  <h1>Hello World!</h1>
</clickable>

Then I defined a directive to take this clickable element and turn it into what I want (something that automatically sets up my click event):

app.directive('clickable', function() {
    return {
        transclude: true,
        restrict: 'E',
        template: '<div ng-transclude ng-click="handleClick($event)"></div>'
    };
});

Finally in my controller I have the click event ready to go:

$scope.handleClick = function($event) {
    var i = 0;
};

Now, its worth stating that this hard codes the name of the method that handles the click event. If you wanted to eliminate this, you should be able to provide the directive with the name of your click handler and "tada" - you have an element (or attribute) that you can use and never have to inject "$event" again.

Hope that helps!

Threading pool similar to the multiprocessing Pool?

The overhead of creating the new processes is minimal, especially when it's just 4 of them. I doubt this is a performance hot spot of your application. Keep it simple, optimize where you have to and where profiling results point to.

How to split the screen with two equal LinearLayouts?

I am answering this question after 4-5 years but best practices to do this as below

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

   <LinearLayout
      android:id="@+id/firstLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_toLeftOf="@+id/secondView"
      android:orientation="vertical"></LinearLayout>

   <View
      android:id="@+id/secondView"
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_centerHorizontal="true" />

   <LinearLayout
      android:id="@+id/thirdLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_toRightOf="@+id/secondView"
      android:orientation="vertical"></LinearLayout>
</RelativeLayout>

This is right approach as use of layout_weight is always heavy for UI operations. Splitting Layout equally using LinearLayout is not good practice

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

Running Python on Windows for Node.js dependencies

Example : pg_config not executable / error node-gyp

Solution : On windows just try to add PATH Env -> C:\Program Files\PostgreSQL\12\bin

Work for me, Now i can use npm i pg-promise for example or other dependencies.

How to determine when a Git branch was created?

If you want to get the details for all the branches

for i in `git branch -r | tail -n +2 `;do git log --reverse $i|grep -A 2 -B 2 `echo $i | awk -F'origin/' '{print $2}'` |head -n 4; done

maven error: package org.junit does not exist

Ok, you've declared junit dependency for test classes only (those that are in src/test/java but you're trying to use it in main classes (those that are in src/main/java).

Either do not use it in main classes, or remove <scope>test</scope>.

Need help rounding to 2 decimal places

The System.Math.Round method uses the Double structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:

Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)

Result: 0.58

UDP vs TCP, how much faster is it?

The network setup is crucial for any measurements. It makes a huge difference, if you are communicating via sockets on your local machine or with the other end of the world.

Three things I want to add to the discussion:

  1. You can find here a very good article about TCP vs. UDP in the context of game development.
  2. Additionally, iperf (jperf enhance iperf with a GUI) is a very nice tool for answering your question yourself by measuring.
  3. I implemented a benchmark in Python (see this SO question). In average of 10^6 iterations the difference for sending 8 bytes is about 1-2 microseconds for UDP.

How to change the CHARACTER SET (and COLLATION) throughout a database?

here describes the process well. However, some of the characters that didn't fit in latin space are gone forever. UTF-8 is a SUPERSET of latin1. Not the reverse. Most will fit in single byte space, but any undefined ones will not (check a list of latin1 - not all 256 characters are defined, depending on mysql's latin1 definition)

Error: getaddrinfo ENOTFOUND in nodejs for get call

var http = require('http');

  var options = {     
      host: 'localhost',
      port: 80,
      path: '/broadcast'
    };

  var requestLoop = setInterval(function(){

      http.get (options, function (resp) {
        resp.on('data', function (d) {
          console.log ('data!', d.toString());
        });
        resp.on('end', function (d) {
           console.log ('Finished !');
        });
      }).on('error', function (e) {
          console.log ('error:', e);
      });
  }, 10000);

var dns = require('dns'), cache = {};
dns._lookup = dns.lookup;
dns.lookup = function(domain, family, done) {
    if (!done) {
        done = family;
        family = null;
    }

    var key = domain+family;
    if (key in cache) {
        var ip = cache[key],
            ipv = ip.indexOf('.') !== -1 ? 4 : 6;

        return process.nextTick(function() {
            done(null, ip, ipv);
        });
    }

    dns._lookup(domain, family, function(err, ip, ipv) {
        if (err) return done(err);
        cache[key] = ip;
        done(null, ip, ipv);
    });
};

// Works fine (100%)

Print JSON parsed object?

try console.dir() instead of console.log()

console.dir(obj);

MDN says console.dir() is supported by:

  • FF8+
  • IE9+
  • Opera
  • Chrome
  • Safari

C++ - how to find the length of an integer

Would this be an efficient approach? Converting to a string and finding the length property?

int num = 123  
string strNum = to_string(num); // 123 becomes "123"
int length = strNum.length(); // length = 3
char array[3]; // or whatever you want to do with the length

Check if a div exists with jquery

As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true in if-statements. And because of that, the third method is incorrect.

How to create a file in a directory in java?

You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().

File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...

Is there a simple way to convert C++ enum to string?

That's pretty much the only way it can be done (an array of string could work also).

The problem is, once a C program is compiled, the binary value of the enum is all that is used, and the name is gone.

MySql Error: 1364 Field 'display_name' doesn't have default value

Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:

public function up()
{

    Schema::create('trip_table', function (Blueprint $table) {
        $table->increments('trip_id')->unsigned();
        $table->time('est_start');
        $table->time('est_end');
        $table->time('act_start')->nullable();
        $table->time('act_end')->nullable();
        $table->date('Trip_Date');
        $table->integer('Starting_Miles')->nullable();
        $table->integer('Ending_Miles')->nullable();
        $table->string('Bus_id')->nullable();
        $table->string('Event');
        $table->string('Desc')->nullable();
        $table->string('Destination');
        $table->string('Departure_location');
        $table->text('Drivers_Comment')->nullable();
        $table->string('Requester')->nullable();
        $table->integer('driver_id')->nullable();
        $table->timestamps();
    });

}

The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!

Laravel, sync() - how to sync an array and also pass additional pivot fields?

This works for me

foreach ($photos_array as $photo) {

    //collect all inserted record IDs
    $photo_id_array[$photo->id] = ['type' => 'Offence'];  

}

//Insert into offence_photo table
$offence->photos()->sync($photo_id_array, false);//dont delete old entries = false

How to concatenate text from multiple rows into a single text string in SQL server?

This can be useful too

create table #test (id int,name varchar(10))
--use separate inserts on older versions of SQL Server
insert into #test values (1,'Peter'), (1,'Paul'), (1,'Mary'), (2,'Alex'), (3,'Jack')

DECLARE @t VARCHAR(255)
SELECT @t = ISNULL(@t + ',' + name, name) FROM #test WHERE id = 1
select @t
drop table #test

returns

Peter,Paul,Mary

How do I change the value of a global variable inside of a function

Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.

You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.

That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.

MySQL Sum() multiple columns

//Mysql sum of multiple rows Hi Here is the simple way to do sum of columns

SELECT sum(IF(day_1 = 1,1,0)+IF(day_3 = 1,1,0)++IF(day_4 = 1,1,0)) from attendence WHERE class_period_id='1' and student_id='1'

Unix: How to delete files listed in a file

xargs -I{} sh -c 'rm {}' < 1.txt should do what you want. Be careful with this command as one incorrect entry in that file could cause a lot of trouble.

This answer was edited after @tdavies pointed out that the original did not do shell expansion.

Play/pause HTML 5 video using JQuery

I use FancyBox and jQuery to embedd a video. Give it an ID.

Perhaps not the BEST solution could toggle play/pause differently - but easy for me and IT WORKS! :)

In the

`

<input type="hidden" id="current_video_playing">

<input type="hidden" id="current_video_status" value="playing">

<video id="video-1523" autobuffer="false" src="movie.mp4"></video>

<script>

// Play Pause with spacebar

$(document).keypress(function(e) { 

    theVideo = document.getElementById('current_video_playing').value

    if (e.which == 32) {

        if (document.getElementById('current_video_status').value == 'playing') {

            document.getElementById(theVideo).pause();

            document.getElementById('current_video_status').value = 'paused'

        } else {

            document.getElementById('current_video_status').value = 'playing'

            document.getElementById(theVideo).play();

        }

    }

});

</script>`

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)

But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver. Just build your JDBC URL like this:

jdbc:sqlserver://localhost;integratedSecurity=true;

And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver)

MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL

Play audio with Python

If you're on OSX, you can use the "os" module or "subprocess" etc. to call the OSX "play" command. From the OSX shell, it looks like

play "bah.wav"

It starts to play in about a half-second on my machine.

How To Check If A Key in **kwargs Exists?

DSM's and Tadeck's answers answer your question directly.

In my scripts I often use the convenient dict.pop() to deal with optional, and additional arguments. Here's an example of a simple print() wrapper:

def my_print(*args, **kwargs):
    prefix = kwargs.pop('prefix', '')
    print(prefix, *args, **kwargs)

Then:

>>> my_print('eggs')
 eggs
>>> my_print('eggs', prefix='spam')
spam eggs

As you can see, if prefix is not contained in kwargs, then the default '' (empty string) is being stored in the local prefix variable. If it is given, then its value is being used.

This is generally a compact and readable recipe for writing wrappers for any kind of function: Always just pass-through arguments you don't understand, and don't even know if they exist. If you always pass through *args and **kwargs you make your code slower, and requires a bit more typing, but if interfaces of the called function (in this case print) changes, you don't need to change your code. This approach reduces development time while supporting all interface changes.

Redirect to a page/URL after alert button is pressed

if (window.confirm('Really go to another page?'))
{
    alert('message');
    window.location = '/some/url';
}
else
{
    die();
}

Transaction marked as rollback only: How do I find the cause

I finally understood the problem:

methodA() {
    methodB()
}

@Transactional(noRollbackFor = Exception.class)
methodB() {
    ...
    try {
        methodC()
    } catch (...) {...}
    log("OK");
}

@Transactional
methodC() {
    throw new ...();
}

What happens is that even though the methodB has the right annotation, the methodC does not. When the exception is thrown, the second @Transactional marks the first transaction as Rollback only anyway.

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give each input a name attribute. Only the clicked input's name attribute will be sent to the server.

<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">

And then

<?php
    if (isset($_POST['publish'])) {
        # Publish-button was clicked
    }
    elseif (isset($_POST['save'])) {
        # Save-button was clicked
    }
?>

Edit: Changed value attributes to alt. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]?

Edit: Since this keeps getting upvotes I went ahead and changed the weird alt/value code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image].

UEFA/FIFA scores API

UEFA internally provides their own LIVEX Api for their Broadcasting Partners. That one is perfect enough to develop the Applications by their partners for themselves.

Creating an Array from a Range in VBA

Just define the variable as a variant, and make them equal:

Dim DirArray As Variant
DirArray = Range("a1:a5").Value

No need for the Array command.

CodeIgniter: How to use WHERE clause and OR clause

$where = "name='Joe' AND status='boss' OR status='active'";

$this->db->where($where);

Though I am 3/4 of a month late, you still execute the following after your where clauses are defined... $this->db->get("tbl_name");

Generate sha256 with OpenSSL and C++

Here's how I did it:

void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])
{
    int i = 0;

    for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }

    outputBuffer[64] = 0;
}


void sha256_string(char *string, char outputBuffer[65])
{
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, string, strlen(string));
    SHA256_Final(hash, &sha256);
    int i = 0;
    for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }
    outputBuffer[64] = 0;
}

int sha256_file(char *path, char outputBuffer[65])
{
    FILE *file = fopen(path, "rb");
    if(!file) return -534;

    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    const int bufSize = 32768;
    unsigned char *buffer = malloc(bufSize);
    int bytesRead = 0;
    if(!buffer) return ENOMEM;
    while((bytesRead = fread(buffer, 1, bufSize, file)))
    {
        SHA256_Update(&sha256, buffer, bytesRead);
    }
    SHA256_Final(hash, &sha256);

    sha256_hash_string(hash, outputBuffer);
    fclose(file);
    free(buffer);
    return 0;
}

It's called like this:

static unsigned char buffer[65];
sha256("string", buffer);
printf("%s\n", buffer);

Copy file remotely with PowerShell

None of the above answers worked for me. I kept getting this error:

Copy-Item : Access is denied
+ CategoryInfo          : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>   
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand

So this did it for me:

netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes

Then from my host my machine in the Run box I just did this:

\\{IP address of nanoserver}\C$

Manually type in a value in a "Select" / Drop-down HTML list?

I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.

The good news is that selectize.js does exactly this:

Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.

How to show full height background image?

 html, body {
    height:100%;
}

body { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

"rm -rf" equivalent for Windows?

Try this command:

del /s foldername

Linux command: How to 'find' only text files?

How about this:

$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable'

If you want the filenames without the file types, just add a final sed filter.

$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'

You can filter-out unneeded file types by adding more -e 'type' options to the last grep command.

EDIT:

If your xargs version supports the -d option, the commands above become simpler:

$ grep -rl "needle text" my_folder | xargs -d '\n' -r file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'

Iterate Multi-Dimensional Array with Nested Foreach Statement

Use LINQ .Cast<int>() to convert 2D array to IEnumerable<int>.

LINQPad example:

var arr = new int[,] { 
  { 1, 2, 3 }, 
  { 4, 5, 6 } 
};

IEnumerable<int> values = arr.Cast<int>();
Console.WriteLine(values);

Output:

Sequence is 1,2,3,4,5,6

How to access route, post, get etc. parameters in Zend Framework 2

If You have no access to plugin for instance outside of controller You can get params from servicelocator like this

//from POST
$foo = $this->serviceLocator->get('request')->getPost('foo'); 
//from GET
$foo = $this->serviceLocator->get('request')->getQuery()->foo;
//from route
$foo = $this->serviceLocator->get('application')->getMvcEvent()->getRouteMatch()->getParam('foo');

Default value in Go's method

NO,but there are some other options to implement default value. There are some good blog posts on the subject, but here are some specific examples.


**Option 1:** The caller chooses to use default values
// Both parameters are optional, use empty string for default value
func Concat1(a string, b int) string {
  if a == "" {
    a = "default-a"
  }
  if b == 0 {
    b = 5
  }

  return fmt.Sprintf("%s%d", a, b)
}

**Option 2:** A single optional parameter at the end
// a is required, b is optional.
// Only the first value in b_optional will be used.
func Concat2(a string, b_optional ...int) string {
  b := 5
  if len(b_optional) > 0 {
    b = b_optional[0]
  }

  return fmt.Sprintf("%s%d", a, b)
}

**Option 3:** A config struct
// A declarative default value syntax
// Empty values will be replaced with defaults
type Parameters struct {
  A string `default:"default-a"` // this only works with strings
  B string // default is 5
}

func Concat3(prm Parameters) string {
  typ := reflect.TypeOf(prm)

  if prm.A == "" {
    f, _ := typ.FieldByName("A")
    prm.A = f.Tag.Get("default")
  }

  if prm.B == 0 {
    prm.B = 5
  }

  return fmt.Sprintf("%s%d", prm.A, prm.B)
}

**Option 4:** Full variadic argument parsing (javascript style)
func Concat4(args ...interface{}) string {
  a := "default-a"
  b := 5

  for _, arg := range args {
    switch t := arg.(type) {
      case string:
        a = t
      case int:
        b = t
      default:
        panic("Unknown argument")
    }
  }

  return fmt.Sprintf("%s%d", a, b)
}

Getting unique items from a list

Use a HashSet<T>. For example:

var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
    Console.WriteLine(s);

prints

A
B
D
C

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

Do aman 2 sendfile. You only need to open the source file on the client and destination file on the server, then call sendfile and the kernel will chop and move the data.

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

Best way to store a key=>value array in JavaScript?

You can use Map.

  • A new data structure introduced in JavaScript ES6.
  • Alternative to JavaScript Object for storing key/value pairs.
  • Has useful methods for iteration over the key/value pairs.
var map = new Map();
map.set('name', 'John');
map.set('id', 11);

// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }

Get value of the Map using key

console.log(map.get('name')); // John 
console.log(map.get('id')); // 11

Get size of the Map

console.log(map.size); // 2

Check key exists in Map

console.log(map.has('name')); // true
console.log(map.has('age')); // false

Get keys

console.log(map.keys()); // MapIterator { 'name', 'id' }

Get values

console.log(map.values()); // MapIterator { 'John', 11 }

Get elements of the Map

for (let element of map) {
  console.log(element);
}

// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]

Print key value pairs

for (let [key, value] of map) {
  console.log(key + " - " + value);
}

// Output: 
// name - John
// id - 11

Print only keys of the Map

for (let key of map.keys()) {
  console.log(key);
}

// Output:
// name
// id

Print only values of the Map

for (let value of map.values()) {
  console.log(value);
}

// Output:
// John
// 11

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

Go to IIS -> Application Pool -> Advance Settings -> Enable 32-bit Applications

What is the T-SQL syntax to connect to another SQL Server?

on my C drive I first create a txt file to create a new table. You can use what ever you want in this text file

in this case the text file is called "Bedrijf.txt"

the content:

Print 'START(A) create table'

GO 1

If not EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME = 'Bedrijf'
)
BEGIN
CREATE TABLE [dbo].[Bedrijf] (
[IDBedrijf] [varchar] (38)   NOT NULL ,
[logo] [varbinary] (max) NULL ,
[VolledigeHandelsnaam] [varchar] (100)  NULL 
) ON [PRIMARY]

save it

then I create an other txt file with the name "Bedrijf.bat" and the extension bat. It's content:

OSQL.EXE  -U Username -P Password -S IPaddress -i C:Bedrijf.txt -o C:Bedrijf.out -d myDatabaseName

save it and from explorer double click to execute

The results will be saved in a txt file on your C drive with the name "Bedrijf.out"

it shows

1> 2> 3> START(A) create table

if all goes well

That's it

Codeigniter $this->db->get(), how do I return values for a specific row?

SOLUTION ONE

$this->db->where('id', '3');
// here we select every column of the table
$q = $this->db->get('my_users_table');
$data = $q->result_array();

echo($data[0]['age']);

SOLUTION TWO

// here we select just the age column
$this->db->select('age');
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
$data = $q->result_array();

echo($data[0]['age']);

SOLUTION THREE

$this->db->select('age');
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
// if id is unique, we want to return just one row
$data = array_shift($q->result_array());

echo($data['age']);

SOLUTION FOUR (NO ACTIVE RECORD)

$q = $this->db->query('SELECT age FROM my_users_table WHERE id = ?',array(3));
$data = array_shift($q->result_array());
echo($data['age']);

Java collections convert a string to a list of characters

IntStream can be used to access each character and add them to the list.

String str = "abc";
List<Character> charList = new ArrayList<>();
IntStream.range(0,str.length()).forEach(i -> charList.add(str.charAt(i)));