Programs & Examples On #Dataguard

How do I make a branch point at a specific commit?

If you are currently not on branch master, that's super easy:

git branch -f master 1258f0d0aae

This does exactly what you want: It points master at the given commit, and does nothing else.

If you are currently on master, you need to get into detached head state first. I'd recommend the following two command sequence:

git checkout 1258f0d0aae    #detach from master
git branch -f master HEAD   #exactly as above

#optionally reattach to master
git checkout master

Be aware, though, that any explicit manipulation of where a branch points has the potential to leave behind commits that are no longer reachable by any branches, and thus become object to garbage collection. So, think before you type git branch -f!


This method is better than the git reset --hard approach, as it does not destroy anything in the index or working directory.

error: Your local changes to the following files would be overwritten by checkout

i had got the same error. Actually i tried to override the flutter Old SDK Package with new Updated Package. so that error occurred.

i opened flutter sdk directory with VS Code and cleaned the project

use this code in VSCode cmd

git clean -dxf

then use git pull

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

Google Maps API v3 marker with label

I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.

 .labels {
   color: red;
   background-color: white;
   font-family: "Lucida Grande", "Arial", sans-serif;
   font-size: 10px;
   font-weight: bold;
   text-align: center;
   width: 60px;     
   border: 2px solid black;
   white-space: nowrap;
 }

JavaScript:

 var marker = new MarkerWithLabel({
   position: homeLatLng,
   draggable: true,
   map: map,
   labelContent: "$425K",
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75}
 });

The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50).

In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|

Ignore case in Python strings

I can't find any other built-in way of doing case-insensitive comparison: The python cook-book recipe uses lower().

However you have to be careful when using lower for comparisons because of the Turkish I problem. Unfortunately Python's handling for Turkish Is is not good. i is converted to I, but I is not converted to i. I is converted to i, but i is not converted to I.

javascript find and remove object in array based on key value

Maybe you are looking for $.grep() function:

arr = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

id = 88;
arr = $.grep(arr, function(data, index) {
   return data.id != id
});

How to specify the port an ASP.NET Core application is hosted on?

You can specify hosting URL without any changes to your app.

Create a Properties/launchSettings.json file in your project directory and fill it with something like this:

{
  "profiles": {
    "MyApp1-Dev": {
        "commandName": "Project",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "applicationUrl": "http://localhost:5001/"
    }
  }
}

dotnet run command should pick your launchSettings.json file and will display it in the console:

C:\ProjectPath [master =]
?  dotnet run
Using launch settings from C:\ProjectPath\Properties\launchSettings.json...
Hosting environment: Development
Content root path: C:\ProjectPath
Now listening on: http://localhost:5001
Application started. Press Ctrl+C to shut down. 

More details: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments

How to change the text color of first select option

For Option 1 used as the placeholder:

select:invalid { color:grey; }

All other options:

select:valid { color:black; }

How to wait for a JavaScript Promise to resolve before resuming function?

I'm wondering if there is any way to get a value from a Promise or wait (block/sleep) until it has resolved, similar to .NET's IAsyncResult.WaitHandle.WaitOne(). I know JavaScript is single-threaded, but I'm hoping that doesn't mean that a function can't yield.

The current generation of Javascript in browsers does not have a wait() or sleep() that allows other things to run. So, you simply can't do what you're asking. Instead, it has async operations that will do their thing and then call you when they're done (as you've been using promises for).

Part of this is because of Javascript's single threadedness. If the single thread is spinning, then no other Javascript can execute until that spinning thread is done. ES6 introduces yield and generators which will allow some cooperative tricks like that, but we're quite a ways from being able to use those in a wide swatch of installed browsers (they can be used in some server-side development where you control the JS engine that is being used).


Careful management of promise-based code can control the order of execution for many async operations.

I'm not sure I understand exactly what order you're trying to achieve in your code, but you could do something like this using your existing kickOff() function, and then attaching a .then() handler to it after calling it:

function kickOff() {
  return new Promise(function(resolve, reject) {
    $("#output").append("start");

    setTimeout(function() {
      resolve();
    }, 1000);
  }).then(function() {
    $("#output").append(" middle");
    return " end";
  });
}

kickOff().then(function(result) {
    // use the result here
    $("#output").append(result);
});

This will return output in a guaranteed order - like this:

start
middle
end

Update in 2018 (three years after this answer was written):

If you either transpile your code or run your code in an environment that supports ES7 features such as async and await, you can now use await to make your code "appear" to wait for the result of a promise. It is still developing with promises. It does still not block all of Javascript, but it does allow you to write sequential operations in a friendlier syntax.

Instead of the ES6 way of doing things:

someFunc().then(someFunc2).then(result => {
    // process result here
}).catch(err => {
    // process error here
});

You can do this:

// returns a promise
async function wrapperFunc() {
    try {
        let r1 = await someFunc();
        let r2 = await someFunc2(r1);
        // now process r2
        return someValue;     // this will be the resolved value of the returned promise
    } catch(e) {
        console.log(e);
        throw e;      // let caller know the promise was rejected with this reason
    }
}

wrapperFunc().then(result => {
    // got final result
}).catch(err => {
    // got error
});

How to get a list column names and datatypes of a table in PostgreSQL?

Open psql command line and type :

\d+ table_name

jquery 3.0 url.indexOf error

@choz answer is the correct way. If you have many usages and want to make sure it works everywhere without changes you can add these small migration-snippet:

/* Migration jQuery from 1.8 to 3.x */
jQuery.fn.load = function (callback) {
    var el = $(this);

    el.on('load', callback);

    return el;
};

In this case you got no erros on other nodes e.g. on $image like in @Korsmakolnikov answer!

const $image = $('img.image').load(function() {
  $(this).doSomething();
});

$image.doSomethingElseWithTheImage();

Laravel 5 PDOException Could Not Find Driver

Same thing happend to me after upgrading distro.

Running sudo apt-get install php7.0-mysql fixed it for me.

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

Please set your form action attribute as below it will solve your problem.

<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">

jQuery code:

$(document).ready(function () {
    $("#addProductForm").submit(function (event) {

        //disable the default form submission
        event.preventDefault();
        //grab all form data  
        var formData = $(this).serialize();

        $.ajax({
            url: 'addProduct.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function () {
                alert('Form Submitted!');
            },
            error: function(){
                alert("error in ajax form submission");
            }
        });

        return false;
    });
});

preventDefault() on an <a> tag

Why not just do it in css?

Take out the 'href' attribute in your anchor tag

<ul class="product-info">
  <li>
    <a>YOU CLICK THIS TO SHOW/HIDE</a>
    <div class="toggle">
      <p>CONTENT TO SHOW/HIDE</p>
    </div>
  </li>
</ul>

In your css,

  a{
    cursor: pointer;
    }

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

TypeError: Router.use() requires middleware function but got a Object

check your routes.js file

example my routes.js

_x000D_
_x000D_
    const express = require('express')_x000D_
    const router = express.Router()_x000D_
    _x000D_
    const usersController = require('../app/controllers/usersController')_x000D_
    const autheticateuser = require('../app/middlewares/authentication')_x000D_
    _x000D_
    router.post('/users/login', autheticateuser, usersController.login)_x000D_
    router.post('/users/register', autheticateuser, usersController.register)_x000D_
      
_x000D_
_x000D_
_x000D_

check end of routes.js

module.exports = router

if not there add and module.exports = router run again


If your Error is : "TypeError: Route.post() or Route.get() requires middleware function but got a Object"

goto controller.js (i.e., usersController) and check all the function names you might misspelled , or you given in function routes file but missed in contollers

_x000D_
_x000D_
const User = require('../models/user')_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
_x000D_
_x000D_
_x000D_
module.exports.register = (req, res) => {_x000D_
    const data = req.body_x000D_
    const user = new User(data)_x000D_
    user.save()_x000D_
        .then((user) => {_x000D_
            res.send(user)_x000D_
        })_x000D_
        .catch((err) => {_x000D_
            res.json(err)_x000D_
        })_x000D_
}
_x000D_
_x000D_
_x000D_

in routes.js i given two routes but in controllers i missed to define route for

router.post('/users/login')

this will make error **

"TypeError: route.post() requires middleware function but got a Object"

**

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

For SDK 29 :

String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}

public static void createTextFile(String sBody, String FileName, String Where) {
    try {
        File gpxfile = new File(Where, FileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then you can save your file like this :

createTextFile("This is Content","file.txt",str1);

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

What's the difference between lists enclosed by square brackets and parentheses in Python?

Another way brackets and parentheses differ is that square brackets can describe a list comprehension, e.g. [x for x in y]

Whereas the corresponding parenthetic syntax specifies a tuple generator: (x for x in y)

You can get a tuple comprehension using: tuple(x for x in y)

See: Why is there no tuple comprehension in Python?

Live video streaming using Java?

Yes if you want to stream live video you can use RTSP protoco this will allow you to create a video file, which can be play while creating, both operation will work simultaneously. RTSP-Client-Server

Android - Spacing between CheckBox and text

Setting minHeight and minWidth to 0dp was the cleanest and directest solution for me on Android 9 API 28:

<CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="0dp"
        android:minWidth="0dp" />

How do I create a singleton service in Angular 2?

In addition to the above excellent answers, there may be something else that is missing if things in your singleton still aren't behaving as a singleton. I ran into the issue when calling a public function on the singleton and finding that it was using the wrong variables. It turns out that the problem was the this isn't guaranteed to be bound to the singleton for any public functions in the singleton. This can be corrected by following the advice here, like so:

@Injectable({
  providedIn: 'root',
})
export class SubscriptableService {
  public serviceRequested: Subject<ServiceArgs>;
  public onServiceRequested$: Observable<ServiceArgs>;

  constructor() {
    this.serviceRequested = new Subject<ServiceArgs>();
    this.onServiceRequested$ = this.serviceRequested.asObservable();

    // save context so the singleton pattern is respected
    this.requestService = this.requestService.bind(this);
  }

  public requestService(arg: ServiceArgs) {
    this.serviceRequested.next(arg);
  }
}

Alternatively, you can simply declare the class members as public static instead of public, then the context won't matter, but you'll have to access them like SubscriptableService.onServiceRequested$ instead of using dependency injection and accessing them via this.subscriptableService.onServiceRequested$.

How to add buttons like refresh and search in ToolBar in Android?

To control the location of the title you may want to set a custom font as explained here (by twaddington): Link

Then to relocate the position of the text, in updateMeasureState() you would add p.baselineShift += (int) (p.ascent() * R); Similarly in updateDrawState() add tp.baselineShift += (int) (tp.ascent() * R); Where R is double between -1 and 1.

Display JSON Data in HTML Table

          <table id="myData">

          </table>

           <script type="text/javascript">
              $('#search').click(function() {
                    alert("submit handler has fired");
                    $.ajax({
                        type: 'POST',
                        url: 'cityResults.htm',
                        data: $('#cityDetails').serialize(),

                        success: function(data){ 
                            $.each(data, function( index, value ) {
                               var row = $("<tr><td>" + value.city + "</td><td>" + value.cStatus + "</td></tr>");
                               $("#myData").append(row);
                            });
                        },
                        error: function(jqXHR, textStatus, errorThrown){
                            alert('error: ' + textStatus + ': ' + errorThrown);
                        }
                    });
                    return false;//suppress natural form submission
                }); 

   </script>

loop through the data and append it to a table like the code above.

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

Convert spark DataFrame column to python list

A possible solution is using the collect_list() function from pyspark.sql.functions. This will aggregate all column values into a pyspark array that is converted into a python list when collected:

mvv_list   = df.select(collect_list("mvv")).collect()[0][0]
count_list = df.select(collect_list("count")).collect()[0][0] 

Make flex items take content width, not width of parent container

Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

Learn more about flex alignment along the main axis here:

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I was getting this on 1.6.2 server, 1.6.8 tortoise. All on Windows, no merges in this branch.

I renamed a directory and somehow (possibly due to AnkhSVN) two of the files within the directory were being marked as "replaced" rather than "normal". There were some additional minor changes to other files within the directory.

Reverting the files marked as replaced fixed the problem.

What is the best way to measure execution time of a function?

Tickcount is good, however i suggest running it 100 or 1000 times, and calculating an average. Not only makes it more measurable - in case of really fast/short functions, but helps dealing with some one-off effects caused by the overhead.

How to store Node.js deployment settings/configuration files?

I know this is a really old post. But I want to share my module for configuring environment variables, I think it is very flexible solution. Here is the module json-configurator

var configJson = {
  'baseUrl': 'http://test.com',
  '$prod_baseUrl': 'https://prod.com',
  'endpoints': {
    'users': '<%= baseUrl %>/users',
    'accounts': '<%= baseUrl %>/accounts'
    },
  foo: 'bar',
  foobar: 'foobar',
  $prod_foo: 'foo in prod',
  $test_foo: 'foo in test',
  deep:{
    veryDeep: {
      publicKey: 'abc',
      secret: 'secret',
      $prod_secret: 'super secret'
    }
  }
};

var config = require('json-configurator')(configJson, 'prod');

console.log(config.deep.veryDeep.secret) 
// super secret 

console.log(config.endpoints.users)
// https://prod.com/users 

Then you can use process.env.NODE_ENV to get all the variables for your environment.

Skip certain tables with mysqldump

for multiple databases:

mysqldump -u user -p --ignore-table=db1.tbl1 --ignore-table=db2.tbl1 --databases db1 db2 ..

Tool to generate JSON schema from JSON data

For node.js > 6.0.0 there is also the json-schema-by-example module.

How to apply shell command to each line of a command output?

Better result for me:

ls -1 | xargs -L1 -d "\n" CMD

How to add anything in <head> through jquery/javascript?

Create a temporary element (e. g. DIV), assign your HTML code to its innerHTML property, and then append its child nodes to the HEAD element one by one. For example, like this:

var temp = document.createElement('div');

temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
               + '<script src="foobar.js"><\/script> ';

var head = document.head;

while (temp.firstChild) {
    head.appendChild(temp.firstChild);
}

Compared with rewriting entire HEAD contents via its innerHTML, this wouldn’t affect existing child elements of the HEAD element in any way.

Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval().

jQuery’s .bind() vs. .on()

From the jQuery documentation:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

http://api.jquery.com/bind/

git commit error: pathspec 'commit' did not match any file(s) known to git

Please try adding the double quotes git commit -m "initial commit". This will solve your problem.

Adding line break in C# Code behind page

Strings are immutable, so using

public string GenerateString()
{
    return
        "abc" +
        "def";
}

will slow you performance - each of those values is a string literal which must be concatenated at runtime - bad news if you reuse the method/property/whatever alot...

Store your string literals in resources is a good idea...

public string GenerateString()
{
    return Resources.MyString;
}

That way it is localisable and the code is tidy (although performance is pretty terrible).

Multiple arguments to function called by pthread_create()?

use

struct arg_struct *args = (struct arg_struct *)arguments;

in place of

struct arg_struct *args = (struct arg_struct *)args;

How to get the selected row values of DevExpress XtraGrid?

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.

For example:

private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
        return;
    MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());            
}

Creating InetAddress object in Java

From the API for InetAddress

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

Remove border from IFrame

Add the frameBorder attribute (note the capital ‘B’).

So it would look like:

<iframe src="myURL" width="300" height="300" frameBorder="0">Browser not compatible.</iframe>

Cross-Origin Request Headers(CORS) with PHP headers

I got the same error, and fixed it with the following PHP in my back-end script:

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

How to get Map data using JDBCTemplate.queryForMap

queryForMap is appropriate if you want to get a single row. You are selecting without a where clause, so you probably want to queryForList. The error is probably indicative of the fact that queryForMap wants one row, but you query is retrieving many rows.

Check out the docs. There is a queryForList that takes just sql; the return type is a

List<Map<String,Object>>.

So once you have the results, you can do what you are doing. I would do something like

List results = template.queryForList(sql);

for (Map m : results){
   m.get('userid');
   m.get('username');
} 

I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.

If you have a User object, and you actually want to load User instances, you can use the queryForList that takes sql and a class type

queryForList(String sql, Class<T> elementType)

(wow Spring has changed a lot since I left Javaland.)

Retrieving a List from a java.util.stream.Stream in Java 8

There is an another variant of collect method provided by LongStream class and similarly by IntStream and DoubleStream classes too .

<R> R collect(Supplier<R> supplier,
              ObjLongConsumer<R> accumulator,
              BiConsumer<R,R> combiner)

Performs a mutable reduction operation on the elements of this stream. A mutable reduction is one in which the reduced value is a mutable result container, such as an ArrayList, and elements are incorporated by updating the state of the result rather than by replacing the result. This produces a result equivalent to:

R result = supplier.get();
  for (long element : this stream)
       accumulator.accept(result, element);
  return result;

Like reduce(long, LongBinaryOperator), collect operations can be parallelized without requiring additional synchronization. This is a terminal operation.

And answer to your question with this collect method is as below :

    LongStream.of(1L, 2L, 3L, 3L).filter(i -> i > 2)
    .collect(ArrayList::new, (list, value) -> list.add(value)
    , (list1, list2) -> list1.addAll(list2));

Below is the method reference variant which is quite smart but some what tricky to understand :

     LongStream.of(1L, 2L, 3L, 3L).filter(i -> i > 2)
    .collect(ArrayList::new, List::add , List::addAll);

Below will be the HashSet variant :

     LongStream.of(1L, 2L, 3L, 3).filter(i -> i > 2)
     .collect(HashSet::new, HashSet::add, HashSet::addAll);

Similarly LinkedList variant is like this :

     LongStream.of(1L, 2L, 3L, 3L)
     .filter(i -> i > 2)
     .collect(LinkedList::new, LinkedList::add, LinkedList::addAll);

Excel formula to get week number in month (having Monday)

If week 1 always starts on the first Monday of the month try this formula for week number

=INT((6+DAY(A1+1-WEEKDAY(A1-1)))/7)

That gets the week number from the date in A1 with no intermediate calculations - if you want to use your "Monday's date" in B1 you can use this version

=INT((DAY(B1)+6)/7)

How do I disable the security certificate check in Python requests

Use requests.packages.urllib3.disable_warnings() and verify=False on requests methods.

import requests
from urllib3.exceptions import InsecureRequestWarning

# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

# Set `verify=False` on `requests.post`.
requests.post(url='https://example.com', data={'bar':'baz'}, verify=False)

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

this is the easiest way: Make list
Select list
right click: Define Name (e.g. ItemStatus)
select a cell where the list should appear (copy paste can be done later, so not location critical)
Data > Data Validation
Allow: Select List
Source: =ItemStatus (don't forget the = sign)
click Ok
dropdown appears in the cell you selected
Home > Conditional Formatting
Manage Rules
New Rule
etc.

Add space between HTML elements only using CSS

Or, instead of setting margin and than overriding it, you can just set it properly right away with the following combo:

span:not(:first-of-type) {
    margin-left:  5px;
}

span:not(:last-of-type) {
    margin-right: 5px;
}

jQuery add class .active on menu

    let path = window.location.href;
    $('#nav li a').each(function() {
        if (this.href === path) {
            $(this).addClass('activo');
        }else{
            $(this).removeClass('activo')
        }
        
    })
    

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

angular 2 how to return data from subscribe

I have used this way lots time ...

_x000D_
_x000D_
@Component({_x000D_
   selector: "data",_x000D_
   template: "<h1>{{ getData() }}</h1>"_x000D_
})_x000D_
_x000D_
export class DataComponent{_x000D_
    this.http.get(path).subscribe({_x000D_
       DataComponent.setSubscribeData(res);_x000D_
    })_x000D_
}_x000D_
_x000D_
_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
    DataComponent.subscribeData=data;_x000D_
    return data;_x000D_
}
_x000D_
_x000D_
_x000D_

use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...

Retrieving the COM class factory for component failed

I had the same error when I deployed my app. I've got solution from this site: Component with CLSID XXX failed due to the following error: 80070005 Access is denied

Here is this solution:

  1. In DCOMCNFG, right click on the My Computer and select properties.

  2. Choose the COM Securities tab.

  3. In Access Permissions, click Edit Defaults and add Network Service to it and give it Allow local access permission. Do the same for < Machine_name >\Users.

  4. In Launch and Activation Permissions, click Edit Defaults and add Network Service to it and give it Local launch and Local Activation permission. Do the same for < Machine_name >\Users.

*I used forms authentication.

Javascript array value is undefined ... how do I test for that

predQuery[preId]=='undefined'

You're testing against the string 'undefined'; you've confused this test with the typeof test which would return a string. You probably mean to be testing against the special value undefined:

predQuery[preId]===undefined

Note the strict-equality operator to avoid the generally-unwanted match null==undefined.

However there are two ways you can get an undefined value: either preId isn't a member of predQuery, or it is a member but has a value set to the special undefined value. Often, you only want to check whether it's present or not; in that case the in operator is more appropriate:

!(preId in predQuery)

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

Download multiple files with a single action

A jQuery version of the iframe answers:

function download(files) {
    $.each(files, function(key, value) {
        $('<iframe></iframe>')
            .hide()
            .attr('src', value)
            .appendTo($('body'))
            .load(function() {
                var that = this;
                setTimeout(function() {
                    $(that).remove();
                }, 100);
            });
    });
}

Handling JSON Post Request in Go

I was driving myself crazy with this exact problem. My JSON Marshaller and Unmarshaller were not populating my Go struct. Then I found the solution at https://eager.io/blog/go-and-json:

"As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller."

After that, my Marshaller and Unmarshaller worked perfectly!

require_once :failed to open stream: no such file or directory

It says that the file C:\wamp\www\mysite\php\includes\dbconn.inc doesn't exist, so the error is, you're missing the file.

Entity Framework code first unique column

In Entity Framework 6.1+ you can use this attribute on your model:

[Index(IsUnique=true)]

You can find it in this namespace:

using System.ComponentModel.DataAnnotations.Schema;

If your model field is a string, make sure it is not set to nvarchar(MAX) in SQL Server or you will see this error with Entity Framework Code First:

Column 'x' in table 'dbo.y' is of a type that is invalid for use as a key column in an index.

The reason is because of this:

SQL Server retains the 900-byte limit for the maximum total size of all index key columns."

(from: http://msdn.microsoft.com/en-us/library/ms191241.aspx )

You can solve this by setting a maximum string length on your model:

[StringLength(450)]

Your model will look like this now in EF CF 6.1+:

public class User
{
   public int UserId{get;set;}
   [StringLength(450)]
   [Index(IsUnique=true)]
   public string UserName{get;set;}
}

Update:

if you use Fluent:

  public class UserMap : EntityTypeConfiguration<User>
  {
    public UserMap()
    {
      // ....
      Property(x => x.Name).IsRequired().HasMaxLength(450).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index") { IsUnique = true } }));
    }
  }

and use in your modelBuilder:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  // ...
  modelBuilder.Configurations.Add(new UserMap());
  // ...
}

Update 2

for EntityFrameworkCore see also this topic: https://github.com/aspnet/EntityFrameworkCore/issues/1698

Update 3

for EF6.2 see: https://github.com/aspnet/EntityFramework6/issues/274

Update 4

ASP.NET Core Mvc 2.2 with EF Core:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Unique { get; set; }

MySQL vs MySQLi when using PHP

If you have a look at MySQL Improved Extension Overview, it should tell you everything you need to know about the differences between the two.

The main useful features are:

  • an Object-oriented interface
  • support for prepared statements
  • support for multiple statements
  • support for transactions
  • enhanced debugging capabilities
  • embedded server support.

Get JSONArray without array name?

You don't need to call json.getJSONArray() at all, because the JSON you're working with already is an array. So, don't construct an instance of JSONObject; use a JSONArray. This should suffice:

// ...
JSONArray json = new JSONArray(result);
// ...

for(int i=0;i<json.length();i++){                        
    HashMap<String, String> map = new HashMap<String, String>();    
    JSONObject e = json.getJSONObject(i);

    map.put("id",  String.valueOf(i));
    map.put("name", "Earthquake name:" + e.getString("eqid"));
    map.put("magnitude", "Magnitude: " +  e.getString("magnitude"));
    mylist.add(map);            
}

You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArray at the root, not a JSONObject.

Align text in JLabel to the right

To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:

JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);     

And if you have an image:

JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);

But, I believe you want to make the label such that there are only 2 words on 1 line.

In that case try this:

String urText="<html>You can<br>use basic HTML<br>in Swing<br> components," 
   +"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);

Select multiple columns using Entity Framework

Why don't you create a new object right in the .Select:

.Select(x => new PInfo{ 
    ServerName = x.ServerName, 
    ProcessID = x.ProcessID, 
    UserName = x.Username }).ToList();

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

How to add composite primary key to table

If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

enter image description here

How to make a new line or tab in <string> XML (eclipse/android)?

You can use \n for new line and \t for tabs. Also, extra spaces/tabs are just copied the way you write them in Strings.xml so just give a couple of spaces where ever you want them.

A better way to reach this would probably be using padding/margin in your view xml and splitting up your long text in different strings in your string.xml

Specifying a custom DateTime format when serializing with Json.Net

There is another solution I've been using. Just create a string property and use it for json. This property wil return date properly formatted.

class JSonModel {
    ...

    [JsonIgnore]
    public DateTime MyDate { get; set; }

    [JsonProperty("date")]
    public string CustomDate {
        get { return MyDate.ToString("ddMMyyyy"); }
        // set { MyDate = DateTime.Parse(value); }
        set { MyDate = DateTime.ParseExact(value, "ddMMyyyy", null); }
    }

    ...
}

This way you don't have to create extra classes. Also, it allows you to create diferent data formats. e.g, you can easily create another Property for Hour using the same DateTime.

Cannot instantiate the type List<Product>

List is an interface. You need a specific class in the end so either try

List l = new ArrayList();

or

List l = new LinkedList();

Whichever suit your needs.

Graphical HTTP client for windows

You could try Jsonium tool http://jsonium.org- nice free tool specialized on requests with JSON in bodies and responses

What's the Kotlin equivalent of Java's String[]?

There's no special case for String, because String is an ordinary referential type on JVM, in contrast with Java primitives (int, double, ...) -- storing them in a reference Array<T> requires boxing them into objects like Integer and Double. The purpose of specialized arrays like IntArray in Kotlin is to store non-boxed primitives, getting rid of boxing and unboxing overhead (the same as Java int[] instead of Integer[]).

You can use Array<String> (and Array<String?> for nullables), which is equivalent to String[] in Java:

val stringsOrNulls = arrayOfNulls<String>(10) // returns Array<String?>
val someStrings = Array<String>(5) { "it = $it" }
val otherStrings = arrayOf("a", "b", "c")

See also: Arrays in the language reference

HttpContext.Current.Session is null when routing requests

Nice job! I've been having the exact same problem. Adding and removing the Session module worked perfectly for me too. It didn't however bring back by HttpContext.Current.User so I tried your little trick with the FormsAuth module and sure enough, that did it.

<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>

How do I show the number keyboard on an EditText in android?

You can configure an inputType for your EditText:

<EditText android:inputType="number" ... />

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

So it turns out that because AnyObject is the spiritual successor to id, you can call any message you want on AnyObject. That's the equivalent of sending a message to id. Ok, fair enough. But now we add in the concept that all methods are optional on AnyObject, and we have something we can work with.

Given the above, I was hopeful I could just cast UIApplication.sharedApplication() to AnyObject, then create a variable equal to the method signature, set that variable to the optional method, then test the variable. This didn't seem to work. My guess is that when compiled against the iOS 8.0 SDK, the compiler knows where it thinks that method should be, so it optimizes this all down to a memory lookup. Everything works fine until I try to test the variable, at which point I get a EXC_BAD_ACCESS.

However, in the same WWDC talk where I found the gem about all methods being optional, they use Optional Chaining to call an optional method - and this seems to work. The lame part is that you have to actually attempt to call the method in order to know if it exists, which in the case of registering for notifications is a problem because you're trying to figure out if this method exists before you go creating a UIUserNotificationSettings object. It seems like calling that method with nil though is okay, so the solution that seems to be working for me is:

var ao: AnyObject = UIApplication.sharedApplication()
if let x:Void = ao.registerUserNotificationSettings?(nil) {
    // It's iOS 8
    var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
    var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
} else {
    // It's older
    var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
    UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
}

After much searching related to this, the key info came from this WWDC talk https://developer.apple.com/videos/wwdc/2014/#407 right in the middle at the section about "Optional Methods in Protocols"

In Xcode 6.1 beta the above code does not work anymore, the code below works:

   if UIApplication.sharedApplication().respondsToSelector("registerUserNotificationSettings:") {
        // It's iOS 8
        var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
       var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
       UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    } else {
        // It's older
        var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
        UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
    }

How to delete all the rows in a table using Eloquent?

simple solution:

 Mymodel::query()->delete();

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Just Run MySQL Server Installer and Reconfigure the My SQL Server...This worked for me.

Box shadow in IE7 and IE8

You could try this

box-shadow:
progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=10, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=10, OffY=20, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=20, OffY=30, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=30, OffY=40, Color='#19000000');

Is it possible to view RabbitMQ message contents directly from the command line?

I wrote rabbitmq-dump-queue which allows dumping messages from a RabbitMQ queue to local files and requeuing the messages in their original order.

Example usage (to dump the first 50 messages of queue incoming_1):

rabbitmq-dump-queue -url="amqp://user:[email protected]:5672/" -queue=incoming_1 -max-messages=50 -output-dir=/tmp

What is an IIS application pool?

Application pools are used to separate set of IIS worker processes that share the same configuration. Application pools enable us to isolate our web application for better security, reliability, and availability

JSON and XML comparison

The XML (extensible Markup Language) is used often XHR because this is a standard broadcasting language, what can be used by any programming language, and supported both server and client side, so this is the most flexible solution. The XML can be separated for more parts so a specified group can develop the part of the program, without affecting the other parts. The XML format can also be determined by the XML DTD or XML Schema (XSL) and can be tested.

The JSON a data-exchange format which is getting more popular as the JavaScript applications possible format. Basically this is an object notation array. JSON has a very simple syntax so can be easily learned. And also the JavaScript support parsing JSON with the eval function. On the other hand, the eval function has got negatives. For example, the program can be very slow parsing JSON and because of security the eval can be very risky. This not mean that the JSON is not good, just we have to be more careful.

My suggestion is that you should use JSON for applications with light data-exchange, like games. Because you don't have to really care about the data-processing, this is very simple and fast.

The XML is best for the bigger websites, for example shopping sites or something like this. The XML can be more secure and clear. You can create basic data-struct and schema to easily test the correction and separate it into parts easily.

I suggest you use XML because of the speed and the security, but JSON for lightweight stuff.

What is the reason for a red exclamation mark next to my project in Eclipse?

Solutin 1:

step:1

Right click on your project -> Close Project. it will Close your project and all opened file(s) of the project

step:2

Right click on your project -> Open Project. it will Open your project and rebuild your project, Hope fully it will fix red exclamation mark

Solution 2:

Step:1

Right click on your Project -> Properties -> Java Build Path. Can you see missing in front of your library file(s) as per following screen-shot

Step:2 Click on Add Jar to select your Jar file if it is the placed in WEB-INF/lib of your project or Add External Jar if jar file placed somewhere on your computer

Step:3 Select the old missing file(s) and click on Remove click here for image

Solutioin 3: Right click on your Project -> Properties -> Java Build Path -> JRE System Library and reconfigure the JRE

and go to your project and remove .properties and .classpath in your project directories.

backup your project data and create a new one and follow the solutions 1 & 2

How can I solve ORA-00911: invalid character error?

I had the same problem and it was due to the end of line. I had copied from another document. I put everythng on the same line, then split them again and it worked.

CSS Div Background Image Fixed Height 100% Width

See my answer to a similar question here.

It sounds like you want a background-image to keep it's own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that's the case, do something like this:

.chapter {
    position: relative;
    height: 1200px;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/3/

The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.

If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height to 0 and set the padding-bottom to the percentage of the width:

.chapter {
    position: relative;
    height: 0;
    padding-bottom: 75%;
    z-index: 1;
}

#chapter1 {
    background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: center top;
    background-attachment: fixed;
}

jsfiddle: http://jsfiddle.net/ndKWN/4/

You could also put the padding-bottom percentage into each #chapter style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value.

How to set the 'selected option' of a select dropdown list with jquery

One thing I don't think anyone has mentioned, and a stupid mistake I've made in the past (especially when dynamically populating selects). jQuery's .val() won't work for a select input if there isn't an option with a value that matches the value supplied.

Here's a fiddle explaining -> http://jsfiddle.net/go164zmt/

<select id="example">
    <option value="0">Test0</option>
    <option value="1">Test1</option>
</select>

$("#example").val("0");
alert($("#example").val());
$("#example").val("1");
alert($("#example").val());

//doesn't exist
$("#example").val("2");
//and thus returns null
alert($("#example").val());

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

COALESCE Function in TSQL

Simplest definition of the Coalesce() function could be:

Coalesce() function evaluates all passed arguments then returns the value of the first instance of the argument that did not evaluate to a NULL.

Note: it evaluates ALL parameters, i.e. does not skip evaluation of the argument(s) on the right side of the returned/NOT NULL parameter.

Syntax:

Coalesce(arg1, arg2, argN...)

Beware: Apart from the arguments that evaluate to NULL, all other (NOT-NULL) arguments must either be of same datatype or must be of matching-types (that can be "implicitly auto-converted" into a compatible datatype), see examples below:

PRINT COALESCE(NULL, ('str-'+'1'), 'x')  --returns 'str-1, works as all args (excluding NULLs) are of same VARCHAR type.
--PRINT COALESCE(NULL, 'text', '3', 3)    --ERROR: passed args are NOT matching type / can't be implicitly converted.
PRINT COALESCE(NULL, 3, 7.0/2, 1.99)      --returns 3.0, works fine as implicit conversion into FLOAT type takes place.
PRINT COALESCE(NULL, '1995-01-31', 'str') --returns '2018-11-16', works fine as implicit conversion into VARCHAR occurs.

DECLARE @dt DATE = getdate()
PRINT COALESCE(NULL, @dt, '1995-01-31')  --returns today's date, works fine as implicit conversion into DATE type occurs.

--DATE comes before VARCHAR (works):
PRINT COALESCE(NULL, @dt, 'str')      --returns '2018-11-16', works fine as implicit conversion of Date into VARCHAR occurs.

--VARCHAR comes before DATE (does NOT work):
PRINT COALESCE(NULL, 'str', @dt)      --ERROR: passed args are NOT matching type, can't auto-cast 'str' into Date type.

HTH

Git ignore local file changes

git pull wants you to either remove or save your current work so that the merge it triggers doesn't cause conflicts with your uncommitted work. Note that you should only need to remove/save untracked files if the changes you're pulling create files in the same locations as your local uncommitted files.

Remove your uncommitted changes

Tracked files

git checkout -f

Untracked files

git clean -fd

Save your changes for later

Tracked files

git stash

Tracked files and untracked files

git stash -u

Reapply your latest stash after git pull:

git stash pop

Angular: date filter adds timezone, how to output UTC?

Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example

Mongoose, update values in array of objects

Below is an example of how to update the value in the array of objects more dynamically.

Person.findOneAndUpdate({_id: id}, 
{ 
  "$set": {[`items.$[outer].${propertyName}`]: value} 
},
{ 
  "arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
  ...
})

Note that by doing it that way, you would be able to update even deeper levels of the nested array by adding additional arrayFilters and positional operator like so:

"$set": {[`items.$[outer].innerItems.$[inner].${propertyName}`]: value} 

"arrayFilters":[{ "outer.id": itemId },{ "inner.id": innerItemId }]

More usage can be found in the official docs.

How to search by key=>value in a multidimensional array in PHP

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

How to detect DataGridView CheckBox event change?

I found @Killercam's solution to work but was a bit dodgy if the user double clicked too fast. Not sure if other's found that the case either. I found a another solution here.

It uses the datagrid's CellValueChanged and CellMouseUp. Changhong explains that

"The reason for that is OnCellvalueChanged event won’t fire until the DataGridView thinks you have completed editing. This makes senses for a TextBox Column, as OnCellvalueChanged wouldn’t [bother] to fire for each key strike, but it doesn’t [make sense] for a CheckBox."

Here it is in action from his example:

private void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)
    {
        // Handle checkbox state change here
    }
}

And the code to tell the checkbox it is done editing when it is clicked, instead of waiting till the user leaves the field:

private void myDataGrid_OnCellMouseUp(object sender,DataGridViewCellMouseEventArgs e)
{
    // End of edition on each click on column of checkbox
    if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)
    {
        myDataGrid.EndEdit();
    }
}

Edit: A DoubleClick event is treated separate from a MouseUp event. If a DoubleClick event is detected, the application will ignore the first MouseUp event entirely. This logic needs to be added to the CellDoubleClick event in addition to the MouseUp event:

private void myDataGrid_OnCellDoubleClick(object sender,DataGridViewCellEventArgs e)
{
    // End of edition on each click on column of checkbox
    if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)
    {
        myDataGrid.EndEdit();
    }
}

How do I list all cron jobs for all users?

for user in $(cut -f1 -d: /etc/passwd); 
do 
    echo $user; crontab -u $user -l; 
done

Check if a file exists with wildcard in shell script

Here is my answer -

files=(xorg-x11-fonts*)

if [ -e "${files[0]}" ];
then
    printf "BLAH"
fi

Selecting/excluding sets of columns in pandas

You can either Drop the columns you do not need OR Select the ones you need

# Using DataFrame.drop
df.drop(df.columns[[1, 2]], axis=1, inplace=True)

# drop by Name
df1 = df1.drop(['B', 'C'], axis=1)

# Select the ones you want
df1 = df[['a','d']]

How do operator.itemgetter() and sort() work?

You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter returns a callable:

>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8

To do it in a different way, you can use lambda:

a.sort(key=lambda x: x[1])

And reverse it:

a.sort(key=operator.itemgetter(1), reverse=True)

Sort by more than one column:

a.sort(key=operator.itemgetter(1,2))

See the sorting How To.

How to increment datetime by custom months in python without using library

What about this one? (doesn't require any extra libraries)

from datetime import date, timedelta
from calendar import monthrange

today = date.today()
month_later = date(today.year, today.month, monthrange(today.year, today.month)[1]) + timedelta(1)

setting min date in jquery datepicker

Just in case if for example you need to put a min date, the last 3 months and max date next 3 months

$('#id_your_date').datepicker({ 
   maxDate: '+3m',
   minDate: '-3m'
 });

Can regular JavaScript be mixed with jQuery?

Or no JavaScript load function at all...

<html>
<head></head>
<body>
    <canvas id="canvas" width="150" height="150"></canvas>
</body>
<script type="text/javascript">
    var draw = function() {
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (10, 10, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (30, 30, 55, 50);
        }
    }
    draw();

    //or self executing...

    (function(){
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (50, 50, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (70, 70, 55, 50);
        }
    })();
</script>
</html>

How can I iterate over an enum?

Extending @Eponymous's answer: It's great, but doesn't provide a general syntax. Here's what I came up with:

// Common/EnumTools.h
#pragma once

#include <array>

namespace Common {

// Here we forward-declare metafunction for mapping enums to their values.
// Since C++<23 doesn't have reflection, you have to populate it yourself :-(
// Usage: After declaring enum class E, add this overload in the namespace of E:
// inline constexpr auto allValuesArray(const E&, Commob::EnumAllValuesTag) { return std::array{E::foo, E::bar}; }
// Then `AllValues<NS::E>` will call `allValuesArray(NS::E{}, EnumAllValuesTag)` which will resolve
// by ADL.
// Just be sure to keep it sync'd with your enum!

// Here's what you want to use in, e.g., loops: "for (auto val : Common::AllValues<MyEnum>) {"

struct EnumAllValuesTag {}; // So your allValuesArray function is clearly associated with this header.

template <typename Enum>
static inline constexpr auto AllValues = allValuesArray(Enum{}, EnumAllValuesTag{});
// ^ Just "constexpr auto" or "constexpr std::array<Enum, allValuesArray(Enum{}, EnumAllValuesTag{}).size()>" didn't work on all compilers I'm using, but this did.

} // namespace Common

then in your namespace:

#include "Common/EnumTools.h"

namespace MyNamespace {

enum class MyEnum {
    foo,
    bar = 4,
    baz = 42,
};

// Making this not have to be in the `Common` namespace took some thinking,
// but is a critical feature since otherwise there's no hope in keeping it sync'd with the enum.
inline constexpr auto allValuesArray(const MyEnum&, Common::EnumAllValuesTag) {
    return std::array{ MyEnum::foo, MyEnum::bar, MyEnum::baz };
}

} // namespace MyNamespace

then wherever you need to use it:

for (const auto& e : Common::AllValues<MyNamespace::MyEnum>) { ... }

so even if you've typedef'd:

namespace YourNS {
using E = MyNamespace::MyEnum;
} // namespace YourNS

for (const auto& e : Common::AllValues<YourNS::E>) { ... }

I can't think of anything much better, short of the actual language feature everyone looking at this page want.

Future work:

  1. You should be able to add a constexpr function (and so a metafunction) that filters Common::AllValues<E> to provide a Common::AllDistinctValues<E> for the case of enums with repeated numerical values like enum { foo = 0, bar = 0 };.
  2. I bet there's a way to use the compiler's switch-covers-all-enum-values to write allValuesArray such that it errors if the enum has added a value.

Detecting scroll direction

  1. Initialize an oldValue
  2. Get the newValue by listening to the event
  3. Subtract the two
  4. Conclude from the result
  5. Update oldValue with the newValue

// Initialization

let oldValue = 0;

//Listening on the event

window.addEventListener('scroll', function(e){

    // Get the new Value
    newValue = window.pageYOffset;

    //Subtract the two and conclude
    if(oldValue - newValue < 0){
        console.log("Up");
    } else if(oldValue - newValue > 0){
        console.log("Down");
    }

    // Update the old value
    oldValue = newValue;
});

Place API key in Headers or URL

passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.

How do I break out of a loop in Perl?

Oh, I found it. You use last instead of break

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

Android, landscape only orientation?

Yes, in AndroidManifest.xml, declare your Activity like so: <activity ... android:screenOrientation="landscape" .../>

Recursive mkdir() system call on Unix

Quite straight. This can be a good starting point

int makeDir(char *fullpath, mode_t permissions){
int i=0;
char *arrDirs[20];
char aggrpaz[255];
arrDirs[i] = strtok(fullpath,"/");
strcpy(aggrpaz, "/");
while(arrDirs[i]!=NULL)
{
    arrDirs[++i] = strtok(NULL,"/");
    strcat(aggrpaz, arrDirs[i-1]);
    mkdir(aggrpaz,permissions);
    strcat(aggrpaz, "/");
}
i=0;
return 0;
}

You parse this function a full path plus the permissions you want, i.e S_IRUSR, for a full list of modes go here https://techoverflow.net/2013/04/05/how-to-use-mkdir-from-sysstat-h/

The fullpath string will be split by the "/" character and individual dirs will be appended to the aggrpaz string one at a time. Each loop iteration calls the mkdir function, passing it the aggregate path so far plus the permissions. This example can be improved, I am not checking the mkdir function output and this function only works with absolute paths.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

A random value?

If you want a random value, try

<?php
$value = mt_rand($min, $max);

mt_rand() will run a bit more random if you are using many random numbers in a row, or if you might ever execute the script more than once a second. In general, you should use mt_rand() over rand() if there is any doubt.

Copy multiple files in Python

Here is another example of a recursive copy function that lets you copy the contents of the directory (including sub-directories) one file at a time, which I used to solve this problem.

import os
import shutil

def recursive_copy(src, dest):
    """
    Copy each file from src dir to dest dir, including sub-directories.
    """
    for item in os.listdir(src):
        file_path = os.path.join(src, item)

        # if item is a file, copy it
        if os.path.isfile(file_path):
            shutil.copy(file_path, dest)

        # else if item is a folder, recurse 
        elif os.path.isdir(file_path):
            new_dest = os.path.join(dest, item)
            os.mkdir(new_dest)
            recursive_copy(file_path, new_dest)

EDIT: If you can, definitely just use shutil.copytree(src, dest). This requires that that destination folder does not already exist though. If you need to copy files into an existing folder, the above method works well!

Set focus on <input> element

html of component:

<input [cdkTrapFocusAutoCapture]="show" [cdkTrapFocus]="show">

controler of component:

showSearch() {
  this.show = !this.show;    
}

..and do not forget about import A11yModule from @angular/cdk/a11y

import { A11yModule } from '@angular/cdk/a11y'

Crystal Reports - Adding a parameter to a 'Command' query

The solution I came up with was as follows:

  1. Create the SQL query in your favorite query dev tool
  2. In Crystal Reports, within the main report, create parameter to pass to the subreport
  3. Create sub report, using the 'Add Command' option in the 'Data' portion of the 'Report Creation Wizard' and the SQL query from #1.
  4. Once the subreport is added to the main report, right click on the subreport, choose 'Change Subreport Links...', select the link field, and uncheck 'Select data in subreport based on field:'

    NOTE: You may have to initially add the parameter with the 'Select data in subreport based on field:' checked, then go back to 'Change Subreport Links ' and uncheck it after the subreport has been created.

  5. In the subreport, click the 'Report' menu, 'Select Expert', use the 'Formula Editor', set the SQL column from #1 either equal to or like the parameter(s) selected in #4.

                    (Subreport SQL Column)  (Parameter from Main Report)
            Example:  {Command.Project} like {?Pm-?Proj_Name}
    

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

php REQUEST_URI

You can simply use $_GET especially if you know the othervar's name. If you want to be on the safe side, use if (isset ($_GET ['varname'])) to test for existence.

PSEXEC, access denied errors

For anybody who may stumble upon this. There is a recent (Dec 2013) Security Update from Microsoft Windows on Windows 7 that is preventing remote execution. See http://support.microsoft.com/kb/2893294/en-us

I uninstalled the Security Update by going to Control Panel\Programs\Programs and Features\Installed Updates

It worked right after that.

How to create a GUID/UUID in Python

If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.

Ex:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')

How to get current location in Android

I'm using this tutorial and it works nicely for my application.

In my activity I put this code:

GPSTracker tracker = new GPSTracker(this);
    if (!tracker.canGetLocation()) {
        tracker.showSettingsAlert();
    } else {
        latitude = tracker.getLatitude();
        longitude = tracker.getLongitude();
    }

also check if your emulator runs with Google API

java.lang.NoClassDefFoundError: Could not initialize class XXX

If you're working on an Android project, make sure you aren't calling any static methods on any Android classes. I'm only using JUnit + Mockito, so maybe some other frameworks might help you avoid the problem altogether, I'm not sure.

My problem was calling Uri.parse(uriString) as part of a static initializer for a unit test. The Uri class is an Android API, which is why the unit test build couldn't find it. I changed this value to null instead and everything went back to normal.

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

Center align with table-cell

This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.

DEMO

here's the gist of the demo

.container{

  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;

}

html

<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,
  </div>
</div>

enter image description here

Convert Java Date to UTC String

Well if you want to use java.util.Date only, here is a small trick you can use:

String dateString = Long.toString(Date.UTC(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));

Convert txt to csv python script

import pandas as pd
df = pd.read_fwf('log.txt')
df.to_csv('log.csv')

How to enable or disable an anchor using jQuery?

$('#divID').addClass('disabledAnchor');

In css file

.disabledAnchor a{
       pointer-events: none !important;
       cursor: default;
       color:white;
}

mean() warning: argument is not numeric or logical: returning NA

The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean() function. Therefore, check your data using str(data.frame&column) function to see what data type you have, and convert it to numeric format if necessary. For example, if your data is Character convert it with as.numeric(data.frame$column), or as a factor with as.numeric(as.character(data.frame$column)). The mean function does not work with types other than numeric.

Is there a Mutex in Java?

Any object in Java can be used as a lock using a synchronized block. This will also automatically take care of releasing the lock when an exception occurs.

Object someObject = ...;

synchronized (someObject) {
  ...
}

You can read more about this here: Intrinsic Locks and Synchronization

Running Command Line in Java

Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

Find a line in a file and remove it

package com.ncs.cache;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {

    public void removeLineFromFile(String file, String lineToRemove) {

        try {

            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }

            // Construct the new file that will later be renamed to the original
            // filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            // Read from the original file and write to the new
            // unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().equals(lineToRemove)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            // Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

            // Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile))
                System.out.println("Could not rename file");

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FileUtil util = new FileUtil();
        util.removeLineFromFile("test.txt", "bbbbb");
    }
}

src : http://www.javadb.com/remove-a-line-from-a-text-file/

Regular expression: find spaces (tabs/space) but not newlines

Try this character set:

[ \t]

This does only match a space or a tabulator.

How can I run Tensorboard on a remote server?

You don't need to do anything fancy. Just run:

tensorboard --host 0.0.0.0 <other args here>

and connect with your server url and port. The --host 0.0.0.0 tells tensorflow to listen from connections on all IPv4 addresses on the local machine.

Handling null values in Freemarker

If you have a lot of variables to convert in optional, you can use SubimeText with this:

Find: \${([A-Za-z_0-9]*)}
Replace: \$\{${1}!\}

Be sure regex and case-sensitive options are enabled:

Sublime regex replace

mysql.h file can't be found

this worked for me

$ gcc dbconnect.c -o dbconnect -lmysqlclient
$ ./dbconnect

-lmysqlclient is must.

and i would personally recommend to use following notation instead of using -I compilation flag.

#include <mysql/mysql.h>

How to send data to COM PORT using JAVA?

An alternative to javax.comm is the rxtx library which supports more platforms than javax.comm.

How do I ignore files in Subversion?

When using propedit make sure not have any trailing spaces as that will cause the file to be excluded from the ignore list.

These are inserted automatically if you've use tab-autocomplete on linux to create the file to begin with:

svn propset svn:ignore 'file1
file2' .

Using quotation marks inside quotation marks

One case which is prevalent in duplicates is the requirement to use quotes for external processes. A workaround for that is to not use a shell, which removes the requirement for one level of quoting.

os.system("""awk '/foo/ { print "bar" }' %""" % filename)

can usefully be replaced with

subprocess.call(['awk', '/foo/ { print "bar" }', filename])

(which also fixes the bug that shell metacharacters in filename would need to be escaped from the shell, which the original code failed to do; but without a shell, no need for that).

Of course, in the vast majority of cases, you don't want or need an external process at all.

with open(filename) as fh:
    for line in fh:
        if 'foo' in line:
            print("bar")

Microsoft.ACE.OLEDB.12.0 is not registered

Summarized: INSTALL 32 bit version of Microsoft Access Database Engine 2010 Redistributable. Uninstall 64 bit version if previously installed. http://www.microsoft.com/en-us/download/details.aspx?id=13255

The Excel connection manager is trying to use the ACE OLE DB provider in order to access the Excel file when the version is above 2007 (xlsx). Although your box is 64-bit, you’re using SQL Server Data Tools, which is a 32-bit application. There is no 64-bit version for SSDT. When you design your package within SSDT, you’re using a 32-bit process, which can only use 32-bit providers. When you try to choose the table in the Excel file, the connection manager needs to access the 32-bit version of the ACE OLE DB provider, but this provider is not registered on your machine, only the 64-bit version is installed.

You should download the 32-bit version of the “Microsoft Access Database Engine 2010 Redistributable”. When you try to install it, you might get an error message. You should first uninstall only the 64-bit version of the “Microsoft Access Database Engine 2010 Redistributable”, which you probably installed previously. The 64-bit version and the 32-bit version can’t live together on the same host, so you’ll have to uninstall (through “Program and Features”) and install the other one if you wish to switch between them.

Once you finish uninstalling the 64-bit version and installing the 32-bit version of the provider, the problem is solved, and you can finally choose the table within the Excel file. The Excel connection manager is now able to use the ACE OLE DB provider (32-bit version) in order to access the Excel file.

How to load/reference a file as a File instance from the classpath

Or use directly the InputStream of the resource using the absolute CLASSPATH path (starting with the / slash character):


getClass().getResourceAsStream("/com/path/to/file.txt");

Or relative CLASSPATH path (when the class you are writing is in the same Java package as the resource file itself, i.e. com.path.to):


getClass().getResourceAsStream("file.txt");

How to create a project from existing source in Eclipse and then find it?

In the package explorer and the navigation screen you should now see the project you created. Note that eclipse will not copy your files, it will just allow you to use the existing source and edit it from eclipse.

How can I account for period (AM/PM) using strftime?

The Python time.strftime docs say:

When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

Sure enough, changing your %H to %I makes it work.

Apply style to only first level of td tags

This style:

table tr td { border: 1px solid red; }
td table tr td { border: none; }

gives me:

this http://img12.imageshack.us/img12/4477/borders.png

However, using a class is probably the right approach here.

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

Call JavaScript function from C#

This may be helpful to you:

<script type="text/javascript">
    function Showalert() {
        alert('Profile not parsed!!');
        window.parent.parent.parent.location.reload();
    }
    function ImportingDone() {
        alert('Importing done successfull.!');
        window.parent.parent.parent.location.reload();
    }
</script>

if (SelectedRowCount == 0)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}
else
{
    ScriptManager.RegisterStartupScript(this, GetType(), "importingdone", "ImportingDone();", true);
}

Better way to sum a property value in an array

I was already using jquery. But I think its intuitive enough to just have:

var total_amount = 0; 
$.each(traveler, function( i, v ) { total_amount += v.Amount ; });

This is basically just a short-hand version of @akhouri's answer.

When should I use a List vs a LinkedList

Use LinkedList<> when

  1. You don't know how many objects are coming through the flood gate. For example, Token Stream.
  2. When you ONLY wanted to delete\insert at the ends.

For everything else, it is better to use List<>.

SQL Server replace, remove all after certain character

Use LEFT combined with CHARINDEX:

UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

Note that the WHERE clause skips updating rows in which there is no semicolon.

Here is some code to verify the SQL above works:

declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself    

UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

select * from @MyTable

I get the following results:

id MyText
-- -------------------------
1  some text
2  text again
3  text without a semicolon
4  NULL
5        (empty string)
6  test 3 semicolons
7        (empty string)

How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also use formatDate

let formattedDt = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ssZZZZZ', 'en_US')

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

A simple solution is to use Microsoft ASP.NET Web API 2.2 Client from NuGet.

Then you can simply do this and it'll serialize the object to JSON and set the Content-Type header to application/json; charset=utf-8:

var data = new
{
    name = "Foo",
    category = "article"
};

var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var response = await client.PostAsJsonAsync("", data);

How to stop a setTimeout loop?

var myVar = null;

if(myVar)
   clearTimeout(myVar);

myVar = setTimeout(function(){ alert("Hello"); }, 3000);

Store output of subprocess.Popen call in a string

for Python 2.7+ the idiomatic answer is to use subprocess.check_output()

You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....

If args is just single command with no args of its own (or you have shell=True set), it can be a string. Otherwise it must be a list.

for example... to invoke the ls command, this is fine:

from subprocess import check_call
check_call('ls')

so is this:

from subprocess import check_call
check_call(['ls',])

however, if you want to pass some args to the shell command, you can't do this:

from subprocess import check_call
check_call('ls -al')

instead, you must pass it as a list:

from subprocess import check_call
check_call(['ls', '-al'])

the shlex.split() function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses... like this:

from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))

SQL Server: how to select records with specific date from datetime column

The easiest way is to convert to a date:

SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';

Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.

I would be inclined to use the following, just out of habit:

SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';

integrating barcode scanner into php application?

PHP can be easily utilized for reading bar codes printed on paper documents. Connecting manual barcode reader to the computer via USB significantly extends usability of PHP (or any other web programming language) into tasks involving document and product management, like finding a book records in the database or listing all bills for a particular customer.

Following sections briefly describe process of connecting and using manual bar code reader with PHP.

The usage of bar code scanners described in this article are in the same way applicable to any web programming language, such as ASP, Python or Perl. This article uses only PHP since all tests have been done with PHP applications.

What is a bar code reader (scanner)

Bar code reader is a hardware pluggable into computer that sends decoded bar code strings into computer. The trick is to know how to catch that received string. With PHP (and any other web programming language) the string will be placed into focused input HTML element in browser. Thus to catch received bar code string, following must be done:

just before reading the bar code, proper input element, such as INPUT TEXT FIELD must be focused (mouse cursor is inside of the input field). once focused, start reading the code when the code is recognized (bar code reader usually shortly beeps), it is send to the focused input field. By default, most of bar code readers will append extra special character to decoded bar code string called CRLF (ENTER). For example, if decoded bar code is "12345AB", then computer will receive "12345ABENTER". Appended character ENTER (or CRLF) emulates pressing the key ENTER causing instant submission of the HTML form:

<form action="search.php" method="post">
    <input name="documentID" onmouseover="this.focus();" type="text">
</form>

Choosing the right bar code scanner

When choosing bar code reader, one should consider what types of bar codes will be read with it. Some bar codes allow only numbers, others will not have checksum, some bar codes are difficult to print with inkjet printers, some barcode readers have narrow reading pane and cannot read for example barcodes with length over 10 cm. Most of barcode readers support common barcodes, such as EAN8, EAN13, CODE 39, Interleaved 2/5, Code 128 etc.

For office purposes, the most suitable barcodes seem to be those supporting full range of alphanumeric characters, which might be:

  • code 39 - supports 0-9, uppercased A-Z, and few special characters (dash, comma, space, $, /, +, %, *)
  • code 128 - supports 0-9, a-z, A-Z and other extended characters

Other important things to note:

  • make sure all standard barcodes are supported, at least CODE39, CODE128, Interleaved25, EAN8, EAN13, PDF417, QRCODE.
  • use only standard USB plugin cables. RS232 interfaces are meant for industrial usage, rather than connecting to single PC.
  • the cable should be long enough, at least 1.5 m - the longer the better.
  • bar code reader plugged into computer should not require other power supply - it should power up simply by connecting to PC via USB.
  • if you also need to print bar code into generated PDF documents, you can use TCPDF open source library that supports most of common 2D bar codes.

Installing scanner drivers

Installing manual bar code reader requires installing drivers for your particular operating system and should be normally supplied with purchased bar code reader.

Once installed and ready, bar code reader turns on signal LED light. Reading the barcode starts with pressing button for reading.

Scanning the barcode - how does it work?

STEP 1 - Focused input field ready for receiving character stream from bar code scanner:

step 1

STEP 2 - Received barcode string from bar code scanner is immediatelly submitted for search into database, which creates nice "automated" effect:

step 2

STEP 3 - Results returned after searching the database with submitted bar code:

step 3

Conclusion

It seems, that utilization of PHP (and actually any web programming language) for scanning the bar codes has been quite overlooked so far. However, with natural support of emulated keypress (ENTER/CRLF) it is very easy to automate collecting & processing recognized bar code strings via simple HTML (GUI) fomular.

The key is to understand, that recognized bar code string is instantly sent to the focused HTML element, such as INPUT text field with appended trailing character ASCII 13 (=ENTER/CRLF, configurable option), which instantly sends input text field with populated received barcode as a HTML formular to any other script for further processing.

Reference: http://www.synet.sk/php/en/280-barcode-reader-scanner-in-php

Hope this helps you :)

Posting raw image data as multipart/form-data in curl

In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.

This is the relevant part of the server code that helped:

if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
    $headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
    $postfields = array("filedata" => "@$filedata", "filename" => $filename);
    $ch = curl_init();
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $postfields,
        CURLOPT_INFILESIZE => $filesize,
        CURLOPT_RETURNTRANSFER => true
    ); // cURL options
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    if(!curl_errno($ch))
    {
        $info = curl_getinfo($ch);
        if ($info['http_code'] == 200)
            $errmsg = "File uploaded successfully";
    }
    else
    {
        $errmsg = curl_error($ch);
    }
    curl_close($ch);
}
else
{
    $errmsg = "Please select the file";
}
}

html form should look something like:

<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
  <td>Upload</td>
  <td align="center">:</td>
  <td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td align="center">&nbsp;</td>
  <td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>

Open Bootstrap Modal from code-behind

Finally I found out the problem preventing me from showing the modal from code-behind. One must think that it was as easy as register a clientscript that made the opening, like:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(),"none",
    "<script>$('#mymodal').modal('show');</script>", false);

But this never worked for me.

The problem is that Twitter Bootstrap Modals scripts don't work at all when the modal is inside an asp:Updatepanel, period. The behaviour of the modals fail from each side, codebehind to client and client to codebehind (postback). It even prevents postbacks when any js of the modal has executed, like a close button that you also need to do some sever objects disposing (for a dirty example)

I've notified the bootstrap staff, but they replied a convenient "please give us a fail scenario with only plain html and not asp." In my town, that's called... well, Bootstrap not supporting anything more that plain html. Nevermind, using it on asp.

I thought them to at least looking what they're doing different at the backdrop management, that I found causes the major part of the problems, but... (justa hint there)

So anyone that has the problem, drop the updatepanel for a try.

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

What’s the best way to get an HTTP response code from a URL?

Update using the wonderful requests library. Note we are using the HEAD request, which should happen more quickly then a full GET or POST request.

import requests
try:
    r = requests.head("https://stackoverflow.com")
    print(r.status_code)
    # prints the int of the status code. Find more at httpstatusrappers.com :)
except requests.ConnectionError:
    print("failed to connect")

Sass - Converting Hex to RGBa for background opacity

If you need to mix colour from variable and alpha transparency, and with solutions that include rgba() function you get an error like

      background-color: rgba(#{$color}, 0.3);
                       ^
      $color: #002366 is not a color.
   ?
   ¦       background-color: rgba(#{$color}, 0.3);
   ¦                         ^^^^^^^^^^^^^^^^^^^^

Something like this might be useful.

$meeting-room-colors: (
  Neumann: '#002366',
  Turing: '#FF0000',
  Lovelace: '#00BFFF',
  Shared: '#00FF00',
  Chilling: '#FF1493',
);
$color-alpha: EE;

@each $name, $color in $meeting-room-colors {

  .#{$name} {

     background-color: #{$color}#{$color-alpha};

  }

}

How to initialize an array's length in JavaScript?

Assuming that Array's length is constant. In Javascript, This is what we do:

const intialArray = new Array(specify the value);

how to write an array to a file Java

Just loop over the elements in your array.

Ex:

for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here

Passing an array using an HTML form hidden element

Use:

$postvalue = array("a", "b", "c");
foreach($postvalue as $value)
{
    echo '<input type="hidden" name="result[]" value="'. $value. '">';
}

And you will get $_POST['result'] as an array.

print_r($_POST['result']);

Free Rest API to retrieve current datetime as string (timezone irrelevant)

If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.

Check an integer value is Null in c#

Simply you can do this:

    public void CheckNull(int? item)
    {
        if (item != null)
        {
            //Do Something
        }

    }

jQuery: Setting select list 'selected' based on text, failing strangely

We can do it by searching the text in options of dropdown list and then by setting selected attribute to true.

This code is run in every environment.

 $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected');

.Net picking wrong referenced assembly version

I had the same message when switching between two versions of an application that referenced different versions of the same DLL. Although I was testing in different folders I accidentally copied the newer version over the older version.

So the first thing to check is the version of the referenced DLL in the application's folder. Just in case.

C char array initialization

Edit: OP (or an editor) silently changed some of the single quotes in the original question to double quotes at some point after I provided this answer.

Your code will result in compiler errors. Your first code fragment:

char buf[10] ; buf = ''

is doubly illegal. First, in C, there is no such thing as an empty char. You can use double quotes to designate an empty string, as with:

char* buf = ""; 

That will give you a pointer to a NUL string, i.e., a single-character string with only the NUL character in it. But you cannot use single quotes with nothing inside them--that is undefined. If you need to designate the NUL character, you have to specify it:

char buf = '\0';

The backslash is necessary to disambiguate from character '0'.

char buf = 0;

accomplishes the same thing, but the former is a tad less ambiguous to read, I think.

Secondly, you cannot initialize arrays after they have been defined.

char buf[10];

declares and defines the array. The array identifier buf is now an address in memory, and you cannot change where buf points through assignment. So

buf =     // anything on RHS

is illegal. Your second and third code fragments are illegal for this reason.

To initialize an array, you have to do it at the time of definition:

char buf [10] = ' ';

will give you a 10-character array with the first char being the space '\040' and the rest being NUL, i.e., '\0'. When an array is declared and defined with an initializer, the array elements (if any) past the ones with specified initial values are automatically padded with 0. There will not be any "random content".

If you declare and define the array but don't initialize it, as in the following:

char buf [10];

you will have random content in all the elements.

How do I run a docker instance from a DockerFile?

While other answers were usable, this really helped me, so I am putting it also here.

From the documentation:

Instead of specifying a context, you can pass a single Dockerfile in the URL or pipe the file in via STDIN. To pipe a Dockerfile from STDIN:

$ docker build - < Dockerfile

With Powershell on Windows, you can run:

Get-Content Dockerfile | docker build -

When the build is done, run command:

docker image ls

You will see something like this:

REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
<none>                     <none>              123456789        39 seconds ago      422MB

Copy your actual IMAGE ID and then run

docker run 123456789

Where the number at the end is the actual Image ID from previous step

If you do not want to remember the image id, you can tag your image by

docker tag 123456789 pavel/pavel-build

Which will tag your image as pavel/pavel-build

All possible array initialization syntaxes

For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };

OpenCV - DLL missing, but it's not?

You just need to add the folder of the needed dll file (or files) to your system "Environment Variables" in "Path". Your problem will 100% be resolved. I had this problem too.

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

Can I run HTML files directly from GitHub, instead of just viewing their source?

i wanted to edit html and js in github and have a preview. i wanted to do it in github to have instant commits and saves.

tried rawgithub.com but rawgithub.com was not realtime (it's cache refreshes once a minute).

so i quickly developed my own solution:

node.js solution for this: https://github.com/shimondoodkin/rawgithub

Spark - Error "A master URL must be set in your configuration" when submitting an app

The default value of "spark.master" is spark://HOST:PORT, and the following code tries to get a session from the standalone cluster that is running at HOST:PORT, and expects the HOST:PORT value to be in the spark config file.

SparkSession spark = SparkSession
    .builder()
    .appName("SomeAppName")
    .getOrCreate();

"org.apache.spark.SparkException: A master URL must be set in your configuration" states that HOST:PORT is not set in the spark configuration file.

To not bother about value of "HOST:PORT", set spark.master as local

SparkSession spark = SparkSession
    .builder()
    .appName("SomeAppName")
    .config("spark.master", "local")
    .getOrCreate();

Here is the link for list of formats in which master URL can be passed to spark.master

Reference : Spark Tutorial - Setup Spark Ecosystem

Best place to insert the Google Analytics code

As google says:

Paste it into your web page, just before the closing </head> tag.

One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the <head> section, and we recommend placing the snippet at the bottom of the <head> section for best performance

Get yesterday's date in bash on Linux, DST-safe

I think this should work, irrespective of how often and when you run it ...

date -d "yesterday 13:00" '+%Y-%m-%d'

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

I'm running oracle xpress edition 11.2 on windows 8 and I had the same error when trying to connect to DB using sqldeveloper.

I've edited listener.ora as per Brandt answer above and even restarted my machine the issue wasn't fixed.

I've done the following: go to control panel -> administrative tools -> services you will find a service called "OracleServiceXE" not running.

I started it and tried to connect again, issue resolved.

How to reload or re-render the entire page using AngularJS

I got this working code for removing cache and reloading the page

View

        <a class="btn" ng-click="reload()">
            <i class="icon-reload"></i> 
        </a>

Controller

Injectors: $scope,$state,$stateParams,$templateCache

       $scope.reload = function() { // To Reload anypage
            $templateCache.removeAll();     
            $state.transitionTo($state.current, $stateParams, { reload: true, inherit: true, notify: true });
        };

Handling exceptions from Java ExecutorService tasks

If your ExecutorService comes from an external source (i. e. it's not possible to subclass ThreadPoolExecutor and override afterExecute()), you can use a dynamic proxy to achieve the desired behavior:

public static ExecutorService errorAware(final ExecutorService executor) {
    return (ExecutorService) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class[] {ExecutorService.class},
            (proxy, method, args) -> {
                if (method.getName().equals("submit")) {
                    final Object arg0 = args[0];
                    if (arg0 instanceof Runnable) {
                        args[0] = new Runnable() {
                            @Override
                            public void run() {
                                final Runnable task = (Runnable) arg0;
                                try {
                                    task.run();
                                    if (task instanceof Future<?>) {
                                        final Future<?> future = (Future<?>) task;

                                        if (future.isDone()) {
                                            try {
                                                future.get();
                                            } catch (final CancellationException ce) {
                                                // Your error-handling code here
                                                ce.printStackTrace();
                                            } catch (final ExecutionException ee) {
                                                // Your error-handling code here
                                                ee.getCause().printStackTrace();
                                            } catch (final InterruptedException ie) {
                                                Thread.currentThread().interrupt();
                                            }
                                        }
                                    }
                                } catch (final RuntimeException re) {
                                    // Your error-handling code here
                                    re.printStackTrace();
                                    throw re;
                                } catch (final Error e) {
                                    // Your error-handling code here
                                    e.printStackTrace();
                                    throw e;
                                }
                            }
                        };
                    } else if (arg0 instanceof Callable<?>) {
                        args[0] = new Callable<Object>() {
                            @Override
                            public Object call() throws Exception {
                                final Callable<?> task = (Callable<?>) arg0;
                                try {
                                    return task.call();
                                } catch (final Exception e) {
                                    // Your error-handling code here
                                    e.printStackTrace();
                                    throw e;
                                } catch (final Error e) {
                                    // Your error-handling code here
                                    e.printStackTrace();
                                    throw e;
                                }
                            }
                        };
                    }
                }
                return method.invoke(executor, args);
            });
}

UIBarButtonItem in navigation bar programmatically?

In Swift 3.0+, UIBarButtonItem programmatically set up as follows:

   override func viewDidLoad() {
        super.viewDidLoad()
        let testUIBarButtonItem = UIBarButtonItem(image: UIImage(named: "test.png"), style: .plain, target: self, action: #selector(self.clickButton))
        self.navigationItem.rightBarButtonItem  = testUIBarButtonItem
    }

   @objc func clickButton(){
            print("button click")
     }

Simple pthread! C++

Linkage. Try this:

extern "C" void *print_message() {...

How do I return an int from EditText? (Android)

For now, use an EditText. Use android:inputType="number" to force it to be numeric. Convert the resulting string into an integer (e.g., Integer.parseInt(myEditText.getText().toString())).

In the future, you might consider a NumberPicker widget, once that becomes available (slated to be in Honeycomb).

How to get name of calling function/method in PHP?

My favourite way, in one line!

debug_backtrace()[1]['function'];

You can use it like this:

echo 'The calling function: ' . debug_backtrace()[1]['function'];

Note that this is only compatible with versions of PHP released within the last year. But it's a good idea to keep your PHP up to date anyway for security reasons.

Passing multiple values for a single parameter in Reporting Services

So multiply text values would end up in the query with single quotes around each I used =join(Parameters!Customer.Value,"','"). So after ".Value" that is comma, double-quote, single-quote, comma, single-quote, double-quote, close-bracket. simples :)

Using JAXB to unmarshal/marshal a List<String>

In case anyone of you wants to write a list wrapper for lists containing elements of multiple classes and want to give an individual XmlElement name according to the Class type without Writing X Wrapper classes you could use the @XmlMixed annotation. By doing so JAXB names the items of the list according to the value set by the @XmlRootElement. When doing so you have to specify which classes could possibly be in the list using @XmlSeeAlso

Example:

Possible Classes in the list

@XmlRootElement(name="user")
public class User {/*...*/}

@XmlRootElement(name="entry")
public class LogEntry {/*...*/}

Wrapper class

@XmlRootElement(name="records")
@XmlSeeAlso({User.class, LogEntry.class})
public static class JaxbList<T>{

    protected List<T> records;

    public JaxbList(){}

    public JaxbList(List<T> list){
        this.records=list;
    }

    @XmlMixed 
    public List<T> getRecords(){
        return records;
    }
}

Example:

List l = new List();
l.add(new User("userA"));
l.add(new LogEntry(new UserB()));


XStream xStream = new XStream();
String result = xStream.toXML(l);

Result:

<records>
    <user>...</user>
    <entry>...</entry>
</records>

Alternatevily you could specify the XmlElement names directly inside the wrapper class using the @XmlElementRef annotation

@XmlRootElement(name="records")
@XmlSeeAlso({User.class, LogEntry.class})
public static class JaxbList<T>{

    protected List<T> records;

    public JaxbList(){}

    public JaxbList(List<T> list){
        this.records=list;
    }

    @XmlElementRefs({
        @XmlElementRef(name="item", type=Object.class),
        @XmlElementRef(name="user", type=User.class),
        @XmlElementRef(name="entry", type=LogEntry.class)
    })
    public List<T> getRecords(){
        return records;
    }
}

Creating for loop until list.length

In Python you can iterate over the list itself:

for item in my_list:
   #do something with item

or to use indices you can use xrange():

for i in xrange(1,len(my_list)):    #as indexes start at zero so you 
                                    #may have to use xrange(len(my_list))
    #do something here my_list[i]

There's another built-in function called enumerate(), which returns both item and index:

for index,item in enumerate(my_list):
    # do something here

examples:

In [117]: my_lis=list('foobar')

In [118]: my_lis
Out[118]: ['f', 'o', 'o', 'b', 'a', 'r']

In [119]: for item in my_lis:
    print item
   .....:     
f
o
o
b
a
r

In [120]: for i in xrange(len(my_lis)):
    print my_lis[i]
   .....:     
f
o
o
b
a
r

In [122]: for index,item in enumerate(my_lis):
    print index,'-->',item
   .....:     
0 --> f
1 --> o
2 --> o
3 --> b
4 --> a
5 --> r

How do you run a Python script as a service in Windows?

pysc: Service Control Manager on Python

Example script to run as a service taken from pythonhosted.org:

from xmlrpc.server import SimpleXMLRPCServer

from pysc import event_stop


class TestServer:

    def echo(self, msg):
        return msg


if __name__ == '__main__':
    server = SimpleXMLRPCServer(('127.0.0.1', 9001))

    @event_stop
    def stop():
        server.server_close()

    server.register_instance(TestServer())
    server.serve_forever()

Create and start service

import os
import sys
from xmlrpc.client import ServerProxy

import pysc


if __name__ == '__main__':
    service_name = 'test_xmlrpc_server'
    script_path = os.path.join(
        os.path.dirname(__file__), 'xmlrpc_server.py'
    )
    pysc.create(
        service_name=service_name,
        cmd=[sys.executable, script_path]
    )
    pysc.start(service_name)

    client = ServerProxy('http://127.0.0.1:9001')
    print(client.echo('test scm'))

Stop and delete service

import pysc

service_name = 'test_xmlrpc_server'

pysc.stop(service_name)
pysc.delete(service_name)
pip install pysc

Convert NSArray to NSString in Objective-C

NSString * str = [componentsJoinedByString:@""];

and you have dic or multiple array then used bellow

NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];   

JQuery Number Formatting

I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. Could be usefull.

number_format = function (number, decimals, dec_point, thousands_sep) {
        number = number.toFixed(decimals);

        var nstr = number.toString();
        nstr += '';
        x = nstr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? dec_point + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

        return x1 + x2;
    }

For example:

var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56

Verify ImageMagick installation

Remember that after installing Imagick (or indeed any PHP module) you need to restart your web server and/or php-fpm if you're using it, for the module to appear in phpinfo().

fatal error: iostream.h no such file or directory

You should be using iostream without the .h.

Early implementations used the .h variants but the standard mandates the more modern style.

What do I use for a max-heap implementation in Python?

Following up to Isaac Turner's excellent answer, I'd like put an example based on K Closest Points to the Origin using max heap.

from math import sqrt
import heapq


class MaxHeapObj(object):
    def __init__(self, val):
        self.val = val.distance
        self.coordinates = val.coordinates

    def __lt__(self, other):
        return self.val > other.val

    def __eq__(self, other):
        return self.val == other.val

    def __str__(self):
        return str(self.val)


class MinHeap(object):
    def __init__(self):
        self.h = []

    def heappush(self, x):
        heapq.heappush(self.h, x)

    def heappop(self):
        return heapq.heappop(self.h)

    def __getitem__(self, i):
        return self.h[i]

    def __len__(self):
        return len(self.h)


class MaxHeap(MinHeap):
    def heappush(self, x):
        heapq.heappush(self.h, MaxHeapObj(x))

    def heappop(self):
        return heapq.heappop(self.h).val

    def peek(self):
        return heapq.nsmallest(1, self.h)[0].val

    def __getitem__(self, i):
        return self.h[i].val


class Point():
    def __init__(self, x, y):
        self.distance = round(sqrt(x**2 + y**2), 3)
        self.coordinates = (x, y)


def find_k_closest(points, k):
    res = [Point(x, y) for (x, y) in points]
    maxh = MaxHeap()

    for i in range(k):
        maxh.heappush(res[i])

    for p in res[k:]:
        if p.distance < maxh.peek():
            maxh.heappop()
            maxh.heappush(p)

    res = [str(x.coordinates) for x in maxh.h]
    print(f"{k} closest points from origin : {', '.join(res)}")


points = [(10, 8), (-2, 4), (0, -2), (-1, 0), (3, 5), (-2, 3), (3, 2), (0, 1)]
find_k_closest(points, 3)

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

Suggestion 1

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

Example route configuration

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

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

Example check for the custom module property

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

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

Suggestion 2

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

Value publicStates

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

Value privateStates

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

The Helper

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

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

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

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

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

Note: the code above isn't tested

How do I prevent Eclipse from hanging on startup?

I used eclipse -clean -clearPersistedState and that worked for me.

Warning: This may remove all projects from the workspace.

Converting Integer to String with comma for thousands

This is a way that also able you to replace default separator with any characters:

val myNumber = NumberFormat.getNumberInstance(Locale.US)
   .format(123456789)
   .replace(",", "?")

Bootstrap - Removing padding or margin when screen size is smaller

I have had this problem occur on sites that used similar formatting and code and I have racked my brain over what was the missing detail that made some of my sites work, and some not.

For Bootstrap 3: The answer for me was not in rewriting css for .container-fluid, .row or resetting margins, the consistent pattern that I realized was the length of longer words were throwing off the design and creating margins.

The solution steps:

  1. Test your page by temporarily deleting sections that contain containers and test your site on small browsers. This will identify your problem container.

  2. You may have a div formatting problem. If you do, fix it. If all is well then:

  3. Identify if you have used long words that are not wrapping. If you cannot change the word (like for tag lines or slogans, etc.)

Solution 1: Format the font to smaller size in your media query for smaller screen (I usually find @media (max-width: 767px) to be sufficient).

OR:

Solution 2:

@media (max-width: 767px){

h1, h2, h3 {word-wrap: break-word;}
}

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

How to add an extra language input to Android?

I just found Scandinavian Keyboard as a fine solution to this problem. It do also have English and German keyboard, but neither Dutch nor Spanish - but I guess they could be added. And I guess there is other alternatives out there.

Javascript loading CSV file into an array

You can't use AJAX to fetch files from the user machine. This is absolutely the wrong way to go about it.

Use the FileReader API:

<input type="file" id="file input">

js:

console.log(document.getElementById("file input").files); // list of File objects

var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);
console.log(content);

Then parse content as CSV. Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4"""

Explanation of BASE terminology

It has to do with BASE: the BASE jumper kind is always Basically Available (to new relationships), in a Soft state (none of his relationship last very long) and Eventually consistent (one day he will get married).

Change the mouse pointer using JavaScript

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.

document.body.style.cursor = 'wait';

PHP foreach change original array values

Try this

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }

Pentaho Data Integration SQL connection

Missing driver file.

This error is really common for people just getting started with PDI.

Drivers go in \pentaho\design-tools\data-integration\libext\JDBC for PDI. If you are using other tools in the Pentaho suite, you may need to copy drivers to additional locations for those tools. For reference, here are the appropriate folders for some of the other design tools:

  • Aggregation Designer: \pentaho\design-tools\aggregation-designer\drivers
  • Metadata Editor: \pentaho\design-tools\metadata-editor\libext\JDBC
  • Report Designer: \pentaho\design-tools\report-designer\lib\jdbc
  • Schema Workbench: \pentaho\design-tools\schema-workbench\drivers

If this transformation or job will run on another box, such as a test or production server, don't forget to include copying the jar file and restarting PDI or the Data Integration Server in your deployment considerations.

How to encrypt/decrypt data in php?

It took me quite a while to figure out, how to not get a false when using openssl_decrypt() and get encrypt and decrypt working.

    // cryptographic key of a binary string 16 bytes long (because AES-128 has a key size of 16 bytes)
    $encryption_key = '58adf8c78efef9570c447295008e2e6e'; // example
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = openssl_encrypt($plaintext, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);
    $encrypted = $encrypted . ':' . base64_encode($iv);

    // decrypt to get again $plaintext
    $parts = explode(':', $encrypted);
    $decrypted = openssl_decrypt($parts[0], 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, base64_decode($parts[1])); 

If you want to pass the encrypted string via a URL, you need to urlencode the string:

    $encrypted = urlencode($encrypted);

To better understand what is going on, read:

To generate 16 bytes long keys you can use:

    $bytes = openssl_random_pseudo_bytes(16);
    $hex = bin2hex($bytes);

To see error messages of openssl you can use: echo openssl_error_string();

Hope that helps.

How can I de-install a Perl module installed via `cpan`?

You can't. There isn't a feature in my CPAN client to do such a thing. We were talking about how we might do something like that at this weekend's Perl QA Workshop, but it's generally hard for all the reasons that Ether mentioned.